blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
68ab5ec9be6ec50944ef68e6d6d5b04de37a480b | 902aab58f902a488a4f0f0e8e0d6b0bab8334240 | /InProgress/CavityRefine/case/system/refineMeshDict | 8435e5bd43a4645b523608dc2fe6df97fb1f1837 | [] | no_license | Foadsf/OpenFOAM_Tutorials_ | d32d5ef6583f276018f2314a78fe66c730c47109 | 4b914e5112863f2660e15b899dfddfc0ec04f90c | refs/heads/master | 2021-09-12T08:19:21.666536 | 2018-01-24T17:31:13 | 2018-01-24T17:31:13 | 118,747,914 | 1 | 0 | null | 2018-01-24T10:10:08 | 2018-01-24T10:10:08 | null | UTF-8 | C++ | false | false | 2,070 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class dictionary;
location "system";
object refineMeshDict;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// Cells to refine; name of 'cellSet'
set cellZone_1;
// Type of coordinate system:
// - global : coordinate system same for every cell. Usually aligned with
// x,y,z axis. Specify in globalCoeffs section below.
// - patchLocal : coordinate system different for every cell. Specify in
// patchLocalCoeffs section below.
coordinateSystem global;
// Specifies 2 directions by a name and a vector. The normal direction is
// calculated as tan1^tan2
globalCoeffs
{
tan1 ( 1 0 0 );
tan2 ( 0 1 0 );
}
patchLocalCoeffs
{
// Normal direction is face normal of zero'th face of patch
patch outside;
tan1 ( 1 0 0 );
tan2 ( 0 0 1 );
}
// Specifies the direction to be refined by the name used above
// To refine in the third direction, use the keyword 'normal'
directions
(
tan1
normal
);
// Whether to use hex topology. This will
// - if patchLocal: all cells on selected patch should be hex
// - split all hexes in 2x2x2 through the middle of edges.
useHexTopology yes;
// Cut purely geometric (will cut hexes through vertices) or take
// topology into account. Incompatible with 'useHexTopology'
geometricCut no;
// Write meshes from intermediate steps
writeMesh no; | [
"[email protected]"
] | ||
cad5d2c2e4b55396db9c5ff1e384aff2a66035f4 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5648941810974720_1/C++/Paradox1/test3.cpp | 3eaaa6c57cc19ba9f94ac16963cbf61e0bfb9894 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,452 | cpp | //Mitesh Agrawal
#include <bits/stdc++.h>
using namespace std;
#define gc getchar
#define pi(n) printf("%d",n)
#define pin(n) printf("%d\n",n)
#define pis(n) printf("%d ",n)
#define pll(n) printf("%d",n)
#define plls(n) printf("%lld ",n)
#define plln(n) printf("%lld\n",n)
#define ps printf(" ")
#define pn printf("\n")
#define si(n) scanf("%d",&n)
#define sii(n,m) scanf("%d %d",&n,&m)
#define siii(k,n,m) scanf("%d %d %d",&k,&n,&m)
#define rep(i,n) for(i=0;i<n;i++)
#define fu(i,a,n) for(i=a;i<=n;i++)
#define fd(i,n,a) for(i=n;i>=a;i--)
#define ll long long
#define ii pair<ll,ll>
#define iii pair<ii,ll>
#define ff first
#define ss second
#define mod 1000000007
#define MAXN 100005
int main()
{
freopen ("A-large.in","r",stdin);
freopen ("A-large.out","w",stdout);
int i,j,n,t,l,qw,mini;
string s;
si(t);
fu(qw,1,t){
cin>>s;
map<char,int> m;
vector<int> v(10);
l=s.size();
rep(i,l)
m[s[i]]++;
v[0]=m['Z'];
v[2]=m['W'];
v[4]=m['U'];
v[6]=m['X'];
v[8]=m['G'];
v[1]=m['O']-v[2]-v[4]-v[0];
v[3]=m['H']-v[8];
v[5]=m['F']-v[4];
v[7]=m['S']-v[6];
v[9]=m['I']-v[5]-v[6]-v[8];
printf("Case #%d: ",qw);
rep(i,10){
rep(j,v[i])
pi(i);
}pn;
}
return 0;
} | [
"[email protected]"
] | |
2765d8e12b3e89b0dc4f41b01e73ecc5d5aeb22b | fe6360bf697243c6c318836a3c64a9c1984b610b | /deprecated/physiCal/include/shape/shape.line.h | 8477ec2a9665a3fbdf9214206e0b9cb3c948832a | [] | no_license | davidmueller13/vexx | 366cec96f4abac2e814176cd5d2ae75393561c0d | 9194877951c78cd3fde3e7fbe6d511e40c24f8eb | refs/heads/master | 2021-01-10T11:51:19.124071 | 2015-09-26T15:30:05 | 2015-09-26T15:30:05 | 43,210,604 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,000 | h | #ifndef SHAPE_LINE_H
#define SHAPE_LINE_H
#include "shape/shape.types.h"
BEGIN_PHYSICAL_NAMESPACE
class PHYSICAL_EXPORT line
{
public:
//! Position of the line
pVector position;
//! The direction of the line
pVector direction;
//! Initiate from a point and a vector
line( pVector=pVector(), pVector=pVector() );
~line();
//! Find whether a point lies on the line
bool liesOn( pVector );
//! Sample this line at t
pVector sample( pReal );
//! Returns the shortest distance to a point
pReal shortestDistance( pVector );
//! Check for the shortest distance between a line and this line
pReal shortestDistance( line );
//! Return the t for this line at which this line is closest to the given line
pReal collision( line );
//! Return the t for this line at which this line is closest to the given line
pReal collision( pVector );
};
line lineToSpace( line, jLib::math::matrix4x4 );
END_PHYSICAL_NAMESPACE
#endif
| [
"jorjpimm@e3525c50-fa1a-11de-8c8a-61c5e9addfc9"
] | jorjpimm@e3525c50-fa1a-11de-8c8a-61c5e9addfc9 |
87aa44104fcb3fa1d3d263cebc4c67b61c0f6597 | 7d81e3fe487ff012f630fc602d9b94e6e428bf21 | /include/openMVG/multiview/two_view_kernel.hpp | 15fa1cf7fdf31bb01caca4e020f32b5f493ee894 | [] | no_license | MagicPixel/Linux_Tx2 | 8e71bd2c17e864afedbb7cf819afdb0d45e6f827 | 59fdc8c0ad303537ad076fcb4c3f525514d885f0 | refs/heads/master | 2020-05-16T09:28:57.420876 | 2019-04-30T03:15:04 | 2019-04-30T03:15:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,212 | hpp |
// Copyright (c) 2010 libmv authors.
//
// 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.
// Copyright (c) 2012, 2013 Pierre MOULON.
// 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/.
#ifndef OPENMVG_MULTIVIEW_TWO_VIEW_KERNEL_H_
#define OPENMVG_MULTIVIEW_TWO_VIEW_KERNEL_H_
#include <vector>
#include "openMVG/multiview/conditioning.hpp"
#include "openMVG/numeric/numeric.h"
namespace openMVG {
namespace two_view {
namespace kernel {
using namespace std;
// This is one example (targeted at solvers that operate on correspondences
// between two views) that shows the "kernel" part of a robust fitting
// problem:
//
// 1. The model; Mat3 in the case of the F or H matrix.
// 2. The minimum number of samples needed to fit; 7 or 8 (or 4).
// 3. A way to convert samples to a model.
// 4. A way to convert a sample and a model to an error.
//
// Of particular note is that the kernel does not expose what the samples are.
// All the robust fitting algorithm sees is that there is some number of
// samples; it is able to fit subsets of them (via the kernel) and check their
// error, but can never access the samples themselves.
//
// The Kernel objects must follow the following concept so that the robust
// fitting alogrithm can fit this type of relation:
//
// 1. Kernel::MAX_MODELS
// 2. Kernel::MINIMUM_SAMPLES
// 3. Kernel::Fit(vector<size_t>, vector<Kernel::Model> *)
// 4. Kernel::Error(size_t, Model) -> error
//
// The fit routine must not clear existing entries in the vector of models; it
// should append new solutions to the end.
template<typename SolverArg,
typename ErrorArg,
typename ModelArg = Mat3>
class Kernel {
public:
Kernel(const Mat &x1, const Mat &x2) : x1_(x1), x2_(x2) {}
typedef SolverArg Solver;
typedef ModelArg Model;
/// The minimal number of point required for the model estimation
enum { MINIMUM_SAMPLES = Solver::MINIMUM_SAMPLES };
/// The number of models that the minimal solver could return.
enum { MAX_MODELS = Solver::MAX_MODELS };
/// Extract required sample and fit model(s) to the sample
void Fit(const vector<size_t> &samples, vector<Model> *models) const {
Mat x1 = ExtractColumns(x1_, samples),
x2 = ExtractColumns(x2_, samples);
Solver::Solve(x1, x2, models);
}
/// Return the error associated to the model and sample^nth point
double Error(size_t sample, const Model &model) const {
return ErrorArg::Error(model, x1_.col(sample), x2_.col(sample));
}
/// Number of putative point
size_t NumSamples() const {
return x1_.cols();
}
/// Compute a model on sampled point
static void Solve(const Mat &x1, const Mat &x2, vector<Model> *models) {
// By offering this, Kernel types can be passed to templates.
Solver::Solve(x1, x2, models);
}
protected:
const Mat & x1_, & x2_; // Left/Right corresponding point
};
// Analog Normalized version of the previous Kernel.
template<typename SolverArg,
typename UnnormalizerArg,
typename ModelArg = Mat3>
class NormalizedSolver {
public:
enum { MINIMUM_SAMPLES = SolverArg::MINIMUM_SAMPLES };
enum { MAX_MODELS = SolverArg::MAX_MODELS };
static void Solve(const Mat &x1, const Mat &x2, vector<ModelArg> *models) {
assert(2 == x1.rows());
assert(MINIMUM_SAMPLES <= x1.cols());
assert(x1.rows() == x2.rows());
assert(x1.cols() == x2.cols());
// Normalize the data.
Mat3 T1, T2;
Mat x1_normalized, x2_normalized;
NormalizePoints(x1, &x1_normalized, &T1);
NormalizePoints(x2, &x2_normalized, &T2);
SolverArg::Solve(x1_normalized, x2_normalized, models);
// Unormalize model from the computed conditioning.
for (int i = 0; i < models->size(); ++i) {
UnnormalizerArg::Unnormalize(T1, T2, &(*models)[i]);
}
}
};
} // namespace kernel
} // namespace two_view
} // namespace openMVG
#endif // OPENMVG_MULTIVIEW_TWO_VIEW_KERNEL_H_
| [
"[email protected]"
] | |
a24b2e2279517515e50c60c5fc97a3d6e45fb88a | eb7b03bd2431a8244a9997179b2da074c589586c | /.history/200/Multiplication 2_20201205170945.cpp | 2cdc36085f4e90ba19158077d7c3c39ca440efc8 | [] | no_license | runes224/competitive-programming | f52e490bb1da9bc1d0e3c76f8383f53bf4b2b8f9 | 36f791eca638ebc1f78e384708db5d1693ca825b | refs/heads/master | 2023-06-01T09:08:42.112523 | 2021-07-11T05:51:09 | 2021-07-11T05:51:09 | 308,819,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i, c) for (int i = 0; i < (int)c; i++)
// typedef long long
const MX = 1e18;
int main()
{
int n;
cin >> n;
vector<long long> a(n);
rep(i, n) cin >> a[i];
long long ans = 1;
rep(i, n) {
if(a[i] == 0){
cout << 0 << endl;
return 0;
}
}
rep(i, n)
{
ans = ans * a[i];
if (ans > 1000000000000000000) {
cout << -1 << endl;
return 0;
}
};
cout << ans << endl;
return 0;
} | [
"[email protected]"
] | |
fab7b760a8bdf5f8456194afcc39cdc2a851b0cc | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /content/renderer/pepper/pepper_plugin_instance_metrics.cc | 34a87fb5a7fab18d6c035b1a9510fe36b12d5ea2 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 2,530 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/renderer/pepper/pepper_plugin_instance_metrics.h"
#include <stddef.h>
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "build/build_config.h"
#include "ppapi/shared_impl/ppapi_preferences.h"
#define UMA_HISTOGRAM_ASPECT_RATIO(name, width, height) \
base::UmaHistogramSparse( \
name, (height) ? ((width)*100) / (height) : kInfiniteRatio);
namespace content {
namespace {
// Histogram tracking prevalence of tiny Flash instances. Units in pixels.
enum PluginFlashTinyContentSize {
TINY_CONTENT_SIZE_1_1 = 0,
TINY_CONTENT_SIZE_5_5 = 1,
TINY_CONTENT_SIZE_10_10 = 2,
TINY_CONTENT_SIZE_LARGE = 3,
TINY_CONTENT_SIZE_NUM_ITEMS
};
const int kInfiniteRatio = 99999;
const char kFlashClickSizeAspectRatioHistogram[] =
"Plugin.Flash.ClickSize.AspectRatio";
const char kFlashClickSizeHeightHistogram[] = "Plugin.Flash.ClickSize.Height";
const char kFlashClickSizeWidthHistogram[] = "Plugin.Flash.ClickSize.Width";
const char kFlashTinyContentSizeHistogram[] = "Plugin.Flash.TinyContentSize";
} // namespace
void RecordFlashSizeMetric(int width, int height) {
PluginFlashTinyContentSize size = TINY_CONTENT_SIZE_LARGE;
if (width <= 1 && height <= 1)
size = TINY_CONTENT_SIZE_1_1;
else if (width <= 5 && height <= 5)
size = TINY_CONTENT_SIZE_5_5;
else if (width <= 10 && height <= 10)
size = TINY_CONTENT_SIZE_10_10;
UMA_HISTOGRAM_ENUMERATION(kFlashTinyContentSizeHistogram, size,
TINY_CONTENT_SIZE_NUM_ITEMS);
}
void RecordFlashClickSizeMetric(int width, int height) {
base::HistogramBase* width_histogram = base::LinearHistogram::FactoryGet(
kFlashClickSizeWidthHistogram,
0, // minimum width
500, // maximum width
100, // number of buckets.
base::HistogramBase::kUmaTargetedHistogramFlag);
width_histogram->Add(width);
base::HistogramBase* height_histogram = base::LinearHistogram::FactoryGet(
kFlashClickSizeHeightHistogram,
0, // minimum height
400, // maximum height
100, // number of buckets.
base::HistogramBase::kUmaTargetedHistogramFlag);
height_histogram->Add(height);
UMA_HISTOGRAM_ASPECT_RATIO(kFlashClickSizeAspectRatioHistogram, width,
height);
}
} // namespace content
| [
"[email protected]"
] | |
4fdb4b4b453290a86c2a575c4f8062a86fa02f8f | cf2ed0195fa168da120dcc6c8a0fe31eb919af1a | /FirstGame/Classes/AppDelegate.cpp | 1498850ba1f0a41ecca60fc7481fdcc7f5967df5 | [] | no_license | jubirosaiko/cocos2d-x_projects | 6b42be791d86d4fd971a3b043e7a430fd39eca28 | 9b1dd0d55bf9519461b7945c1015322c0946c32a | refs/heads/master | 2021-01-10T09:28:52.501054 | 2016-02-18T10:34:11 | 2016-02-18T10:34:11 | 51,996,578 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,655 | cpp | #include "AppDelegate.h"
#include "HelloWorldScene.h"
#include"scene/Title/TitleScene.h"
#include"scene/Splash/SplashScene.h"
USING_NS_CC;
static cocos2d::Size designResolutionSize = cocos2d::Size(1024, 512);
static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320);
static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768);
static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536);
AppDelegate::AppDelegate() {
}
AppDelegate::~AppDelegate()
{
}
//if you want a different context,just modify the value of glContextAttrs
//it will takes effect on all platforms
void AppDelegate::initGLContextAttrs()
{
//set OpenGL context attributions,now can only set six attributions:
//red,green,blue,alpha,depth,stencil
GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8};
GLView::setGLContextAttrs(glContextAttrs);
}
// If you want to use packages manager to install more packages,
// don't modify or remove this function
static int register_all_packages()
{
return 0; //flag for packages manager
}
bool AppDelegate::applicationDidFinishLaunching() {
// initialize director
auto director = Director::getInstance();
auto glview = director->getOpenGLView();
if(!glview) {
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX)
glview = GLViewImpl::createWithRect("TestPro", Rect(0, 0, designResolutionSize.width, designResolutionSize.height));
#else
glview = GLViewImpl::create("TestPro");
#endif
director->setOpenGLView(glview);
}
// turn on display FPS
director->setDisplayStats(false);
// set FPS. the default value is 1.0/60 if you don't call this
director->setAnimationInterval(1.0 / 60);
// Set the design resolution
glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER);
Size frameSize = glview->getFrameSize();
// if the frame's height is larger than the height of medium size.
if (frameSize.height > mediumResolutionSize.height)
{
director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width));
}
// if the frame's height is larger than the height of small size.
else if (frameSize.height > smallResolutionSize.height)
{
director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width));
}
// if the frame's height is smaller than the height of medium size.
else
{
director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width));
}
register_all_packages();
// create a scene. it's an autorelease object
auto scene = Splash::createScene();
// run
director->runWithScene(scene);
return true;
}
// This function will be called when the app is inactive. When comes a phone call,it's be invoked too
void AppDelegate::applicationDidEnterBackground() {
Director::getInstance()->stopAnimation();
// if you use SimpleAudioEngine, it must be pause
// SimpleAudioEngine::getInstance()->pauseBackgroundMusic();
}
// this function will be called when the app is active again
void AppDelegate::applicationWillEnterForeground() {
Director::getInstance()->startAnimation();
// if you use SimpleAudioEngine, it must resume here
// SimpleAudioEngine::getInstance()->resumeBackgroundMusic();
}
| [
"[email protected]"
] | |
77c391fa6a4fd45176c711cb653c573d01df6218 | e9cf9f371e7e03c0a8988b82df9a0a463ef6f5ed | /SampleAIs/InputTestAI.cc | 1805e1cd95badfb6b3ef523fa1f6f97d4834ec03 | [
"Apache-2.0"
] | permissive | AI-comp/JavaChallenge2015 | 4e8580c5a462c1d515f2c756a10d736c8faf7a2b | db5aa667b5cba74eac45d3d679a477e7c7f1e4bd | refs/heads/master | 2016-09-01T15:40:57.601983 | 2015-12-02T01:28:59 | 2015-12-02T01:28:59 | 43,115,486 | 0 | 4 | null | 2017-03-28T01:40:01 | 2015-09-25T07:13:51 | Java | UTF-8 | C++ | false | false | 643 | cc | /*
* EODが来るまで入力を受け取り続け、その内容をtest.txtに保存するAI
*/
#include <iostream>
#include <random>
#include <fstream>
using namespace std;
const string commands = "URDLA";
int board[40][40];
int life[4];
int turn;
int x[4];
int y[4];
string dir[4];
int main() {
ofstream outputfile;
outputfile.open("test.txt");
cout << "Ready" << endl;
random_device rnd;
while (true) {
string eod;
while (true) {
cin >> eod;
outputfile << eod << " ";
if (eod == "EOD") {
outputfile << endl;
break;
}
}
int c = rnd() % commands.size();
cout << commands[c] << endl;
}
return 0;
}
| [
"[email protected]"
] | |
d75d6eddf779ed0791b4026ac0595eaa98bb700e | 509e9d64744f720392fda2b978d783f985c60824 | /opencv-2.4.11/include/opencv2/stitching/detail/util.hpp | cfd68a61e2a4d7ec8672bb49db601f5e9bdc2acd | [] | no_license | theideasmith/Instant-OpenCV-FFMPEG | 0560598fba630ded533b4e6c111c61c9b0b7502b | 234e359af245b4832b3e7ade6070e91c81b65de0 | refs/heads/master | 2021-01-11T20:39:33.443984 | 2017-01-16T23:09:46 | 2017-01-16T23:09:46 | 79,162,330 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 129 | hpp | version https://git-lfs.github.com/spec/v1
oid sha256:46b4847b4e2d8bbaf52273145e50702d6f734a7300029fd938ae6531a07c9607
size 5563
| [
"[email protected]"
] | |
be2ba15cc9affa17946a836209cad9e1329a178b | 24bc4990e9d0bef6a42a6f86dc783785b10dbd42 | /components/reporting/client/report_queue_factory.cc | db0fd2686467dff5c1af8ca0c013874103de2b7b | [
"BSD-3-Clause"
] | permissive | nwjs/chromium.src | 7736ce86a9a0b810449a3b80a4af15de9ef9115d | 454f26d09b2f6204c096b47f778705eab1e3ba46 | refs/heads/nw75 | 2023-08-31T08:01:39.796085 | 2023-04-19T17:25:53 | 2023-04-19T17:25:53 | 50,512,158 | 161 | 201 | BSD-3-Clause | 2023-05-08T03:19:09 | 2016-01-27T14:17:03 | null | UTF-8 | C++ | false | false | 3,953 | cc | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/reporting/client/report_queue_factory.h"
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/strings/string_piece.h"
#include "base/task/bind_post_task.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/thread_pool.h"
#include "components/reporting/client/report_queue_configuration.h"
#include "components/reporting/client/report_queue_provider.h"
#include "components/reporting/util/backoff_settings.h"
#include "net/base/backoff_entry.h"
#define LOG_WITH_STATUS(LEVEL, MESSAGE, STATUS) \
VLOG(LEVEL) << MESSAGE << " status=" << STATUS.status();
namespace reporting {
// static
void ReportQueueFactory::Create(EventType event_type,
Destination destination,
SuccessCallback success_cb,
int64_t reserved_space) {
DCHECK(base::SequencedTaskRunner::HasCurrentDefault());
auto config_result = ReportQueueConfiguration::Create(
event_type, destination,
base::BindRepeating([]() { return Status::StatusOK(); }), reserved_space);
if (!config_result.ok()) {
LOG_WITH_STATUS(1, "ReportQueueConfiguration is invalid.", config_result);
return;
}
// Asynchronously create and try to set ReportQueue.
auto try_set_cb = CreateTrySetCallback(destination, std::move(success_cb),
GetBackoffEntry());
base::ThreadPool::PostTask(
FROM_HERE, base::BindOnce(ReportQueueProvider::CreateQueue,
std::move(config_result.ValueOrDie()),
std::move(try_set_cb)));
}
// static
std::unique_ptr<ReportQueue, base::OnTaskRunnerDeleter>
ReportQueueFactory::CreateSpeculativeReportQueue(EventType event_type,
Destination destination,
int64_t reserved_space) {
DCHECK(base::SequencedTaskRunner::HasCurrentDefault());
auto config_result = ReportQueueConfiguration::Create(
event_type, destination,
base::BindRepeating([]() { return Status::StatusOK(); }), reserved_space);
if (!config_result.ok()) {
DVLOG(1)
<< "Cannot initialize report queue. Invalid ReportQueueConfiguration: "
<< config_result.status();
return std::unique_ptr<ReportQueue, base::OnTaskRunnerDeleter>(
nullptr, base::OnTaskRunnerDeleter(
base::SequencedTaskRunner::GetCurrentDefault()));
}
auto speculative_queue_result = ReportQueueProvider::CreateSpeculativeQueue(
std::move(config_result.ValueOrDie()));
if (!speculative_queue_result.ok()) {
DVLOG(1) << "Failed to create speculative queue: "
<< speculative_queue_result.status();
return std::unique_ptr<ReportQueue, base::OnTaskRunnerDeleter>(
nullptr, base::OnTaskRunnerDeleter(
base::SequencedTaskRunner::GetCurrentDefault()));
}
return std::move(speculative_queue_result.ValueOrDie());
}
ReportQueueFactory::TrySetReportQueueCallback
ReportQueueFactory::CreateTrySetCallback(
Destination destination,
SuccessCallback success_cb,
std::unique_ptr<::net::BackoffEntry> backoff_entry) {
return base::BindPostTaskToCurrentDefault(base::BindOnce(
&ReportQueueFactory::TrySetReportQueue, std::move(success_cb)));
}
// static
void ReportQueueFactory::TrySetReportQueue(
SuccessCallback success_cb,
StatusOr<std::unique_ptr<ReportQueue>> report_queue_result) {
if (!report_queue_result.ok()) {
LOG_WITH_STATUS(1, "ReportQueue could not be created.",
report_queue_result);
return;
}
std::move(success_cb).Run(std::move(report_queue_result.ValueOrDie()));
}
} // namespace reporting
| [
"[email protected]"
] | |
526b10a7fba6b289cd313aebc492e9bbdf7c961a | 78918391a7809832dc486f68b90455c72e95cdda | /boost_lib/boost/polygon/detail/scan_arbitrary.hpp | a82876e920b558581ffa30613a686828a2cddf76 | [
"MIT"
] | permissive | kyx0r/FA_Patcher | 50681e3e8bb04745bba44a71b5fd04e1004c3845 | 3f539686955249004b4483001a9e49e63c4856ff | refs/heads/master | 2022-03-28T10:03:28.419352 | 2020-01-02T09:16:30 | 2020-01-02T09:16:30 | 141,066,396 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 136,705 | hpp | /*
Copyright 2008 Intel Corporation
Use, modification and distribution are subject to the Boost Software License,
Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
http://www.boost.org/LICENSE_1_0.txt).
*/
#ifndef BOOST_POLYGON_SCAN_ARBITRARY_HPP
#define BOOST_POLYGON_SCAN_ARBITRARY_HPP
#ifdef BOOST_POLYGON_DEBUG_FILE
#include <fstream>
#endif
#include "polygon_sort_adaptor.hpp"
namespace boost
{
namespace polygon
{
template <typename Unit>
class line_intersection : public scanline_base<Unit>
{
private:
typedef typename scanline_base<Unit>::Point Point;
//the first point is the vertex and and second point establishes the slope of an edge eminating from the vertex
//typedef std::pair<Point, Point> half_edge;
typedef typename scanline_base<Unit>::half_edge half_edge;
//scanline comparator functor
typedef typename scanline_base<Unit>::less_half_edge less_half_edge;
typedef typename scanline_base<Unit>::less_point less_point;
//when parallel half edges are encounterd the set of segments is expanded
//when a edge leaves the scanline it is removed from the set
//when the set is empty the element is removed from the map
typedef int segment_id;
typedef std::pair<half_edge, std::set<segment_id> > scanline_element;
typedef std::map<half_edge, std::set<segment_id>, less_half_edge> edge_scanline;
typedef typename edge_scanline::iterator iterator;
// std::map<Unit, std::set<segment_id> > vertical_data_;
// edge_scanline edge_scanline_;
// Unit x_;
// int just_before_;
// segment_id segment_id_;
// std::vector<std::pair<half_edge, int> > event_edges_;
// std::set<Point> intersection_queue_;
public:
// inline line_intersection() : vertical_data_(), edge_scanline_(), x_((std::numeric_limits<Unit>::max)()), just_before_(0), segment_id_(0), event_edges_(), intersection_queue_() {
// less_half_edge lessElm(&x_, &just_before_);
// edge_scanline_ = edge_scanline(lessElm);
// }
// inline line_intersection(const line_intersection& that) : vertical_data_(), edge_scanline_(), x_(), just_before_(), segment_id_(), event_edges_(), intersection_queue_() { (*this) = that; }
// inline line_intersection& operator=(const line_intersection& that) {
// x_ = that.x_;
// just_before_ = that.just_before_;
// segment_id_ = that.segment_id_;
// //I cannot simply copy that.edge_scanline_ to this edge_scanline_ becuase the functor store pointers to other members!
// less_half_edge lessElm(&x_, &just_before_);
// edge_scanline_ = edge_scanline(lessElm);
// edge_scanline_.insert(that.edge_scanline_.begin(), that.edge_scanline_.end());
// return *this;
// }
// static inline void between(Point pt, Point pt1, Point pt2) {
// less_point lp;
// if(lp(pt1, pt2))
// return lp(pt, pt2) && lp(pt1, pt);
// return lp(pt, pt1) && lp(pt2, pt);
// }
template <typename iT>
static inline void compute_histogram_in_y(iT begin, iT end, std::size_t size, std::vector<std::pair<Unit, std::pair<std::size_t, std::size_t> > >& histogram)
{
std::vector<std::pair<Unit, int> > ends;
ends.reserve(size * 2);
for(iT itr = begin ; itr != end; ++itr)
{
int count = (*itr).first.first.y() < (*itr).first.second.y() ? 1 : -1;
ends.push_back(std::make_pair((*itr).first.first.y(), count));
ends.push_back(std::make_pair((*itr).first.second.y(), -count));
}
polygon_sort(ends.begin(), ends.end());
histogram.reserve(ends.size());
histogram.push_back(std::make_pair(ends.front().first, std::make_pair(0, 0)));
for(typename std::vector<std::pair<Unit, int> >::iterator itr = ends.begin(); itr != ends.end(); ++itr)
{
if((*itr).first != histogram.back().first)
{
histogram.push_back(std::make_pair((*itr).first, histogram.back().second));
}
if((*itr).second < 0)
histogram.back().second.second -= (*itr).second;
histogram.back().second.first += (*itr).second;
}
}
template <typename iT>
static inline void compute_y_cuts(std::vector<Unit>& y_cuts, iT begin, iT end, std::size_t size)
{
if(begin == end) return;
if(size < 30) return; //30 is empirically chosen, but the algorithm is not sensitive to this constant
std::size_t min_cut = size;
iT cut = begin;
std::size_t position = 0;
std::size_t cut_size = 0;
std::size_t histogram_size = std::distance(begin, end);
for(iT itr = begin; itr != end; ++itr, ++position)
{
if(position < histogram_size / 3)
continue;
if(histogram_size - position < histogram_size / 3) break;
if((*itr).second.first < min_cut)
{
cut = itr;
min_cut = (*cut).second.first;
cut_size = position;
}
}
if(cut_size == 0 || (*cut).second.first > size / 9) //nine is empirically chosen
return;
compute_y_cuts(y_cuts, begin, cut, (*cut).second.first + (*cut).second.second);
y_cuts.push_back((*cut).first);
compute_y_cuts(y_cuts, cut, end, size - (*cut).second.second);
}
template <typename iT>
static inline void validate_scan_divide_and_conquer(std::vector<std::set<Point> >& intersection_points,
iT begin, iT end)
{
std::vector<std::pair<Unit, std::pair<std::size_t, std::size_t> > > histogram;
compute_histogram_in_y(begin, end, std::distance(begin, end), histogram);
std::vector<Unit> y_cuts;
compute_y_cuts(y_cuts, histogram.begin(), histogram.end(), std::distance(begin, end));
std::map<Unit, std::vector<std::pair<half_edge, segment_id> > > bins;
bins[histogram.front().first] = std::vector<std::pair<half_edge, segment_id> >();
for(typename std::vector<Unit>::iterator itr = y_cuts.begin(); itr != y_cuts.end(); ++itr)
{
bins[*itr] = std::vector<std::pair<half_edge, segment_id> >();
}
for(iT itr = begin; itr != end; ++itr)
{
typename std::map<Unit, std::vector<std::pair<half_edge, segment_id> > >::iterator lb =
bins.lower_bound((std::min)((*itr).first.first.y(), (*itr).first.second.y()));
if(lb != bins.begin())
--lb;
typename std::map<Unit, std::vector<std::pair<half_edge, segment_id> > >::iterator ub =
bins.upper_bound((std::max)((*itr).first.first.y(), (*itr).first.second.y()));
for( ; lb != ub; ++lb)
{
(*lb).second.push_back(*itr);
}
}
validate_scan(intersection_points, bins[histogram.front().first].begin(), bins[histogram.front().first].end());
for(typename std::vector<Unit>::iterator itr = y_cuts.begin(); itr != y_cuts.end(); ++itr)
{
validate_scan(intersection_points, bins[*itr].begin(), bins[*itr].end(), *itr);
}
}
template <typename iT>
static inline void validate_scan(std::vector<std::set<Point> >& intersection_points,
iT begin, iT end)
{
validate_scan(intersection_points, begin, end, (std::numeric_limits<Unit>::min)());
}
//quadratic algorithm to do same work as optimal scan for cross checking
template <typename iT>
static inline void validate_scan(std::vector<std::set<Point> >& intersection_points,
iT begin, iT end, Unit min_y)
{
std::vector<Point> pts;
std::vector<std::pair<half_edge, segment_id> > data(begin, end);
for(std::size_t i = 0; i < data.size(); ++i)
{
if(data[i].first.second < data[i].first.first)
{
std::swap(data[i].first.first, data[i].first.second);
}
}
typename scanline_base<Unit>::compute_intersection_pack pack_;
polygon_sort(data.begin(), data.end());
//find all intersection points
for(typename std::vector<std::pair<half_edge, segment_id> >::iterator outer = data.begin();
outer != data.end(); ++outer)
{
const half_edge& he1 = (*outer).first;
//its own end points
pts.push_back(he1.first);
pts.push_back(he1.second);
std::set<Point>& segmentpts = intersection_points[(*outer).second];
for(typename std::set<Point>::iterator itr = segmentpts.begin(); itr != segmentpts.end(); ++itr)
{
if ((*itr).y() >= min_y)
{
pts.push_back(*itr);
}
}
bool have_first_y = he1.first.y() >= min_y && he1.second.y() >= min_y;
for(typename std::vector<std::pair<half_edge, segment_id> >::iterator inner = outer;
inner != data.end(); ++inner)
{
const half_edge& he2 = (*inner).first;
if(have_first_y || (he2.first.y() >= min_y && he2.second.y() >= min_y))
{
//at least one segment has a low y value within the range
if(he1 == he2) continue;
if((std::min)(he2. first.get(HORIZONTAL),
he2.second.get(HORIZONTAL)) >=
(std::max)(he1.second.get(HORIZONTAL),
he1.first.get(HORIZONTAL)))
break;
if(he1.first == he2.first || he1.second == he2.second)
continue;
Point intersection;
if(pack_.compute_intersection(intersection, he1, he2))
{
//their intersection point
pts.push_back(intersection);
intersection_points[(*inner).second].insert(intersection);
intersection_points[(*outer).second].insert(intersection);
}
}
}
}
polygon_sort(pts.begin(), pts.end());
typename std::vector<Point>::iterator newend = std::unique(pts.begin(), pts.end());
typename std::vector<Point>::iterator lfinger = pts.begin();
//find all segments that interact with intersection points
for(typename std::vector<std::pair<half_edge, segment_id> >::iterator outer = data.begin();
outer != data.end(); ++outer)
{
const half_edge& he1 = (*outer).first;
segment_id id1 = (*outer).second;
//typedef rectangle_data<Unit> Rectangle;
//Rectangle rect1;
//set_points(rect1, he1.first, he1.second);
//typename std::vector<Point>::iterator itr = lower_bound(pts.begin(), newend, (std::min)(he1.first, he1.second));
//typename std::vector<Point>::iterator itr2 = upper_bound(pts.begin(), newend, (std::max)(he1.first, he1.second));
Point startpt = (std::min)(he1.first, he1.second);
Point stoppt = (std::max)(he1.first, he1.second);
//while(itr != newend && itr != pts.begin() && (*itr).get(HORIZONTAL) >= (std::min)(he1.first.get(HORIZONTAL), he1.second.get(HORIZONTAL))) --itr;
//while(itr2 != newend && (*itr2).get(HORIZONTAL) <= (std::max)(he1.first.get(HORIZONTAL), he1.second.get(HORIZONTAL))) ++itr2;
//itr = pts.begin();
//itr2 = pts.end();
while(lfinger != newend && (*lfinger).x() < startpt.x()) ++lfinger;
for(typename std::vector<Point>::iterator itr = lfinger ; itr != newend && (*itr).x() <= stoppt.x(); ++itr)
{
if(scanline_base<Unit>::intersects_grid(*itr, he1))
intersection_points[id1].insert(*itr);
}
}
}
template <typename iT, typename property_type>
static inline void validate_scan(std::vector<std::pair<half_edge, std::pair<property_type, int> > >& output_segments,
iT begin, iT end)
{
std::vector<std::pair<property_type, int> > input_properties;
std::vector<std::pair<half_edge, int> > input_segments, intermediate_segments;
int index = 0;
for( ; begin != end; ++begin)
{
input_properties.push_back((*begin).second);
input_segments.push_back(std::make_pair((*begin).first, index++));
}
validate_scan(intermediate_segments, input_segments.begin(), input_segments.end());
for(std::size_t i = 0; i < intermediate_segments.size(); ++i)
{
output_segments.push_back(std::make_pair(intermediate_segments[i].first,
input_properties[intermediate_segments[i].second]));
less_point lp;
if(lp(output_segments.back().first.first, output_segments.back().first.second) !=
lp(input_segments[intermediate_segments[i].second].first.first,
input_segments[intermediate_segments[i].second].first.second))
{
//edge changed orientation, invert count on edge
output_segments.back().second.second *= -1;
}
if(!scanline_base<Unit>::is_vertical(input_segments[intermediate_segments[i].second].first) &&
scanline_base<Unit>::is_vertical(output_segments.back().first))
{
output_segments.back().second.second *= -1;
}
if(lp(output_segments.back().first.second, output_segments.back().first.first))
{
std::swap(output_segments.back().first.first, output_segments.back().first.second);
}
}
}
template <typename iT>
static inline void validate_scan(std::vector<std::pair<half_edge, int> >& output_segments,
iT begin, iT end)
{
std::vector<std::set<Point> > intersection_points(std::distance(begin, end));
validate_scan_divide_and_conquer(intersection_points, begin, end);
//validate_scan(intersection_points, begin, end);
segment_intersections(output_segments, intersection_points, begin, end);
// std::pair<segment_id, segment_id> offenders;
// if(!verify_scan(offenders, output_segments.begin(), output_segments.end())) {
// std::cout << "break here!\n";
// for(typename std::set<Point>::iterator itr = intersection_points[offenders.first].begin();
// itr != intersection_points[offenders.first].end(); ++itr) {
// std::cout << (*itr).x() << " " << (*itr).y() << " ";
// } std::cout << "\n";
// for(typename std::set<Point>::iterator itr = intersection_points[offenders.second].begin();
// itr != intersection_points[offenders.second].end(); ++itr) {
// std::cout << (*itr).x() << " " << (*itr).y() << " ";
// } std::cout << "\n";
// exit(1);
// }
}
//quadratic algorithm to find intersections
template <typename iT, typename segment_id>
static inline bool verify_scan(std::pair<segment_id, segment_id>& offenders,
iT begin, iT end)
{
std::vector<std::pair<half_edge, segment_id> > data(begin, end);
for(std::size_t i = 0; i < data.size(); ++i)
{
if(data[i].first.second < data[i].first.first)
{
std::swap(data[i].first.first, data[i].first.second);
}
}
polygon_sort(data.begin(), data.end());
for(typename std::vector<std::pair<half_edge, segment_id> >::iterator outer = data.begin();
outer != data.end(); ++outer)
{
const half_edge& he1 = (*outer).first;
segment_id id1 = (*outer).second;
for(typename std::vector<std::pair<half_edge, segment_id> >::iterator inner = outer;
inner != data.end(); ++inner)
{
const half_edge& he2 = (*inner).first;
if(he1 == he2) continue;
if((std::min)(he2. first.get(HORIZONTAL),
he2.second.get(HORIZONTAL)) >
(std::max)(he1.second.get(HORIZONTAL),
he1.first.get(HORIZONTAL)))
break;
segment_id id2 = (*inner).second;
if(scanline_base<Unit>::intersects(he1, he2))
{
offenders.first = id1;
offenders.second = id2;
//std::cout << he1.first.x() << " " << he1.first.y() << " " << he1.second.x() << " " << he1.second.y() << " " << he2.first.x() << " " << he2.first.y() << " " << he2.second.x() << " " << he2.second.y() << "\n";
return false;
}
}
}
return true;
}
class less_point_down_slope
{
public:
typedef Point first_argument_type;
typedef Point second_argument_type;
typedef bool result_type;
inline less_point_down_slope() {}
inline bool operator () (const Point& pt1, const Point& pt2) const
{
if(pt1.get(HORIZONTAL) < pt2.get(HORIZONTAL)) return true;
if(pt1.get(HORIZONTAL) == pt2.get(HORIZONTAL))
{
if(pt1.get(VERTICAL) > pt2.get(VERTICAL)) return true;
}
return false;
}
};
template <typename iT>
static inline void segment_edge(std::vector<std::pair<half_edge, int> >& output_segments,
const half_edge&, segment_id id, iT begin, iT end)
{
iT current = begin;
iT next = begin;
++next;
while(next != end)
{
output_segments.push_back(std::make_pair(half_edge(*current, *next), id));
current = next;
++next;
}
}
template <typename iT>
static inline void segment_intersections(std::vector<std::pair<half_edge, int> >& output_segments,
std::vector<std::set<Point> >& intersection_points,
iT begin, iT end)
{
for(iT iter = begin; iter != end; ++iter)
{
//less_point lp;
const half_edge& he = (*iter).first;
//if(lp(he.first, he.second)) {
// //it is the begin event
segment_id id = (*iter).second;
const std::set<Point>& pts = intersection_points[id];
Point hpt(he.first.get(HORIZONTAL)+1, he.first.get(VERTICAL));
if(!scanline_base<Unit>::is_vertical(he) && scanline_base<Unit>::less_slope(he.first.get(HORIZONTAL), he.first.get(VERTICAL),
he.second, hpt))
{
//slope is below horizontal
std::vector<Point> tmpPts;
tmpPts.reserve(pts.size());
tmpPts.insert(tmpPts.end(), pts.begin(), pts.end());
less_point_down_slope lpds;
polygon_sort(tmpPts.begin(), tmpPts.end(), lpds);
segment_edge(output_segments, he, id, tmpPts.begin(), tmpPts.end());
}
else
{
segment_edge(output_segments, he, id, pts.begin(), pts.end());
}
//}
}
}
// //iT iterator over unsorted pair<Point> representing line segments of input
// //output_segments is populated with fully intersected output line segment half
// //edges and the index of the input segment that they are assoicated with
// //duplicate output half edges with different ids will be generated in the case
// //that parallel input segments intersection
// //outputs are in sorted order and include both begin and end events for
// //each segment
// template <typename iT>
// inline void scan(std::vector<std::pair<half_edge, int> >& output_segments,
// iT begin, iT end) {
// std::map<segment_id, std::set<Point> > intersection_points;
// scan(intersection_points, begin, end);
// segment_intersections(output_segments, intersection_points, begin, end);
// }
// //iT iterator over sorted sequence of half edge, segment id pairs representing segment begin and end points
// //intersection points provides a mapping from input segment id (vector index) to the set
// //of intersection points assocated with that input segment
// template <typename iT>
// inline void scan(std::map<segment_id, std::set<Point> >& intersection_points,
// iT begin, iT end) {
// for(iT iter = begin; iter != end; ++iter) {
// const std::pair<half_edge, int>& elem = *iter;
// const half_edge& he = elem.first;
// Unit current_x = he.first.get(HORIZONTAL);
// if(current_x != x_) {
// process_scan_event(intersection_points);
// while(!intersection_queue_.empty() &&
// (*(intersection_queue_.begin()).get(HORIZONTAL) < current_x)) {
// x_ = *(intersection_queue_.begin()).get(HORIZONTAL);
// process_intersections_at_scan_event(intersection_points);
// }
// x_ = current_x;
// }
// event_edges_.push_back(elem);
// }
// process_scan_event(intersection_points);
// }
// inline iterator lookup(const half_edge& he) {
// return edge_scanline_.find(he);
// }
// inline void insert_into_scanline(const half_edge& he, int id) {
// edge_scanline_[he].insert(id);
// }
// inline void lookup_and_remove(const half_edge& he, int id) {
// iterator remove_iter = lookup(he);
// if(remove_iter == edge_scanline_.end()) {
// //std::cout << "failed to find removal segment in scanline\n";
// return;
// }
// std::set<segment_id>& ids = (*remove_iter).second;
// std::set<segment_id>::iterator id_iter = ids.find(id);
// if(id_iter == ids.end()) {
// //std::cout << "failed to find removal segment id in scanline set\n";
// return;
// }
// ids.erase(id_iter);
// if(ids.empty())
// edge_scanline_.erase(remove_iter);
// }
// static inline void update_segments(std::map<segment_id, std::set<Point> >& intersection_points,
// const std::set<segment_id>& segments, Point pt) {
// for(std::set<segment_id>::const_iterator itr = segments.begin(); itr != segments.end(); ++itr) {
// intersection_points[*itr].insert(pt);
// }
// }
// inline void process_intersections_at_scan_event(std::map<segment_id, std::set<Point> >& intersection_points) {
// //there may be additional intersection points at this x location that haven't been
// //found yet if vertical or near vertical line segments intersect more than
// //once before the next x location
// just_before_ = true;
// std::set<iterator> intersecting_elements;
// std::set<Unit> intersection_locations;
// typedef typename std::set<Point>::iterator intersection_iterator;
// intersection_iterator iter;
// //first find all secondary intersection locations and all scanline iterators
// //that are intersecting
// for(iter = intersection_queue_.begin();
// iter != intersection_queue_.end() && (*iter).get(HORIZONTAL) == x_; ++iter) {
// Point pt = *iter;
// Unit y = pt.get(VERTICAL);
// intersection_locations.insert(y);
// //if x_ is max there can be only end events and no sloping edges
// if(x_ != (std::numeric_limits<Unit>::max)()) {
// //deal with edges that project to the right of scanline
// //first find the edges in the scanline adjacent to primary intersectin points
// //lookup segment in scanline at pt
// iterator itr = edge_scanline_.lower_bound(half_edge(pt, Point(x_+1, y)));
// //look above pt in scanline until reaching end or segment that doesn't intersect
// //1x1 grid upper right of pt
// //look below pt in scanline until reaching begin or segment that doesn't interset
// //1x1 grid upper right of pt
// //second find edges in scanline on the y interval of each edge found in the previous
// //step for x_ to x_ + 1
// //third find overlaps in the y intervals of all found edges to find all
// //secondary intersection points
// }
// }
// //erase the intersection points from the queue
// intersection_queue_.erase(intersection_queue_.begin(), iter);
// std::vector<scanline_element> insertion_edges;
// insertion_edges.reserve(intersecting_elements.size());
// std::vector<std::pair<Unit, iterator> > sloping_ends;
// //do all the work of updating the output of all intersecting
// for(typename std::set<iterator>::iterator inter_iter = intersecting_elements.begin();
// inter_iter != intersecting_elements.end(); ++inter_iter) {
// //if it is horizontal update it now and continue
// if(is_horizontal((*inter_iter).first)) {
// update_segments(intersection_points, (*inter_iter).second, Point(x_, (*inter_iter).first.get(VERTICAL)));
// } else {
// //if x_ is max there can be only end events and no sloping edges
// if(x_ != (std::numeric_limits<Unit>::max)()) {
// //insert its end points into the vector of sloping ends
// const half_edge& he = (*inter_iter).first;
// Unit y = evalAtXforY(x_, he.first, he.second);
// Unit y2 = evalAtXforY(x_+1, he.first, he.second);
// if(y2 >= y) y2 +=1; //we round up, in exact case we don't worry about overbite of one
// else y += 1; //downward sloping round up
// sloping_ends.push_back(std::make_pair(y, inter_iter));
// sloping_ends.push_back(std::make_pair(y2, inter_iter));
// }
// }
// }
// //merge sloping element data
// polygon_sort(sloping_ends.begin(), sloping_ends.end());
// std::map<Unit, std::set<iterator> > sloping_elements;
// std::set<iterator> merge_elements;
// for(typename std::vector<std::pair<Unit, iterator> >::iterator slop_iter = sloping_ends.begin();
// slop_iter == sloping_ends.end(); ++slop_iter) {
// //merge into sloping elements
// typename std::set<iterator>::iterator merge_iterator = merge_elements.find((*slop_iter).second);
// if(merge_iterator == merge_elements.end()) {
// merge_elements.insert((*slop_iter).second);
// } else {
// merge_elements.erase(merge_iterator);
// }
// sloping_elements[(*slop_iter).first] = merge_elements;
// }
// //scan intersection points
// typename std::map<Unit, std::set<segment_id> >::iterator vertical_iter = vertical_data_.begin();
// typename std::map<Unit, std::set<iterator> >::iterator sloping_iter = sloping_elements.begin();
// for(typename std::set<Unit>::iterator position_iter = intersection_locations.begin();
// position_iter == intersection_locations.end(); ++position_iter) {
// //look for vertical segments that intersect this point and update them
// Unit y = *position_iter;
// Point pt(x_, y);
// //handle vertical segments
// if(vertical_iter != vertical_data_.end()) {
// typename std::map<Unit, std::set<segment_id> >::iterator next_vertical = vertical_iter;
// for(++next_vertical; next_vertical != vertical_data_.end() &&
// (*next_vertical).first < y; ++next_vertical) {
// vertical_iter = next_vertical;
// }
// if((*vertical_iter).first < y && !(*vertical_iter).second.empty()) {
// update_segments(intersection_points, (*vertical_iter).second, pt);
// ++vertical_iter;
// if(vertical_iter != vertical_data_.end() && (*vertical_iter).first == y)
// update_segments(intersection_points, (*vertical_iter).second, pt);
// }
// }
// //handle sloping segments
// if(sloping_iter != sloping_elements.end()) {
// typename std::map<Unit, std::set<iterator> >::iterator next_sloping = sloping_iter;
// for(++next_sloping; next_sloping != sloping_elements.end() &&
// (*next_sloping).first < y; ++next_sloping) {
// sloping_iter = next_sloping;
// }
// if((*sloping_iter).first < y && !(*sloping_iter).second.empty()) {
// for(typename std::set<iterator>::iterator element_iter = (*sloping_iter).second.begin();
// element_iter != (*sloping_iter).second.end(); ++element_iter) {
// const half_edge& he = (*element_iter).first;
// if(intersects_grid(pt, he)) {
// update_segments(intersection_points, (*element_iter).second, pt);
// }
// }
// ++sloping_iter;
// if(sloping_iter != sloping_elements.end() && (*sloping_iter).first == y &&
// !(*sloping_iter).second.empty()) {
// for(typename std::set<iterator>::iterator element_iter = (*sloping_iter).second.begin();
// element_iter != (*sloping_iter).second.end(); ++element_iter) {
// const half_edge& he = (*element_iter).first;
// if(intersects_grid(pt, he)) {
// update_segments(intersection_points, (*element_iter).second, pt);
// }
// }
// }
// }
// }
// }
// //erase and reinsert edges into scanline with check for future intersection
// }
// inline void process_scan_event(std::map<segment_id, std::set<Point> >& intersection_points) {
// just_before_ = true;
// //process end events by removing those segments from the scanline
// //and insert vertices of all events into intersection queue
// Point prev_point((std::numeric_limits<Unit>::min)(), (std::numeric_limits<Unit>::min)());
// less_point lp;
// std::set<segment_id> vertical_ids;
// vertical_data_.clear();
// for(std::size_t i = 0; i < event_edges_.size(); ++i) {
// segment_id id = event_edges_[i].second;
// const half_edge& he = event_edges_[i].first;
// //vertical half edges are handled during intersection processing because
// //they cannot be inserted into the scanline
// if(!is_vertical(he)) {
// if(lp(he.second, he.first)) {
// //half edge is end event
// lookup_and_remove(he, id);
// } else {
// //half edge is begin event
// insert_into_scanline(he, id);
// //note that they will be immediately removed and reinserted after
// //handling their intersection (vertex)
// //an optimization would allow them to be processed specially to avoid the redundant
// //removal and reinsertion
// }
// } else {
// //common case if you are lucky
// //update the map of y to set of segment id
// if(lp(he.second, he.first)) {
// //half edge is end event
// std::set<segment_id>::iterator itr = vertical_ids.find(id);
// if(itr == vertical_ids.end()) {
// //std::cout << "Failed to find end event id in vertical ids\n";
// } else {
// vertical_ids.erase(itr);
// vertical_data_[he.first.get(HORIZONTAL)] = vertical_ids;
// }
// } else {
// //half edge is a begin event
// vertical_ids.insert(id);
// vertical_data_[he.first.get(HORIZONTAL)] = vertical_ids;
// }
// }
// //prevent repeated insertion of same vertex into intersection queue
// if(prev_point != he.first)
// intersection_queue_.insert(he.first);
// else
// prev_point = he.first;
// // process intersections at scan event
// process_intersections_at_scan_event(intersection_points);
// }
// event_edges_.clear();
// }
public:
template <typename stream_type>
static inline bool test_validate_scan(stream_type& stdcout)
{
std::vector<std::pair<half_edge, segment_id> > input, edges;
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(0, 10)), 0));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(10, 10)), 1));
std::pair<segment_id, segment_id> result;
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail1 " << result.first << " " << result.second << "\n";
return false;
}
input.push_back(std::make_pair(half_edge(Point(0, 5), Point(5, 5)), 2));
edges.clear();
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail2 " << result.first << " " << result.second << "\n";
return false;
}
input.pop_back();
input.push_back(std::make_pair(half_edge(Point(1, 0), Point(11, 11)), input.size()));
edges.clear();
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail3 " << result.first << " " << result.second << "\n";
return false;
}
input.push_back(std::make_pair(half_edge(Point(1, 0), Point(10, 11)), input.size()));
edges.clear();
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail4 " << result.first << " " << result.second << "\n";
return false;
}
input.pop_back();
input.push_back(std::make_pair(half_edge(Point(1, 2), Point(11, 11)), input.size()));
edges.clear();
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail5 " << result.first << " " << result.second << "\n";
return false;
}
input.push_back(std::make_pair(half_edge(Point(0, 5), Point(0, 11)), input.size()));
edges.clear();
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail6 " << result.first << " " << result.second << "\n";
return false;
}
input.pop_back();
for(std::size_t i = 0; i < input.size(); ++i)
{
std::swap(input[i].first.first, input[i].first.second);
}
edges.clear();
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail5 2 " << result.first << " " << result.second << "\n";
return false;
}
for(std::size_t i = 0; i < input.size(); ++i)
{
input[i].first.first = Point(input[i].first.first.get(HORIZONTAL) * -1,
input[i].first.first.get(VERTICAL) * -1);
input[i].first.second = Point(input[i].first.second.get(HORIZONTAL) * -1,
input[i].first.second.get(VERTICAL) * -1);
}
edges.clear();
validate_scan(edges, input.begin(), input.end());
stdcout << edges.size() << "\n";
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail5 3 " << result.first << " " << result.second << "\n";
return false;
}
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(5, 7), Point(7, 6)), 0));
input.push_back(std::make_pair(half_edge(Point(2, 4), Point(6, 7)), 1));
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail2 1 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(3, 2), Point(1, 7)), 0));
input.push_back(std::make_pair(half_edge(Point(0, 6), Point(7, 4)), 1));
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail2 2 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(6, 6), Point(1, 0)), 0));
input.push_back(std::make_pair(half_edge(Point(3, 6), Point(2, 3)), 1));
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail2 3 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(7, 0)), 0));
input.push_back(std::make_pair(half_edge(Point(6, 0), Point(2, 0)), 1));
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail2 4 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(-17333131 - -17208131, -10316869 - -10191869), Point(0, 0)), 0));
input.push_back(std::make_pair(half_edge(Point(-17291260 - -17208131, -10200000 - -10191869), Point(-17075000 - -17208131, -10200000 - -10191869)), 1));
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail2 5 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(-17333131, -10316869), Point(-17208131, -10191869)), 0));
input.push_back(std::make_pair(half_edge(Point(-17291260, -10200000), Point(-17075000, -10200000)), 1));
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail2 6 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(-9850009+9853379, -286971+290340), Point(-12777869+9853379, -3214831+290340)), 0));
input.push_back(std::make_pair(half_edge(Point(-5223510+9853379, -290340+290340), Point(-9858140+9853379, -290340+290340)), 1));
validate_scan(edges, input.begin(), input.end());
print(edges);
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail2 7 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(-9850009, -286971), Point(-12777869, -3214831)), 0));
input.push_back(std::make_pair(half_edge(Point(-5223510, -290340), Point(-9858140, -290340)), 1));
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail2 8 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
//3 3 2 2: 0; 4 2 0 6: 1; 0 3 6 3: 2; 4 1 5 5: 3;
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(3, 3), Point(2, 2)), 0));
input.push_back(std::make_pair(half_edge(Point(4, 2), Point(0, 6)), 1));
input.push_back(std::make_pair(half_edge(Point(0, 3), Point(6, 3)), 2));
input.push_back(std::make_pair(half_edge(Point(4, 1), Point(5, 5)), 3));
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail4 1 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
//5 7 1 3: 0; 4 5 2 1: 1; 2 5 2 1: 2; 4 1 5 3: 3;
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(5, 7), Point(1, 3)), 0));
input.push_back(std::make_pair(half_edge(Point(4, 5), Point(2, 1)), 1));
input.push_back(std::make_pair(half_edge(Point(2, 5), Point(2, 1)), 2));
input.push_back(std::make_pair(half_edge(Point(4, 1), Point(5, 3)), 3));
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail4 2 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
//1 0 -4 -1: 0; 0 0 2 -1: 1;
input.clear();
edges.clear();
input.push_back(std::make_pair(half_edge(Point(1, 0), Point(-4, -1)), 0));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(2, -1)), 1));
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail2 5 " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
Unit min_c =0;
Unit max_c =0;
for(unsigned int outer = 0; outer < 1000; ++outer)
{
input.clear();
for(unsigned int i = 0; i < 4; ++i)
{
Unit x1 = rand();
Unit x2 = rand();
Unit y1 = rand();
Unit y2 = rand();
int neg1 = rand() % 2;
if(neg1) x1 *= -1;
int neg2 = rand() % 2;
if(neg2) x2 *= -1;
int neg3 = rand() % 2;
if(neg3) y1 *= -1;
int neg4 = rand() % 2;
if(neg4) y2 *= -1;
if(x1 < min_c) min_c = x1;
if(x2 < min_c) min_c = x2;
if(y1 < min_c) min_c = y1;
if(y2 < min_c) min_c = y2;
if(x1 > max_c) max_c = x1;
if(x2 > max_c) max_c = x2;
if(y1 > max_c) max_c = y1;
if(y2 > max_c) max_c = y2;
Point pt1(x1, y1);
Point pt2(x2, y2);
if(pt1 != pt2)
input.push_back(std::make_pair(half_edge(pt1, pt2), i));
}
edges.clear();
validate_scan(edges, input.begin(), input.end());
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "s fail9 " << outer << ": " << result.first << " " << result.second << "\n";
print(input);
print(edges);
return false;
}
}
return true;
}
//static void print(const std::pair<half_edge, segment_id>& segment) {
//std::cout << segment.first.first << " " << segment.first.second << ": " << segment.second << "; ";
//}
static void print(const std::vector<std::pair<half_edge, segment_id> >& vec)
{
for(std::size_t i = 0; i < vec.size(); ++ i)
{
// print(vec[i]);
}
//std::cout << "\n";
}
template <typename stream_type>
static inline bool test_verify_scan(stream_type& stdcout)
{
std::vector<std::pair<half_edge, segment_id> > edges;
edges.push_back(std::make_pair(half_edge(Point(0, 0), Point(0, 10)), 0));
edges.push_back(std::make_pair(half_edge(Point(0, 0), Point(10, 10)), 1));
std::pair<segment_id, segment_id> result;
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "fail1\n";
return false;
}
edges.push_back(std::make_pair(half_edge(Point(0, 5), Point(5, 5)), 2));
if(verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "fail2\n";
return false;
}
edges.pop_back();
edges.push_back(std::make_pair(half_edge(Point(1, 0), Point(11, 11)), (segment_id)edges.size()));
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "fail3\n";
return false;
}
edges.push_back(std::make_pair(half_edge(Point(1, 0), Point(10, 11)), (segment_id)edges.size()));
if(verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "fail4\n";
return false;
}
edges.pop_back();
edges.push_back(std::make_pair(half_edge(Point(1, 2), Point(11, 11)), (segment_id)edges.size()));
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "fail5 " << result.first << " " << result.second << "\n";
return false;
}
edges.push_back(std::make_pair(half_edge(Point(0, 5), Point(0, 11)), (segment_id)edges.size()));
if(verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "fail6 " << result.first << " " << result.second << "\n";
return false;
}
edges.pop_back();
for(std::size_t i = 0; i < edges.size(); ++i)
{
std::swap(edges[i].first.first, edges[i].first.second);
}
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "fail5 2 " << result.first << " " << result.second << "\n";
return false;
}
for(std::size_t i = 0; i < edges.size(); ++i)
{
edges[i].first.first = Point(edges[i].first.first.get(HORIZONTAL) * -1,
edges[i].first.first.get(VERTICAL) * -1);
edges[i].first.second = Point(edges[i].first.second.get(HORIZONTAL) * -1,
edges[i].first.second.get(VERTICAL) * -1);
}
if(!verify_scan(result, edges.begin(), edges.end()))
{
stdcout << "fail5 3 " << result.first << " " << result.second << "\n";
return false;
}
return true;
}
};
//scanline consumes the "flattened" fully intersected line segments produced by
//a pass of line_intersection along with property and count information and performs a
//useful operation like booleans or property merge or connectivity extraction
template <typename Unit, typename property_type, typename keytype = std::set<property_type> >
class scanline : public scanline_base<Unit>
{
public:
//definitions
typedef typename scanline_base<Unit>::Point Point;
//the first point is the vertex and and second point establishes the slope of an edge eminating from the vertex
//typedef std::pair<Point, Point> half_edge;
typedef typename scanline_base<Unit>::half_edge half_edge;
//scanline comparator functor
typedef typename scanline_base<Unit>::less_half_edge less_half_edge;
typedef typename scanline_base<Unit>::less_point less_point;
typedef keytype property_set;
//this is the data type used internally to store the combination of property counts at a given location
typedef std::vector<std::pair<property_type, int> > property_map;
//this data structure assocates a property and count to a half edge
typedef std::pair<half_edge, std::pair<property_type, int> > vertex_property;
//this data type is used internally to store the combined property data for a given half edge
typedef std::pair<half_edge, property_map> vertex_data;
//this data type stores the combination of many half edges
typedef std::vector<vertex_property> property_merge_data;
//this data structure stores end points of edges in the scanline
typedef std::set<Point, less_point> end_point_queue;
//this is the output data type that is created by the scanline before it is post processed based on content of property sets
typedef std::pair<half_edge, std::pair<property_set, property_set> > half_edge_property;
//this is the scanline data structure
typedef std::map<half_edge, property_map, less_half_edge> scanline_type;
typedef std::pair<half_edge, property_map> scanline_element;
typedef typename scanline_type::iterator iterator;
typedef typename scanline_type::const_iterator const_iterator;
//data
scanline_type scan_data_;
std::vector<iterator> removal_set_; //edges to be removed at the current scanline stop
std::vector<scanline_element> insertion_set_; //edge to be inserted after current scanline stop
end_point_queue end_point_queue_;
Unit x_;
Unit y_;
int just_before_;
typename scanline_base<Unit>::evalAtXforYPack evalAtXforYPack_;
public:
inline scanline() : scan_data_(), removal_set_(), insertion_set_(), end_point_queue_(),
x_((std::numeric_limits<Unit>::max)()), y_((std::numeric_limits<Unit>::max)()), just_before_(false), evalAtXforYPack_()
{
less_half_edge lessElm(&x_, &just_before_, &evalAtXforYPack_);
scan_data_ = scanline_type(lessElm);
}
inline scanline(const scanline& that) : scan_data_(), removal_set_(), insertion_set_(), end_point_queue_(),
x_((std::numeric_limits<Unit>::max)()), y_((std::numeric_limits<Unit>::max)()), just_before_(false), evalAtXforYPack_()
{
(*this) = that;
}
inline scanline& operator=(const scanline& that)
{
x_ = that.x_;
y_ = that.y_;
just_before_ = that.just_before_;
end_point_queue_ = that.end_point_queue_;
//I cannot simply copy that.scanline_type to this scanline_type becuase the functor store pointers to other members!
less_half_edge lessElm(&x_, &just_before_);
scan_data_ = scanline_type(lessElm);
scan_data_.insert(that.scan_data_.begin(), that.scan_data_.end());
return *this;
}
template <typename result_type, typename result_functor>
void write_out(result_type& result, result_functor rf, const half_edge& he,
const property_map& pm_left, const property_map& pm_right)
{
//std::cout << "write out ";
//std::cout << he.first << ", " << he.second << "\n";
property_set ps_left, ps_right;
set_unique_property(ps_left, pm_left);
set_unique_property(ps_right, pm_right);
if(ps_left != ps_right)
{
//std::cout << "!equivalent\n";
rf(result, he, ps_left, ps_right);
}
}
template <typename result_type, typename result_functor, typename iT>
iT handle_input_events(result_type& result, result_functor rf, iT begin, iT end)
{
//typedef typename high_precision_type<Unit>::type high_precision;
//for each event
property_map vertical_properties_above;
property_map vertical_properties_below;
half_edge vertical_edge_above;
half_edge vertical_edge_below;
std::vector<scanline_element> insertion_elements;
//current_iter should increase monotonically toward end as we process scanline stop
iterator current_iter = scan_data_.begin();
just_before_ = true;
Unit y = (std::numeric_limits<Unit>::min)();
bool first_iteration = true;
//we want to return from inside the loop when we hit end or new x
#ifdef BOOST_POLYGON_MSVC
#pragma warning (push)
#pragma warning (disable: 4127)
#endif
while(true)
{
if(begin == end || (!first_iteration && ((*begin).first.first.get(VERTICAL) != y ||
(*begin).first.first.get(HORIZONTAL) != x_)))
{
//lookup iterator range in scanline for elements coming in from the left
//that end at this y
Point pt(x_, y);
//grab the properties coming in from below
property_map properties_below;
if(current_iter != scan_data_.end())
{
//make sure we are looking at element in scanline just below y
//if(evalAtXforY(x_, (*current_iter).first.first, (*current_iter).first.second) != y) {
if(scanline_base<Unit>::on_above_or_below(Point(x_, y), (*current_iter).first) != 0)
{
Point e2(pt);
if(e2.get(VERTICAL) != (std::numeric_limits<Unit>::max)())
e2.set(VERTICAL, e2.get(VERTICAL) + 1);
else
e2.set(VERTICAL, e2.get(VERTICAL) - 1);
half_edge vhe(pt, e2);
current_iter = scan_data_.lower_bound(vhe);
}
if(current_iter != scan_data_.end())
{
//get the bottom iterator for elements at this point
//while(evalAtXforY(x_, (*current_iter).first.first, (*current_iter).first.second) >= (high_precision)y &&
while(scanline_base<Unit>::on_above_or_below(Point(x_, y), (*current_iter).first) != 1 &&
current_iter != scan_data_.begin())
{
--current_iter;
}
//if(evalAtXforY(x_, (*current_iter).first.first, (*current_iter).first.second) >= (high_precision)y) {
if(scanline_base<Unit>::on_above_or_below(Point(x_, y), (*current_iter).first) != 1)
{
properties_below.clear();
}
else
{
properties_below = (*current_iter).second;
//move back up to y or one past y
++current_iter;
}
}
}
std::vector<iterator> edges_from_left;
while(current_iter != scan_data_.end() &&
//can only be true if y is integer
//evalAtXforY(x_, (*current_iter).first.first, (*current_iter).first.second) == y) {
scanline_base<Unit>::on_above_or_below(Point(x_, y), (*current_iter).first) == 0)
{
//removal_set_.push_back(current_iter);
++current_iter;
}
//merge vertical count with count from below
if(!vertical_properties_below.empty())
{
merge_property_maps(vertical_properties_below, properties_below);
//write out vertical edge
write_out(result, rf, vertical_edge_below, properties_below, vertical_properties_below);
}
else
{
merge_property_maps(vertical_properties_below, properties_below);
}
//iteratively add intertion element counts to count from below
//and write them to insertion set
for(std::size_t i = 0; i < insertion_elements.size(); ++i)
{
if(i == 0)
{
merge_property_maps(insertion_elements[i].second, vertical_properties_below);
write_out(result, rf, insertion_elements[i].first, insertion_elements[i].second, vertical_properties_below);
}
else
{
merge_property_maps(insertion_elements[i].second, insertion_elements[i-1].second);
write_out(result, rf, insertion_elements[i].first, insertion_elements[i].second, insertion_elements[i-1].second);
}
insertion_set_.push_back(insertion_elements[i]);
}
if((begin == end || (*begin).first.first.get(HORIZONTAL) != x_))
{
if(vertical_properties_above.empty())
{
return begin;
}
else
{
y = vertical_edge_above.second.get(VERTICAL);
vertical_properties_below.clear();
vertical_properties_above.swap(vertical_properties_below);
vertical_edge_below = vertical_edge_above;
insertion_elements.clear();
continue;
}
}
vertical_properties_below.clear();
vertical_properties_above.swap(vertical_properties_below);
vertical_edge_below = vertical_edge_above;
insertion_elements.clear();
}
if(begin != end)
{
const vertex_property& vp = *begin;
const half_edge& he = vp.first;
y = he.first.get(VERTICAL);
first_iteration = false;
if(! vertical_properties_below.empty() &&
vertical_edge_below.second.get(VERTICAL) < y)
{
y = vertical_edge_below.second.get(VERTICAL);
continue;
}
if(scanline_base<Unit>::is_vertical(he))
{
update_property_map(vertical_properties_above, vp.second);
vertical_edge_above = he;
}
else
{
if(insertion_elements.empty() ||
insertion_elements.back().first != he)
{
insertion_elements.push_back(scanline_element(he, property_map()));
}
update_property_map(insertion_elements.back().second, vp.second);
}
++begin;
}
}
#ifdef BOOST_POLYGON_MSVC
#pragma warning (pop)
#endif
}
inline void erase_end_events(typename end_point_queue::iterator epqi)
{
end_point_queue_.erase(end_point_queue_.begin(), epqi);
for(typename std::vector<iterator>::iterator retire_itr = removal_set_.begin();
retire_itr != removal_set_.end(); ++retire_itr)
{
scan_data_.erase(*retire_itr);
}
removal_set_.clear();
}
inline void remove_retired_edges_from_scanline()
{
just_before_ = true;
typename end_point_queue::iterator epqi = end_point_queue_.begin();
Unit current_x = x_;
Unit previous_x = x_;
while(epqi != end_point_queue_.end() &&
(*epqi).get(HORIZONTAL) <= current_x)
{
x_ = (*epqi).get(HORIZONTAL);
if(x_ != previous_x) erase_end_events(epqi);
previous_x = x_;
//lookup elements
Point e2(*epqi);
if(e2.get(VERTICAL) != (std::numeric_limits<Unit>::max)())
e2.set(VERTICAL, e2.get(VERTICAL) + 1);
else
e2.set(VERTICAL, e2.get(VERTICAL) - 1);
half_edge vhe_e(*epqi, e2);
iterator current_iter = scan_data_.lower_bound(vhe_e);
while(current_iter != scan_data_.end() && (*current_iter).first.second == (*epqi))
{
//evalAtXforY(x_, (*current_iter).first.first, (*current_iter).first.second) == (*epqi).get(VERTICAL)) {
removal_set_.push_back(current_iter);
++current_iter;
}
++epqi;
}
x_ = current_x;
erase_end_events(epqi);
}
inline void insert_new_edges_into_scanline()
{
just_before_ = false;
for(typename std::vector<scanline_element>::iterator insert_itr = insertion_set_.begin();
insert_itr != insertion_set_.end(); ++insert_itr)
{
scan_data_.insert(*insert_itr);
end_point_queue_.insert((*insert_itr).first.second);
}
insertion_set_.clear();
}
//iterator over range of vertex property elements and call result functor
//passing edge to be output, the merged data on both sides and the result
template <typename result_type, typename result_functor, typename iT>
void scan(result_type& result, result_functor rf, iT begin, iT end)
{
while(begin != end)
{
x_ = (*begin).first.first.get(HORIZONTAL); //update scanline stop location
//print_scanline();
--x_;
remove_retired_edges_from_scanline();
++x_;
begin = handle_input_events(result, rf, begin, end);
remove_retired_edges_from_scanline();
//print_scanline();
insert_new_edges_into_scanline();
}
//print_scanline();
x_ = (std::numeric_limits<Unit>::max)();
remove_retired_edges_from_scanline();
}
//inline void print_scanline() {
// std::cout << "scanline at " << x_ << ": ";
// for(iterator itr = scan_data_.begin(); itr != scan_data_.end(); ++itr) {
// const scanline_element& se = *itr;
// const half_edge& he = se.first;
// const property_map& mp = se.second;
// std::cout << he.first << ", " << he.second << " ( ";
// for(std::size_t i = 0; i < mp.size(); ++i) {
// std::cout << mp[i].first << ":" << mp[i].second << " ";
// } std::cout << ") ";
// } std::cout << "\n";
//}
static inline void merge_property_maps(property_map& mp, const property_map& mp2)
{
property_map newmp;
newmp.reserve(mp.size() + mp2.size());
unsigned int i = 0;
unsigned int j = 0;
while(i != mp.size() && j != mp2.size())
{
if(mp[i].first < mp2[j].first)
{
newmp.push_back(mp[i]);
++i;
}
else if(mp[i].first > mp2[j].first)
{
newmp.push_back(mp2[j]);
++j;
}
else
{
int count = mp[i].second;
count += mp2[j].second;
if(count)
{
newmp.push_back(mp[i]);
newmp.back().second = count;
}
++i;
++j;
}
}
while(i != mp.size())
{
newmp.push_back(mp[i]);
++i;
}
while(j != mp2.size())
{
newmp.push_back(mp2[j]);
++j;
}
mp.swap(newmp);
}
static inline void update_property_map(property_map& mp, const std::pair<property_type, int>& prop_data)
{
property_map newmp;
newmp.reserve(mp.size() +1);
bool consumed = false;
for(std::size_t i = 0; i < mp.size(); ++i)
{
if(!consumed && prop_data.first == mp[i].first)
{
consumed = true;
int count = prop_data.second + mp[i].second;
if(count)
newmp.push_back(std::make_pair(prop_data.first, count));
}
else if(!consumed && prop_data.first < mp[i].first)
{
consumed = true;
newmp.push_back(prop_data);
newmp.push_back(mp[i]);
}
else
{
newmp.push_back(mp[i]);
}
}
if(!consumed) newmp.push_back(prop_data);
mp.swap(newmp);
}
static inline void set_unique_property(property_set& unqiue_property, const property_map& property)
{
unqiue_property.clear();
for(typename property_map::const_iterator itr = property.begin(); itr != property.end(); ++itr)
{
if((*itr).second > 0)
unqiue_property.insert(unqiue_property.end(), (*itr).first);
}
}
static inline bool common_vertex(const half_edge& he1, const half_edge& he2)
{
return he1.first == he2.first ||
he1.first == he2.second ||
he1.second == he2.first ||
he1.second == he2.second;
}
typedef typename scanline_base<Unit>::vertex_half_edge vertex_half_edge;
template <typename iT>
static inline void convert_segments_to_vertex_half_edges(std::vector<vertex_half_edge>& output, iT begin, iT end)
{
for( ; begin != end; ++begin)
{
const half_edge& he = (*begin).first;
int count = (*begin).second;
output.push_back(vertex_half_edge(he.first, he.second, count));
output.push_back(vertex_half_edge(he.second, he.first, -count));
}
polygon_sort(output.begin(), output.end());
}
class test_functor
{
public:
inline test_functor() {}
inline void operator()(std::vector<std::pair<half_edge, std::pair<property_set, property_set> > >& result,
const half_edge& he, const property_set& ps_left, const property_set& ps_right)
{
result.push_back(std::make_pair(he, std::make_pair(ps_left, ps_right)));
}
};
template <typename stream_type>
static inline bool test_scanline(stream_type& stdcout)
{
std::vector<std::pair<half_edge, std::pair<property_set, property_set> > > result;
std::vector<std::pair<half_edge, std::pair<property_type, int> > > input;
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(0, 10)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(10, 0)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 10), Point(10, 10)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(10, 0), Point(10, 10)), std::make_pair(0, -1)));
scanline sl;
test_functor tf;
sl.scan(result, tf, input.begin(), input.end());
stdcout << "scanned\n";
for(std::size_t i = 0; i < result.size(); ++i)
{
stdcout << result[i].first.first << ", " << result[i].first.second << "; ";
}
stdcout << "\n";
input.clear();
result.clear();
input.push_back(std::make_pair(half_edge(Point(-1, -1), Point(10, 0)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(-1, -1), Point(0, 10)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(0, 10), Point(11, 11)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(10, 0), Point(11, 11)), std::make_pair(0, 1)));
scanline sl2;
sl2.scan(result, tf, input.begin(), input.end());
stdcout << "scanned\n";
for(std::size_t i = 0; i < result.size(); ++i)
{
stdcout << result[i].first.first << ", " << result[i].first.second << "; ";
}
stdcout << "\n";
input.clear();
result.clear();
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(0, 10)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(10, 0)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 10), Point(10, 10)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(1, 1), Point(8, 2)), std::make_pair(1, 1)));
input.push_back(std::make_pair(half_edge(Point(1, 1), Point(2, 8)), std::make_pair(1, -1)));
input.push_back(std::make_pair(half_edge(Point(2, 8), Point(9, 9)), std::make_pair(1, -1)));
input.push_back(std::make_pair(half_edge(Point(8, 2), Point(9, 9)), std::make_pair(1, 1)));
input.push_back(std::make_pair(half_edge(Point(10, 0), Point(10, 10)), std::make_pair(0, -1)));
scanline sl3;
sl3.scan(result, tf, input.begin(), input.end());
stdcout << "scanned\n";
for(std::size_t i = 0; i < result.size(); ++i)
{
stdcout << result[i].first.first << ", " << result[i].first.second << "; ";
}
stdcout << "\n";
input.clear();
result.clear();
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(0, 10)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(10, 0)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 10), Point(10, 10)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(1, 1), Point(8, 2)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(1, 1), Point(2, 8)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(2, 8), Point(9, 9)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(8, 2), Point(9, 9)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(10, 0), Point(10, 10)), std::make_pair(0, -1)));
scanline sl4;
sl4.scan(result, tf, input.begin(), input.end());
stdcout << "scanned\n";
for(std::size_t i = 0; i < result.size(); ++i)
{
stdcout << result[i].first.first << ", " << result[i].first.second << "; ";
}
stdcout << "\n";
input.clear();
result.clear();
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(10, 0)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(9, 1)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(1, 9)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(0, 10)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 10), Point(10, 10)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(1, 9), Point(10, 10)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(9, 1), Point(10, 10)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(10, 0), Point(10, 10)), std::make_pair(0, -1)));
scanline sl5;
sl5.scan(result, tf, input.begin(), input.end());
stdcout << "scanned\n";
for(std::size_t i = 0; i < result.size(); ++i)
{
stdcout << result[i].first.first << ", " << result[i].first.second << "; ";
}
stdcout << "\n";
input.clear();
result.clear();
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(10, 0)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(9, 1)), std::make_pair(1, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(1, 9)), std::make_pair(1, -1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(0, 10)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 10), Point(10, 10)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(1, 9), Point(10, 10)), std::make_pair(1, -1)));
input.push_back(std::make_pair(half_edge(Point(9, 1), Point(10, 10)), std::make_pair(1, 1)));
input.push_back(std::make_pair(half_edge(Point(10, 0), Point(10, 10)), std::make_pair(0, -1)));
scanline sl6;
sl6.scan(result, tf, input.begin(), input.end());
stdcout << "scanned\n";
for(std::size_t i = 0; i < result.size(); ++i)
{
stdcout << result[i].first.first << ", " << result[i].first.second << "; ";
}
stdcout << "\n";
input.clear();
result.clear();
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(10, 0)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(9, 1)), std::make_pair(1, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(1, 9)), std::make_pair(1, -1)));
input.push_back(std::make_pair(half_edge(Point(0, 0), Point(0, 10)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 10), Point(10, 10)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(0, 20), Point(10, 20)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 20), Point(9, 21)), std::make_pair(1, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 20), Point(1, 29)), std::make_pair(1, -1)));
input.push_back(std::make_pair(half_edge(Point(0, 20), Point(0, 30)), std::make_pair(0, 1)));
input.push_back(std::make_pair(half_edge(Point(0, 30), Point(10, 30)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(1, 9), Point(10, 10)), std::make_pair(1, -1)));
input.push_back(std::make_pair(half_edge(Point(1, 29), Point(10, 30)), std::make_pair(1, -1)));
input.push_back(std::make_pair(half_edge(Point(9, 1), Point(10, 10)), std::make_pair(1, 1)));
input.push_back(std::make_pair(half_edge(Point(9, 21), Point(10, 30)), std::make_pair(1, 1)));
input.push_back(std::make_pair(half_edge(Point(10, 20), Point(10, 30)), std::make_pair(0, -1)));
input.push_back(std::make_pair(half_edge(Point(10, 20), Point(10, 30)), std::make_pair(0, -1)));
scanline sl7;
sl7.scan(result, tf, input.begin(), input.end());
stdcout << "scanned\n";
for(std::size_t i = 0; i < result.size(); ++i)
{
stdcout << result[i].first.first << ", " << result[i].first.second << "; ";
}
stdcout << "\n";
input.clear();
result.clear();
input.push_back(std::make_pair(half_edge(Point(-1, -1), Point(10, 0)), std::make_pair(0, 1))); //a
input.push_back(std::make_pair(half_edge(Point(-1, -1), Point(0, 10)), std::make_pair(0, -1))); //a
input.push_back(std::make_pair(half_edge(Point(0, 10), Point(11, 11)), std::make_pair(0, -1))); //a
input.push_back(std::make_pair(half_edge(Point(10, 0), Point(20, 0)), std::make_pair(0, 1))); //b
input.push_back(std::make_pair(half_edge(Point(10, 0), Point(11, 11)), std::make_pair(0, -1))); //b
input.push_back(std::make_pair(half_edge(Point(10, 0), Point(11, 11)), std::make_pair(0, 1))); //a
input.push_back(std::make_pair(half_edge(Point(11, 11), Point(20, 10)), std::make_pair(0, -1))); //b
input.push_back(std::make_pair(half_edge(Point(20, 0), Point(30, 0)), std::make_pair(0, 1))); //c
input.push_back(std::make_pair(half_edge(Point(20, 0), Point(20, 10)), std::make_pair(0, -1))); //b
input.push_back(std::make_pair(half_edge(Point(20, 0), Point(20, 10)), std::make_pair(0, 1))); //c
input.push_back(std::make_pair(half_edge(Point(20, 10), Point(30, 10)), std::make_pair(0, -1))); //c
input.push_back(std::make_pair(half_edge(Point(30, 0), Point(30, 10)), std::make_pair(0, -1))); //c
scanline sl8;
sl8.scan(result, tf, input.begin(), input.end());
stdcout << "scanned\n";
for(std::size_t i = 0; i < result.size(); ++i)
{
stdcout << result[i].first.first << ", " << result[i].first.second << "; ";
}
stdcout << "\n";
return true;
}
};
template <typename Unit>
class merge_output_functor
{
public:
typedef typename scanline_base<Unit>::half_edge half_edge;
merge_output_functor() {}
template <typename result_type, typename key_type>
void operator()(result_type& result, const half_edge& edge, const key_type& left, const key_type& right)
{
typename std::pair<half_edge, int> elem;
elem.first = edge;
elem.second = 1;
if(edge.second < edge.first) elem.second *= -1;
if(scanline_base<Unit>::is_vertical(edge)) elem.second *= -1;
if(!left.empty())
result[left].insert_clean(elem);
elem.second *= -1;
if(!right.empty())
result[right].insert_clean(elem);
}
};
template <typename Unit, typename property_type, typename key_type = std::set<property_type>,
typename output_functor_type = merge_output_functor<Unit> >
class property_merge : public scanline_base<Unit>
{
protected:
typedef typename scanline_base<Unit>::Point Point;
//the first point is the vertex and and second point establishes the slope of an edge eminating from the vertex
//typedef std::pair<Point, Point> half_edge;
typedef typename scanline_base<Unit>::half_edge half_edge;
//scanline comparator functor
typedef typename scanline_base<Unit>::less_half_edge less_half_edge;
typedef typename scanline_base<Unit>::less_point less_point;
//this data structure assocates a property and count to a half edge
typedef std::pair<half_edge, std::pair<property_type, int> > vertex_property;
//this data type stores the combination of many half edges
typedef std::vector<vertex_property> property_merge_data;
//this is the data type used internally to store the combination of property counts at a given location
typedef std::vector<std::pair<property_type, int> > property_map;
//this data type is used internally to store the combined property data for a given half edge
typedef std::pair<half_edge, property_map> vertex_data;
property_merge_data pmd;
typename scanline_base<Unit>::evalAtXforYPack evalAtXforYPack_;
template<typename vertex_data_type>
class less_vertex_data
{
typename scanline_base<Unit>::evalAtXforYPack* pack_;
public:
less_vertex_data() : pack_() {}
less_vertex_data(typename scanline_base<Unit>::evalAtXforYPack* pack) : pack_(pack) {}
bool operator() (const vertex_data_type& lvalue, const vertex_data_type& rvalue) const
{
less_point lp;
if(lp(lvalue.first.first, rvalue.first.first)) return true;
if(lp(rvalue.first.first, lvalue.first.first)) return false;
Unit x = lvalue.first.first.get(HORIZONTAL);
int just_before_ = 0;
less_half_edge lhe(&x, &just_before_, pack_);
return lhe(lvalue.first, rvalue.first);
}
};
inline void sort_property_merge_data()
{
less_vertex_data<vertex_property> lvd(&evalAtXforYPack_);
polygon_sort(pmd.begin(), pmd.end(), lvd);
}
public:
inline property_merge_data& get_property_merge_data()
{
return pmd;
}
inline property_merge() : pmd(), evalAtXforYPack_() {}
inline property_merge(const property_merge& pm) : pmd(pm.pmd), evalAtXforYPack_(pm.evalAtXforYPack_) {}
inline property_merge& operator=(const property_merge& pm)
{
pmd = pm.pmd;
return *this;
}
template <typename polygon_type>
void insert(const polygon_type& polygon_object, const property_type& property_value, bool is_hole = false)
{
insert(polygon_object, property_value, is_hole, typename geometry_concept<polygon_type>::type());
}
//result type should be std::map<std::set<property_type>, polygon_set_type>
//or std::map<std::vector<property_type>, polygon_set_type>
template <typename result_type>
void merge(result_type& result)
{
if(pmd.empty()) return;
//intersect data
property_merge_data tmp_pmd;
line_intersection<Unit>::validate_scan(tmp_pmd, pmd.begin(), pmd.end());
pmd.swap(tmp_pmd);
sort_property_merge_data();
scanline<Unit, property_type, key_type> sl;
output_functor_type mof;
sl.scan(result, mof, pmd.begin(), pmd.end());
}
inline bool verify1()
{
std::pair<int, int> offenders;
std::vector<std::pair<half_edge, int> > lines;
int count = 0;
for(std::size_t i = 0; i < pmd.size(); ++i)
{
lines.push_back(std::make_pair(pmd[i].first, count++));
}
if(!line_intersection<Unit>::verify_scan(offenders, lines.begin(), lines.end()))
{
//stdcout << "Intersection failed!\n";
//stdcout << offenders.first << " " << offenders.second << "\n";
return false;
}
std::vector<Point> pts;
for(std::size_t i = 0; i < lines.size(); ++i)
{
pts.push_back(lines[i].first.first);
pts.push_back(lines[i].first.second);
}
polygon_sort(pts.begin(), pts.end());
for(std::size_t i = 0; i < pts.size(); i+=2)
{
if(pts[i] != pts[i+1])
{
//stdcout << "Non-closed figures after line intersection!\n";
return false;
}
}
return true;
}
void clear()
{
*this = property_merge();
}
protected:
template <typename polygon_type>
void insert(const polygon_type& polygon_object, const property_type& property_value, bool is_hole,
polygon_concept )
{
bool first_iteration = true;
bool second_iteration = true;
Point first_point;
Point second_point;
Point previous_previous_point;
Point previous_point;
Point current_point;
direction_1d winding_dir = winding(polygon_object);
for(typename polygon_traits<polygon_type>::iterator_type itr = begin_points(polygon_object);
itr != end_points(polygon_object); ++itr)
{
assign(current_point, *itr);
if(first_iteration)
{
first_iteration = false;
first_point = previous_point = current_point;
}
else if(second_iteration)
{
if(previous_point != current_point)
{
second_iteration = false;
previous_previous_point = previous_point;
second_point = previous_point = current_point;
}
}
else
{
if(previous_point != current_point)
{
create_vertex(pmd, previous_point, current_point, winding_dir,
is_hole, property_value);
previous_previous_point = previous_point;
previous_point = current_point;
}
}
}
current_point = first_point;
if(!first_iteration && !second_iteration)
{
if(previous_point != current_point)
{
create_vertex(pmd, previous_point, current_point, winding_dir,
is_hole, property_value);
previous_previous_point = previous_point;
previous_point = current_point;
}
current_point = second_point;
create_vertex(pmd, previous_point, current_point, winding_dir,
is_hole, property_value);
previous_previous_point = previous_point;
previous_point = current_point;
}
}
template <typename polygon_with_holes_type>
void insert(const polygon_with_holes_type& polygon_with_holes_object, const property_type& property_value, bool is_hole,
polygon_with_holes_concept)
{
insert(polygon_with_holes_object, property_value, is_hole, polygon_concept());
for(typename polygon_with_holes_traits<polygon_with_holes_type>::iterator_holes_type itr =
begin_holes(polygon_with_holes_object);
itr != end_holes(polygon_with_holes_object); ++itr)
{
insert(*itr, property_value, !is_hole, polygon_concept());
}
}
template <typename rectangle_type>
void insert(const rectangle_type& rectangle_object, const property_type& property_value, bool is_hole,
rectangle_concept )
{
polygon_90_data<Unit> poly;
assign(poly, rectangle_object);
insert(poly, property_value, is_hole, polygon_concept());
}
public: //change to private when done testing
static inline void create_vertex(property_merge_data& pmd,
const Point& current_point,
const Point& next_point,
direction_1d winding,
bool is_hole, const property_type& property)
{
if(current_point == next_point) return;
vertex_property current_vertex;
current_vertex.first.first = current_point;
current_vertex.first.second = next_point;
current_vertex.second.first = property;
int multiplier = 1;
if(winding == CLOCKWISE)
multiplier = -1;
if(is_hole)
multiplier *= -1;
if(current_point < next_point)
{
multiplier *= -1;
std::swap(current_vertex.first.first, current_vertex.first.second);
}
current_vertex.second.second = multiplier * (euclidean_distance(next_point, current_point, HORIZONTAL) == 0 ? -1: 1);
pmd.push_back(current_vertex);
//current_vertex.first.second = previous_point;
//current_vertex.second.second *= -1;
//pmd.push_back(current_vertex);
}
static inline void sort_vertex_half_edges(vertex_data& vertex)
{
less_half_edge_pair lessF(vertex.first);
polygon_sort(vertex.second.begin(), vertex.second.end(), lessF);
}
class less_half_edge_pair
{
private:
Point pt_;
public:
less_half_edge_pair(const Point& pt) : pt_(pt) {}
bool operator()(const half_edge& e1, const half_edge& e2)
{
const Point& pt1 = e1.first;
const Point& pt2 = e2.first;
if(get(pt1, HORIZONTAL) ==
get(pt_, HORIZONTAL))
{
//vertical edge is always largest
return false;
}
if(get(pt2, HORIZONTAL) ==
get(pt_, HORIZONTAL))
{
//if half edge 1 is not vertical its slope is less than that of half edge 2
return get(pt1, HORIZONTAL) != get(pt2, HORIZONTAL);
}
return scanline_base<Unit>::less_slope(get(pt_, HORIZONTAL),
get(pt_, VERTICAL), pt1, pt2);
}
};
public:
//test functions
template <typename stream_type>
static stream_type& print (stream_type& o, const property_map& c)
{
o << "count: {";
for(typename property_map::const_iterator itr = c.begin(); itr != c.end(); ++itr)
{
o << ((*itr).first) << ":" << ((*itr).second) << " ";
}
return o << "} ";
}
template <typename stream_type>
static stream_type& print (stream_type& o, const half_edge& he)
{
o << "half edge: (";
o << (he.first);
return o << ", " << (he.second) << ") ";
}
template <typename stream_type>
static stream_type& print (stream_type& o, const vertex_property& c)
{
o << "vertex property: {";
print(o, c.first);
o << ", " << c.second.first << ":" << c.second.second << " ";
return o;
}
template <typename stream_type>
static stream_type& print (stream_type& o, const std::vector<vertex_property>& hev)
{
o << "vertex properties: {";
for(std::size_t i = 0; i < hev.size(); ++i)
{
print(o, (hev[i])) << " ";
}
return o << "} ";
}
template <typename stream_type>
static stream_type& print (stream_type& o, const std::vector<half_edge>& hev)
{
o << "half edges: {";
for(std::size_t i = 0; i < hev.size(); ++i)
{
print(o, (hev[i])) << " ";
}
return o << "} ";
}
template <typename stream_type>
static stream_type& print (stream_type& o, const vertex_data& v)
{
return print(o << "vertex: <" << (v.first) << ", ", (v.second)) << "> ";
}
template <typename stream_type>
static stream_type& print (stream_type& o, const std::vector<vertex_data>& vv)
{
o << "vertices: {";
for(std::size_t i = 0; i < vv.size(); ++i)
{
print(o, (vv[i])) << " ";
}
return o << "} ";
}
template <typename stream_type>
static inline bool test_insertion(stream_type& stdcout)
{
property_merge si;
rectangle_data<Unit> rect;
xl(rect, 0);
yl(rect, 1);
xh(rect, 10);
yh(rect, 11);
si.insert(rect, 333);
print(stdcout, si.pmd) << "\n";
Point pts[4] = {Point(0, 0), Point(10,-3), Point(13, 8), Point(0, 0) };
polygon_data<Unit> poly;
property_merge si2;
poly.set(pts, pts+3);
si2.insert(poly, 444);
si2.sort_property_merge_data();
print(stdcout, si2.pmd) << "\n";
property_merge si3;
poly.set(pts, pts+4);
si3.insert(poly, 444);
si3.sort_property_merge_data();
stdcout << (si2.pmd == si3.pmd) << "\n";
std::reverse(pts, pts+4);
property_merge si4;
poly.set(pts, pts+4);
si4.insert(poly, 444);
si4.sort_property_merge_data();
print(stdcout, si4.pmd) << "\n";
stdcout << (si2.pmd == si4.pmd) << "\n";
std::reverse(pts, pts+3);
property_merge si5;
poly.set(pts, pts+4);
si5.insert(poly, 444);
si5.sort_property_merge_data();
stdcout << (si2.pmd == si5.pmd) << "\n";
return true;
}
template <typename stream_type>
static inline bool test_merge(stream_type& stdcout)
{
property_merge si;
rectangle_data<Unit> rect;
xl(rect, 0);
yl(rect, 1);
xh(rect, 10);
yh(rect, 11);
si.insert(rect, 333);
std::map<std::set<property_type>, polygon_set_data<Unit> > result;
si.merge(result);
print(stdcout, si.pmd) << "\n";
polygon_set_data<Unit> psd = (*(result.begin())).second;
std::vector<polygon_data<Unit> > polys;
psd.get(polys);
if(polys.size() != 1)
{
stdcout << "fail merge 1\n";
return false;
}
stdcout << (polys[0]) << "\n";
si.clear();
std::vector<Point> pts;
pts.push_back(Point(0, 0));
pts.push_back(Point(10, -10));
pts.push_back(Point(10, 10));
polygon_data<Unit> poly;
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
pts.clear();
pts.push_back(Point(5, 0));
pts.push_back(Point(-5, -10));
pts.push_back(Point(-5, 10));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
result.clear();
si.merge(result);
print(stdcout, si.pmd) << "\n";
psd = (*(result.begin())).second;
stdcout << psd << "\n";
polys.clear();
psd.get(polys);
if(polys.size() != 1)
{
stdcout << "fail merge 2\n";
return false;
}
//Polygon { -4 -1, 3 3, -2 3 }
//Polygon { 0 -4, -4 -2, -2 1 }
si.clear();
pts.clear();
pts.push_back(Point(-4, -1));
pts.push_back(Point(3, 3));
pts.push_back(Point(-2, 3));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
pts.clear();
pts.push_back(Point(0, -4));
pts.push_back(Point(-4, -2));
pts.push_back(Point(-2, 1));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
result.clear();
si.merge(result);
print(stdcout, si.pmd) << "\n";
psd = (*(result.begin())).second;
stdcout << psd << "\n";
polys.clear();
psd.get(polys);
if(polys.size() != 1)
{
stdcout << "fail merge 3\n";
return false;
}
stdcout << "Polygon { -2 2, -2 2, 1 4 } \n";
stdcout << "Polygon { 2 4, 2 -4, -3 1 } \n";
si.clear();
pts.clear();
pts.push_back(Point(-2, 2));
pts.push_back(Point(-2, 2));
pts.push_back(Point(1, 4));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
pts.clear();
pts.push_back(Point(2, 4));
pts.push_back(Point(2, -4));
pts.push_back(Point(-3, 1));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
result.clear();
si.merge(result);
print(stdcout, si.pmd) << "\n";
psd = (*(result.begin())).second;
stdcout << psd << "\n";
polys.clear();
psd.get(polys);
if(polys.size() != 1)
{
stdcout << "fail merge 4\n";
return false;
}
stdcout << (polys[0]) << "\n";
stdcout << "Polygon { -4 0, -2 -3, 3 -4 } \n";
stdcout << "Polygon { -1 1, 1 -2, -4 -3 } \n";
si.clear();
pts.clear();
pts.push_back(Point(-4, 0));
pts.push_back(Point(-2, -3));
pts.push_back(Point(3, -4));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
pts.clear();
pts.push_back(Point(-1, 1));
pts.push_back(Point(1, -2));
pts.push_back(Point(-4, -3));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
result.clear();
si.merge(result);
print(stdcout, si.pmd) << "\n";
psd = (*(result.begin())).second;
stdcout << psd << "\n";
polys.clear();
psd.get(polys);
if(polys.size() != 1)
{
stdcout << "fail merge 5\n";
return false;
}
stdcout << "Polygon { 2 2, -2 0, 0 1 } \n";
stdcout << "Polygon { 4 -2, 3 -1, 2 3 } \n";
si.clear();
pts.clear();
pts.push_back(Point(2, 2));
pts.push_back(Point(-2, 0));
pts.push_back(Point(0, 1));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
pts.clear();
pts.push_back(Point(4, -2));
pts.push_back(Point(3, -1));
pts.push_back(Point(2, 3));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
result.clear();
si.merge(result);
print(stdcout, si.pmd) << "\n";
if(!result.empty())
{
psd = (*(result.begin())).second;
stdcout << psd << "\n";
polys.clear();
psd.get(polys);
if(polys.size() != 1)
{
stdcout << "fail merge 6\n";
return false;
}
stdcout << (polys[0]) << "\n";
}
stdcout << "Polygon { 0 2, 3 -1, 4 1 } \n";
stdcout << "Polygon { -4 3, 3 3, 4 2 } \n";
si.clear();
pts.clear();
pts.push_back(Point(0, 2));
pts.push_back(Point(3, -1));
pts.push_back(Point(4, 1));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
pts.clear();
pts.push_back(Point(-4, 3));
pts.push_back(Point(3, 3));
pts.push_back(Point(4, 2));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
result.clear();
si.merge(result);
print(stdcout, si.pmd) << "\n";
if(!result.empty())
{
psd = (*(result.begin())).second;
stdcout << psd << "\n";
polys.clear();
psd.get(polys);
if(polys.size() == 0)
{
stdcout << "fail merge 7\n";
return false;
}
stdcout << (polys[0]) << "\n";
}
stdcout << "Polygon { 1 -2, -1 4, 3 -2 } \n";
stdcout << "Polygon { 0 -3, 3 1, -3 -4 } \n";
si.clear();
pts.clear();
pts.push_back(Point(1, -2));
pts.push_back(Point(-1, 4));
pts.push_back(Point(3, -2));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
pts.clear();
pts.push_back(Point(0, -3));
pts.push_back(Point(3, 1));
pts.push_back(Point(-3, -4));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
result.clear();
si.merge(result);
print(stdcout, si.pmd) << "\n";
if(!result.empty())
{
psd = (*(result.begin())).second;
stdcout << psd << "\n";
polys.clear();
psd.get(polys);
if(polys.size() == 0)
{
stdcout << "fail merge 8\n";
return false;
}
stdcout << (polys[0]) << "\n";
}
stdcout << "Polygon { 2 2, 3 0, -3 4 } \n";
stdcout << "Polygon { -2 -2, 0 0, -1 -1 } \n";
si.clear();
pts.clear();
pts.push_back(Point(2, 2));
pts.push_back(Point(3, 0));
pts.push_back(Point(-3, 4));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
pts.clear();
pts.push_back(Point(-2, -2));
pts.push_back(Point(0, 0));
pts.push_back(Point(-1, -1));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
result.clear();
si.merge(result);
print(stdcout, si.pmd) << "\n";
if(!result.empty())
{
psd = (*(result.begin())).second;
stdcout << psd << "\n";
polys.clear();
psd.get(polys);
if(polys.size() == 0)
{
stdcout << "fail merge 9\n";
return false;
}
stdcout << (polys[0]) << "\n";
}
si.clear();
pts.clear();
//5624841,17616200,75000,9125000
//pts.push_back(Point(5624841,75000));
//pts.push_back(Point(5624841,9125000));
//pts.push_back(Point(17616200,9125000));
//pts.push_back(Point(17616200,75000));
pts.push_back(Point(12262940, 6652520 ));
pts.push_back(Point(12125750, 6652520 ));
pts.push_back(Point(12121272, 6652961 ));
pts.push_back(Point(12112981, 6656396 ));
pts.push_back(Point(12106636, 6662741 ));
pts.push_back(Point(12103201, 6671032 ));
pts.push_back(Point(12103201, 6680007 ));
pts.push_back(Point(12106636, 6688298 ));
pts.push_back(Point(12109500, 6691780 ));
pts.push_back(Point(12748600, 7330890 ));
pts.push_back(Point(15762600, 7330890 ));
pts.push_back(Point(15904620, 7472900 ));
pts.push_back(Point(15909200, 7473030 ));
pts.push_back(Point(15935830, 7476006 ));
pts.push_back(Point(15992796, 7499602 ));
pts.push_back(Point(16036397, 7543203 ));
pts.push_back(Point(16059993, 7600169 ));
pts.push_back(Point(16059993, 7661830 ));
pts.push_back(Point(16036397, 7718796 ));
pts.push_back(Point(15992796, 7762397 ));
pts.push_back(Point(15935830, 7785993 ));
pts.push_back(Point(15874169, 7785993 ));
pts.push_back(Point(15817203, 7762397 ));
pts.push_back(Point(15773602, 7718796 ));
pts.push_back(Point(15750006, 7661830 ));
pts.push_back(Point(15747030, 7635200 ));
pts.push_back(Point(15746900, 7630620 ));
pts.push_back(Point(15670220, 7553930 ));
pts.push_back(Point(14872950, 7553930 ));
pts.push_back(Point(14872950, 7626170 ));
pts.push_back(Point(14869973, 7661280 ));
pts.push_back(Point(14846377, 7718246 ));
pts.push_back(Point(14802776, 7761847 ));
pts.push_back(Point(14745810, 7785443 ));
pts.push_back(Point(14684149, 7785443 ));
pts.push_back(Point(14627183, 7761847 ));
pts.push_back(Point(14583582, 7718246 ));
pts.push_back(Point(14559986, 7661280 ));
pts.push_back(Point(14557070, 7636660 ));
pts.push_back(Point(14556670, 7625570 ));
pts.push_back(Point(13703330, 7625570 ));
pts.push_back(Point(13702930, 7636660 ));
pts.push_back(Point(13699993, 7661830 ));
pts.push_back(Point(13676397, 7718796 ));
pts.push_back(Point(13632796, 7762397 ));
pts.push_back(Point(13575830, 7785993 ));
pts.push_back(Point(13514169, 7785993 ));
pts.push_back(Point(13457203, 7762397 ));
pts.push_back(Point(13436270, 7745670 ));
pts.push_back(Point(13432940, 7742520 ));
pts.push_back(Point(12963760, 7742520 ));
pts.push_back(Point(12959272, 7742961 ));
pts.push_back(Point(12950981, 7746396 ));
pts.push_back(Point(12944636, 7752741 ));
pts.push_back(Point(12941201, 7761032 ));
pts.push_back(Point(12941201, 7770007 ));
pts.push_back(Point(12944636, 7778298 ));
pts.push_back(Point(12947490, 7781780 ));
pts.push_back(Point(13425330, 8259620 ));
pts.push_back(Point(15601330, 8259620 ));
pts.push_back(Point(15904620, 8562900 ));
pts.push_back(Point(15909200, 8563030 ));
pts.push_back(Point(15935830, 8566006 ));
pts.push_back(Point(15992796, 8589602 ));
pts.push_back(Point(16036397, 8633203 ));
pts.push_back(Point(16059993, 8690169 ));
pts.push_back(Point(16059993, 8751830 ));
pts.push_back(Point(16036397, 8808796 ));
pts.push_back(Point(15992796, 8852397 ));
pts.push_back(Point(15935830, 8875993 ));
pts.push_back(Point(15874169, 8875993 ));
pts.push_back(Point(15817203, 8852397 ));
pts.push_back(Point(15773602, 8808796 ));
pts.push_back(Point(15750006, 8751830 ));
pts.push_back(Point(15747030, 8725200 ));
pts.push_back(Point(15746900, 8720620 ));
pts.push_back(Point(15508950, 8482660 ));
pts.push_back(Point(14689890, 8482660 ));
pts.push_back(Point(14685412, 8483101 ));
pts.push_back(Point(14677121, 8486536 ));
pts.push_back(Point(14670776, 8492881 ));
pts.push_back(Point(14667341, 8501172 ));
pts.push_back(Point(14667341, 8510147 ));
pts.push_back(Point(14670776, 8518438 ));
pts.push_back(Point(14673630, 8521920 ));
pts.push_back(Point(14714620, 8562900 ));
pts.push_back(Point(14719200, 8563030 ));
pts.push_back(Point(14745830, 8566006 ));
pts.push_back(Point(14802796, 8589602 ));
pts.push_back(Point(14846397, 8633203 ));
pts.push_back(Point(14869993, 8690169 ));
pts.push_back(Point(14869993, 8751830 ));
pts.push_back(Point(14846397, 8808796 ));
pts.push_back(Point(14802796, 8852397 ));
pts.push_back(Point(14745830, 8875993 ));
pts.push_back(Point(14684169, 8875993 ));
pts.push_back(Point(14627203, 8852397 ));
pts.push_back(Point(14583602, 8808796 ));
pts.push_back(Point(14560006, 8751830 ));
pts.push_back(Point(14557030, 8725200 ));
pts.push_back(Point(14556900, 8720620 ));
pts.push_back(Point(14408270, 8571980 ));
pts.push_back(Point(13696320, 8571980 ));
pts.push_back(Point(13696320, 8675520 ));
pts.push_back(Point(13699963, 8690161 ));
pts.push_back(Point(13699963, 8751818 ));
pts.push_back(Point(13676368, 8808781 ));
pts.push_back(Point(13632771, 8852378 ));
pts.push_back(Point(13575808, 8875973 ));
pts.push_back(Point(13514151, 8875973 ));
pts.push_back(Point(13457188, 8852378 ));
pts.push_back(Point(13436270, 8835670 ));
pts.push_back(Point(13432940, 8832520 ));
pts.push_back(Point(13281760, 8832520 ));
pts.push_back(Point(13277272, 8832961 ));
pts.push_back(Point(13268981, 8836396 ));
pts.push_back(Point(13262636, 8842741 ));
pts.push_back(Point(13259201, 8851032 ));
pts.push_back(Point(13259201, 8860007 ));
pts.push_back(Point(13262636, 8868298 ));
pts.push_back(Point(13265500, 8871780 ));
pts.push_back(Point(13518710, 9125000 ));
pts.push_back(Point(16270720, 9125000 ));
pts.push_back(Point(16270720, 8939590 ));
pts.push_back(Point(17120780, 8939590 ));
pts.push_back(Point(17120780, 9125000 ));
pts.push_back(Point(17616200, 9125000 ));
pts.push_back(Point(17616200, 75000 ));
pts.push_back(Point(16024790, 75000 ));
pts.push_back(Point(16021460, 80700 ));
pts.push_back(Point(16016397, 88796 ));
pts.push_back(Point(15972796, 132397 ));
pts.push_back(Point(15915830, 155993 ));
pts.push_back(Point(15908730, 157240 ));
pts.push_back(Point(15905000, 157800 ));
pts.push_back(Point(15516800, 546000 ));
pts.push_back(Point(15905000, 934200 ));
pts.push_back(Point(15908730, 934760 ));
pts.push_back(Point(15915830, 936006 ));
pts.push_back(Point(15972796, 959602 ));
pts.push_back(Point(16016397, 1003203 ));
pts.push_back(Point(16039993, 1060169 ));
pts.push_back(Point(16039993, 1121830 ));
pts.push_back(Point(16016397, 1178796 ));
pts.push_back(Point(15972796, 1222397 ));
pts.push_back(Point(15915830, 1245993 ));
pts.push_back(Point(15854169, 1245993 ));
pts.push_back(Point(15797203, 1222397 ));
pts.push_back(Point(15753602, 1178796 ));
pts.push_back(Point(15730006, 1121830 ));
pts.push_back(Point(15728760, 1114730 ));
pts.push_back(Point(15728200, 1111000 ));
pts.push_back(Point(15363500, 746300 ));
pts.push_back(Point(14602620, 746300 ));
pts.push_back(Point(14598142, 746741 ));
pts.push_back(Point(14589851, 750176 ));
pts.push_back(Point(14583506, 756521 ));
pts.push_back(Point(14580071, 764812 ));
pts.push_back(Point(14580071, 773787 ));
pts.push_back(Point(14583506, 782078 ));
pts.push_back(Point(14586360, 785560 ));
pts.push_back(Point(14586370, 785560 ));
pts.push_back(Point(14735000, 934200 ));
pts.push_back(Point(14738730, 934760 ));
pts.push_back(Point(14745830, 936006 ));
pts.push_back(Point(14802796, 959602 ));
pts.push_back(Point(14846397, 1003203 ));
pts.push_back(Point(14869993, 1060169 ));
pts.push_back(Point(14870450, 1062550 ));
pts.push_back(Point(14872170, 1071980 ));
pts.push_back(Point(14972780, 1071980 ));
pts.push_back(Point(15925000, 2024200 ));
pts.push_back(Point(15928730, 2024760 ));
pts.push_back(Point(15935830, 2026006 ));
pts.push_back(Point(15992796, 2049602 ));
pts.push_back(Point(16036397, 2093203 ));
pts.push_back(Point(16059993, 2150169 ));
pts.push_back(Point(16059993, 2211830 ));
pts.push_back(Point(16036397, 2268796 ));
pts.push_back(Point(15992796, 2312397 ));
pts.push_back(Point(15935830, 2335993 ));
pts.push_back(Point(15874169, 2335993 ));
pts.push_back(Point(15817203, 2312397 ));
pts.push_back(Point(15773602, 2268796 ));
pts.push_back(Point(15750006, 2211830 ));
pts.push_back(Point(15748760, 2204730 ));
pts.push_back(Point(15748200, 2201000 ));
pts.push_back(Point(14869220, 1322020 ));
pts.push_back(Point(14088350, 1322020 ));
pts.push_back(Point(14083862, 1322461 ));
pts.push_back(Point(14075571, 1325896 ));
pts.push_back(Point(14069226, 1332241 ));
pts.push_back(Point(14065791, 1340532 ));
pts.push_back(Point(14065791, 1349507 ));
pts.push_back(Point(14069226, 1357798 ));
pts.push_back(Point(14072080, 1361280 ));
pts.push_back(Point(14072090, 1361280 ));
pts.push_back(Point(14735000, 2024200 ));
pts.push_back(Point(14738730, 2024760 ));
pts.push_back(Point(14745830, 2026006 ));
pts.push_back(Point(14802796, 2049602 ));
pts.push_back(Point(14846397, 2093203 ));
pts.push_back(Point(14869993, 2150169 ));
pts.push_back(Point(14869993, 2211830 ));
pts.push_back(Point(14846397, 2268796 ));
pts.push_back(Point(14802796, 2312397 ));
pts.push_back(Point(14745830, 2335993 ));
pts.push_back(Point(14684169, 2335993 ));
pts.push_back(Point(14627203, 2312397 ));
pts.push_back(Point(14583602, 2268796 ));
pts.push_back(Point(14560006, 2211830 ));
pts.push_back(Point(14558760, 2204730 ));
pts.push_back(Point(14558200, 2201000 ));
pts.push_back(Point(13752220, 1395020 ));
pts.push_back(Point(12991340, 1395020 ));
pts.push_back(Point(12986862, 1395461 ));
pts.push_back(Point(12978571, 1398896 ));
pts.push_back(Point(12972226, 1405241 ));
pts.push_back(Point(12968791, 1413532 ));
pts.push_back(Point(12968791, 1422507 ));
pts.push_back(Point(12972226, 1430798 ));
pts.push_back(Point(12975080, 1434280 ));
pts.push_back(Point(12975090, 1434280 ));
pts.push_back(Point(13565000, 2024200 ));
pts.push_back(Point(13568730, 2024760 ));
pts.push_back(Point(13575830, 2026006 ));
pts.push_back(Point(13632796, 2049602 ));
pts.push_back(Point(13676397, 2093203 ));
pts.push_back(Point(13699993, 2150169 ));
pts.push_back(Point(13699993, 2211830 ));
pts.push_back(Point(13676397, 2268796 ));
pts.push_back(Point(13632796, 2312397 ));
pts.push_back(Point(13575830, 2335993 ));
pts.push_back(Point(13514169, 2335993 ));
pts.push_back(Point(13457203, 2312397 ));
pts.push_back(Point(13413602, 2268796 ));
pts.push_back(Point(13390006, 2211830 ));
pts.push_back(Point(13388760, 2204730 ));
pts.push_back(Point(13388200, 2201000 ));
pts.push_back(Point(12655220, 1468020 ));
pts.push_back(Point(11894340, 1468020 ));
pts.push_back(Point(11889862, 1468461 ));
pts.push_back(Point(11881571, 1471896 ));
pts.push_back(Point(11875226, 1478241 ));
pts.push_back(Point(11871791, 1486532 ));
pts.push_back(Point(11871791, 1495507 ));
pts.push_back(Point(11875226, 1503798 ));
pts.push_back(Point(11878090, 1507280 ));
pts.push_back(Point(12395000, 2024200 ));
pts.push_back(Point(12398730, 2024760 ));
pts.push_back(Point(12405830, 2026006 ));
pts.push_back(Point(12462796, 2049602 ));
pts.push_back(Point(12506397, 2093203 ));
pts.push_back(Point(12529993, 2150169 ));
pts.push_back(Point(12529993, 2211830 ));
pts.push_back(Point(12506397, 2268796 ));
pts.push_back(Point(12462796, 2312397 ));
pts.push_back(Point(12405830, 2335993 ));
pts.push_back(Point(12344169, 2335993 ));
pts.push_back(Point(12287203, 2312397 ));
pts.push_back(Point(12243602, 2268796 ));
pts.push_back(Point(12220006, 2211830 ));
pts.push_back(Point(12218760, 2204730 ));
pts.push_back(Point(12218200, 2201000 ));
pts.push_back(Point(11558220, 1541020 ));
pts.push_back(Point(10797340, 1541020 ));
pts.push_back(Point(10792862, 1541461 ));
pts.push_back(Point(10784571, 1544896 ));
pts.push_back(Point(10778226, 1551241 ));
pts.push_back(Point(10774791, 1559532 ));
pts.push_back(Point(10774791, 1568507 ));
pts.push_back(Point(10778226, 1576798 ));
pts.push_back(Point(10781080, 1580280 ));
pts.push_back(Point(10781090, 1580280 ));
pts.push_back(Point(11225000, 2024200 ));
pts.push_back(Point(11228730, 2024760 ));
pts.push_back(Point(11235830, 2026006 ));
pts.push_back(Point(11292796, 2049602 ));
pts.push_back(Point(11336397, 2093203 ));
pts.push_back(Point(11359993, 2150169 ));
pts.push_back(Point(11359993, 2211830 ));
pts.push_back(Point(11336397, 2268796 ));
pts.push_back(Point(11292796, 2312397 ));
pts.push_back(Point(11235830, 2335993 ));
pts.push_back(Point(11174169, 2335993 ));
pts.push_back(Point(11117203, 2312397 ));
pts.push_back(Point(11073602, 2268796 ));
pts.push_back(Point(11050006, 2211830 ));
pts.push_back(Point(11048760, 2204730 ));
pts.push_back(Point(11048200, 2201000 ));
pts.push_back(Point(10461220, 1614020 ));
pts.push_back(Point( 5647400, 1614020 ));
pts.push_back(Point( 5642912, 1614461 ));
pts.push_back(Point( 5634621, 1617896 ));
pts.push_back(Point( 5628276, 1624241 ));
pts.push_back(Point( 5624841, 1632532 ));
pts.push_back(Point( 5624841, 1641507 ));
pts.push_back(Point( 5628276, 1649798 ));
pts.push_back(Point( 5631130, 1653280 ));
pts.push_back(Point( 5688490, 1710640 ));
pts.push_back(Point( 9722350, 1710640 ));
pts.push_back(Point(10034620, 2022900 ));
pts.push_back(Point(10039200, 2023030 ));
pts.push_back(Point(10065830, 2026006 ));
pts.push_back(Point(10122796, 2049602 ));
pts.push_back(Point(10166397, 2093203 ));
pts.push_back(Point(10189993, 2150169 ));
pts.push_back(Point(10189993, 2211830 ));
pts.push_back(Point(10166397, 2268796 ));
pts.push_back(Point(10158620, 2279450 ));
pts.push_back(Point(10158620, 2404900 ));
pts.push_back(Point(10548950, 2795240 ));
pts.push_back(Point(15586950, 2795240 ));
pts.push_back(Point(15904620, 3112900 ));
pts.push_back(Point(15909200, 3113030 ));
pts.push_back(Point(15935830, 3116006 ));
pts.push_back(Point(15992796, 3139602 ));
pts.push_back(Point(16036397, 3183203 ));
pts.push_back(Point(16059993, 3240169 ));
pts.push_back(Point(16059993, 3301830 ));
pts.push_back(Point(16036397, 3358796 ));
pts.push_back(Point(15992796, 3402397 ));
pts.push_back(Point(15935830, 3425993 ));
pts.push_back(Point(15874169, 3425993 ));
pts.push_back(Point(15817203, 3402397 ));
pts.push_back(Point(15773602, 3358796 ));
pts.push_back(Point(15750006, 3301830 ));
pts.push_back(Point(15747030, 3275200 ));
pts.push_back(Point(15746900, 3270620 ));
pts.push_back(Point(15494570, 3018280 ));
pts.push_back(Point(14675510, 3018280 ));
pts.push_back(Point(14671032, 3018721 ));
pts.push_back(Point(14662741, 3022156 ));
pts.push_back(Point(14656396, 3028501 ));
pts.push_back(Point(14652961, 3036792 ));
pts.push_back(Point(14652961, 3045767 ));
pts.push_back(Point(14656396, 3054058 ));
pts.push_back(Point(14659260, 3057540 ));
pts.push_back(Point(14714620, 3112900 ));
pts.push_back(Point(14719200, 3113030 ));
pts.push_back(Point(14745830, 3116006 ));
pts.push_back(Point(14802796, 3139602 ));
pts.push_back(Point(14846397, 3183203 ));
pts.push_back(Point(14869993, 3240169 ));
pts.push_back(Point(14869993, 3301830 ));
pts.push_back(Point(14846397, 3358796 ));
pts.push_back(Point(14802796, 3402397 ));
pts.push_back(Point(14745830, 3425993 ));
pts.push_back(Point(14684169, 3425993 ));
pts.push_back(Point(14627203, 3402397 ));
pts.push_back(Point(14583602, 3358796 ));
pts.push_back(Point(14560006, 3301830 ));
pts.push_back(Point(14557030, 3275200 ));
pts.push_back(Point(14556900, 3270620 ));
pts.push_back(Point(14370700, 3084410 ));
pts.push_back(Point(13702830, 3084410 ));
pts.push_back(Point(13702830, 3263160 ));
pts.push_back(Point(13700003, 3302210 ));
pts.push_back(Point(13676407, 3359176 ));
pts.push_back(Point(13632806, 3402777 ));
pts.push_back(Point(13575840, 3426373 ));
pts.push_back(Point(13514179, 3426373 ));
pts.push_back(Point(13457213, 3402777 ));
pts.push_back(Point(13413612, 3359176 ));
pts.push_back(Point(13390016, 3302210 ));
pts.push_back(Point(13387030, 3275200 ));
pts.push_back(Point(13386900, 3270620 ));
pts.push_back(Point(13266840, 3150550 ));
pts.push_back(Point(12532920, 3150550 ));
pts.push_back(Point(12532920, 3264990 ));
pts.push_back(Point(12529993, 3301820 ));
pts.push_back(Point(12506397, 3358786 ));
pts.push_back(Point(12462796, 3402387 ));
pts.push_back(Point(12405830, 3425983 ));
pts.push_back(Point(12344169, 3425983 ));
pts.push_back(Point(12287203, 3402387 ));
pts.push_back(Point(12243602, 3358786 ));
pts.push_back(Point(12220006, 3301820 ));
pts.push_back(Point(12217030, 3275200 ));
pts.push_back(Point(12216900, 3270620 ));
pts.push_back(Point(12157460, 3211170 ));
pts.push_back(Point(11362030, 3211170 ));
pts.push_back(Point(11360250, 3220520 ));
pts.push_back(Point(11359993, 3221830 ));
pts.push_back(Point(11336397, 3278796 ));
pts.push_back(Point(11292796, 3322397 ));
pts.push_back(Point(11235830, 3345993 ));
pts.push_back(Point(11174169, 3345993 ));
pts.push_back(Point(11117203, 3322397 ));
pts.push_back(Point(11096270, 3305670 ));
pts.push_back(Point(11092940, 3302520 ));
pts.push_back(Point(10680760, 3302520 ));
pts.push_back(Point(10676272, 3302961 ));
pts.push_back(Point(10667981, 3306396 ));
pts.push_back(Point(10661636, 3312741 ));
pts.push_back(Point(10658201, 3321032 ));
pts.push_back(Point(10658201, 3330007 ));
pts.push_back(Point(10661636, 3338298 ));
pts.push_back(Point(10664500, 3341780 ));
pts.push_back(Point(11264260, 3941550 ));
pts.push_back(Point(15643260, 3941550 ));
pts.push_back(Point(15904620, 4202900 ));
pts.push_back(Point(15909200, 4203030 ));
pts.push_back(Point(15935830, 4206006 ));
pts.push_back(Point(15992796, 4229602 ));
pts.push_back(Point(16036397, 4273203 ));
pts.push_back(Point(16059993, 4330169 ));
pts.push_back(Point(16059993, 4391830 ));
pts.push_back(Point(16036397, 4448796 ));
pts.push_back(Point(15992796, 4492397 ));
pts.push_back(Point(15935830, 4515993 ));
pts.push_back(Point(15874169, 4515993 ));
pts.push_back(Point(15817203, 4492397 ));
pts.push_back(Point(15773602, 4448796 ));
pts.push_back(Point(15750006, 4391830 ));
pts.push_back(Point(15747030, 4365200 ));
pts.push_back(Point(15746900, 4360620 ));
pts.push_back(Point(15550880, 4164590 ));
pts.push_back(Point(14825070, 4164590 ));
pts.push_back(Point(14825070, 4247610 ));
pts.push_back(Point(14846397, 4273213 ));
pts.push_back(Point(14869993, 4330179 ));
pts.push_back(Point(14869993, 4391840 ));
pts.push_back(Point(14846397, 4448806 ));
pts.push_back(Point(14802796, 4492407 ));
pts.push_back(Point(14745830, 4516003 ));
pts.push_back(Point(14684169, 4516003 ));
pts.push_back(Point(14627203, 4492407 ));
pts.push_back(Point(14583602, 4448806 ));
pts.push_back(Point(14560006, 4391840 ));
pts.push_back(Point(14557030, 4365200 ));
pts.push_back(Point(14556900, 4360620 ));
pts.push_back(Point(14432520, 4236230 ));
pts.push_back(Point(13702830, 4236230 ));
pts.push_back(Point(13702830, 4352930 ));
pts.push_back(Point(13699993, 4391750 ));
pts.push_back(Point(13676397, 4448716 ));
pts.push_back(Point(13632796, 4492317 ));
pts.push_back(Point(13575830, 4515913 ));
pts.push_back(Point(13514169, 4515913 ));
pts.push_back(Point(13457203, 4492317 ));
pts.push_back(Point(13413602, 4448716 ));
pts.push_back(Point(13390006, 4391750 ));
pts.push_back(Point(13387030, 4365200 ));
pts.push_back(Point(13386900, 4360620 ));
pts.push_back(Point(13334170, 4307880 ));
pts.push_back(Point(12532990, 4307880 ));
pts.push_back(Point(12532990, 4357550 ));
pts.push_back(Point(12529993, 4391760 ));
pts.push_back(Point(12506397, 4448726 ));
pts.push_back(Point(12462796, 4492327 ));
pts.push_back(Point(12405830, 4515923 ));
pts.push_back(Point(12344169, 4515923 ));
pts.push_back(Point(12287203, 4492327 ));
pts.push_back(Point(12243602, 4448726 ));
pts.push_back(Point(12220006, 4391760 ));
pts.push_back(Point(12217970, 4378710 ));
pts.push_back(Point(12216810, 4368500 ));
pts.push_back(Point(11363190, 4368500 ));
pts.push_back(Point(11362030, 4378710 ));
pts.push_back(Point(11359983, 4391828 ));
pts.push_back(Point(11336388, 4448791 ));
pts.push_back(Point(11292791, 4492388 ));
pts.push_back(Point(11235828, 4515983 ));
pts.push_back(Point(11174171, 4515983 ));
pts.push_back(Point(11117208, 4492388 ));
pts.push_back(Point(11096270, 4475670 ));
pts.push_back(Point(11092940, 4472520 ));
pts.push_back(Point(11057750, 4472520 ));
pts.push_back(Point(11053272, 4472961 ));
pts.push_back(Point(11044981, 4476396 ));
pts.push_back(Point(11038636, 4482741 ));
pts.push_back(Point(11035201, 4491032 ));
pts.push_back(Point(11035201, 4500007 ));
pts.push_back(Point(11038636, 4508298 ));
pts.push_back(Point(11041490, 4511780 ));
pts.push_back(Point(11573490, 5043780 ));
pts.push_back(Point(15655490, 5043780 ));
pts.push_back(Point(15904620, 5292900 ));
pts.push_back(Point(15909200, 5293030 ));
pts.push_back(Point(15935830, 5296006 ));
pts.push_back(Point(15992796, 5319602 ));
pts.push_back(Point(16036397, 5363203 ));
pts.push_back(Point(16059993, 5420169 ));
pts.push_back(Point(16059993, 5481830 ));
pts.push_back(Point(16036397, 5538796 ));
pts.push_back(Point(15992796, 5582397 ));
pts.push_back(Point(15935830, 5605993 ));
pts.push_back(Point(15874169, 5605993 ));
pts.push_back(Point(15817203, 5582397 ));
pts.push_back(Point(15773602, 5538796 ));
pts.push_back(Point(15750006, 5481830 ));
pts.push_back(Point(15747030, 5455200 ));
pts.push_back(Point(15746900, 5450620 ));
pts.push_back(Point(15563110, 5266820 ));
pts.push_back(Point(14857380, 5266820 ));
pts.push_back(Point(14857380, 5382430 ));
pts.push_back(Point(14869993, 5420179 ));
pts.push_back(Point(14869993, 5481840 ));
pts.push_back(Point(14846397, 5538806 ));
pts.push_back(Point(14802796, 5582407 ));
pts.push_back(Point(14745830, 5606003 ));
pts.push_back(Point(14684169, 5606003 ));
pts.push_back(Point(14627203, 5582407 ));
pts.push_back(Point(14583602, 5538806 ));
pts.push_back(Point(14560006, 5481840 ));
pts.push_back(Point(14557030, 5455200 ));
pts.push_back(Point(14556900, 5450620 ));
pts.push_back(Point(14444750, 5338460 ));
pts.push_back(Point(13702890, 5338460 ));
pts.push_back(Point(13702890, 5364400 ));
pts.push_back(Point(13699993, 5401800 ));
pts.push_back(Point(13676397, 5458766 ));
pts.push_back(Point(13632796, 5502367 ));
pts.push_back(Point(13575830, 5525963 ));
pts.push_back(Point(13514169, 5525963 ));
pts.push_back(Point(13457203, 5502367 ));
pts.push_back(Point(13413602, 5458766 ));
pts.push_back(Point(13390006, 5401800 ));
pts.push_back(Point(13389230, 5397620 ));
pts.push_back(Point(13387590, 5388060 ));
pts.push_back(Point(12532960, 5388060 ));
pts.push_back(Point(12532960, 5446220 ));
pts.push_back(Point(12529993, 5481820 ));
pts.push_back(Point(12506397, 5538786 ));
pts.push_back(Point(12462796, 5582387 ));
pts.push_back(Point(12405830, 5605983 ));
pts.push_back(Point(12344169, 5605983 ));
pts.push_back(Point(12287203, 5582387 ));
pts.push_back(Point(12266270, 5565670 ));
pts.push_back(Point(12262940, 5562520 ));
pts.push_back(Point(11737750, 5562520 ));
pts.push_back(Point(11733272, 5562961 ));
pts.push_back(Point(11724981, 5566396 ));
pts.push_back(Point(11718636, 5572741 ));
pts.push_back(Point(11715201, 5581032 ));
pts.push_back(Point(11715201, 5590007 ));
pts.push_back(Point(11718636, 5598298 ));
pts.push_back(Point(11721500, 5601780 ));
pts.push_back(Point(12287760, 6168050 ));
pts.push_back(Point(15689760, 6168050 ));
pts.push_back(Point(15904620, 6382900 ));
pts.push_back(Point(15909200, 6383030 ));
pts.push_back(Point(15935830, 6386006 ));
pts.push_back(Point(15992796, 6409602 ));
pts.push_back(Point(16036397, 6453203 ));
pts.push_back(Point(16059993, 6510169 ));
pts.push_back(Point(16059993, 6571830 ));
pts.push_back(Point(16036397, 6628796 ));
pts.push_back(Point(15992796, 6672397 ));
pts.push_back(Point(15935830, 6695993 ));
pts.push_back(Point(15874169, 6695993 ));
pts.push_back(Point(15817203, 6672397 ));
pts.push_back(Point(15773602, 6628796 ));
pts.push_back(Point(15750006, 6571830 ));
pts.push_back(Point(15747030, 6545200 ));
pts.push_back(Point(15746900, 6540620 ));
pts.push_back(Point(15597380, 6391090 ));
pts.push_back(Point(14858060, 6391090 ));
pts.push_back(Point(14858060, 6473860 ));
pts.push_back(Point(14869993, 6510179 ));
pts.push_back(Point(14869993, 6571840 ));
pts.push_back(Point(14846397, 6628806 ));
pts.push_back(Point(14802796, 6672407 ));
pts.push_back(Point(14745830, 6696003 ));
pts.push_back(Point(14684169, 6696003 ));
pts.push_back(Point(14627203, 6672407 ));
pts.push_back(Point(14583602, 6628806 ));
pts.push_back(Point(14560006, 6571840 ));
pts.push_back(Point(14557030, 6545200 ));
pts.push_back(Point(14556900, 6540620 ));
pts.push_back(Point(14479020, 6462730 ));
pts.push_back(Point(13702990, 6462730 ));
pts.push_back(Point(13702990, 6537170 ));
pts.push_back(Point(13700003, 6571840 ));
pts.push_back(Point(13676407, 6628806 ));
pts.push_back(Point(13632806, 6672407 ));
pts.push_back(Point(13575840, 6696003 ));
pts.push_back(Point(13514179, 6696003 ));
pts.push_back(Point(13457213, 6672407 ));
pts.push_back(Point(13413612, 6628806 ));
pts.push_back(Point(13390016, 6571840 ));
pts.push_back(Point(13387040, 6545550 ));
pts.push_back(Point(13386710, 6534380 ));
pts.push_back(Point(12533290, 6534380 ));
pts.push_back(Point(12532960, 6545550 ));
pts.push_back(Point(12529983, 6571828 ));
pts.push_back(Point(12506388, 6628791 ));
pts.push_back(Point(12462791, 6672388 ));
pts.push_back(Point(12405828, 6695983 ));
pts.push_back(Point(12344171, 6695983 ));
pts.push_back(Point(12287208, 6672388 ));
pts.push_back(Point(12266270, 6655670 ));
poly.set(pts.begin(), pts.end());
si.insert(poly, 444);
result.clear();
si.merge(result);
si.verify1();
print(stdcout, si.pmd) << "\n";
if(!result.empty())
{
psd = (*(result.begin())).second;
stdcout << psd << "\n";
std::vector<Point> outpts;
for(typename polygon_set_data<Unit>::iterator_type itr = psd.begin();
itr != psd.end(); ++itr)
{
outpts.push_back((*itr).first.first);
outpts.push_back((*itr).first.second);
}
polygon_sort(outpts.begin(), outpts.end());
for(std::size_t i = 0; i < outpts.size(); i+=2)
{
if(outpts[i] != outpts[i+1])
{
stdcout << "Polygon set not a closed figure\n";
stdcout << i << "\n";
stdcout << outpts[i] << " " << outpts[i+1] << "\n";
return 0;
}
}
polys.clear();
psd.get(polys);
if(polys.size() == 0)
{
stdcout << "fail merge 10\n";
return false;
}
stdcout << (polys[0]) << "\n";
}
for(unsigned int i = 0; i < 10; ++i)
{
stdcout << "random case # " << i << "\n";
si.clear();
pts.clear();
pts.push_back(Point(rand()%9-4, rand()%9-4));
pts.push_back(Point(rand()%9-4, rand()%9-4));
pts.push_back(Point(rand()%9-4, rand()%9-4));
polygon_data<Unit> poly1;
poly1.set(pts.begin(), pts.end());
stdcout << poly1 << "\n";
si.insert(poly1, 444);
pts.clear();
pts.push_back(Point(rand()%9-4, rand()%9-4));
pts.push_back(Point(rand()%9-4, rand()%9-4));
pts.push_back(Point(rand()%9-4, rand()%9-4));
polygon_data<Unit> poly2;
poly2.set(pts.begin(), pts.end());
stdcout << poly2 << "\n";
si.insert(poly2, 444);
result.clear();
si.merge(result);
print(stdcout, si.pmd) << "\n";
if(!result.empty())
{
psd = (*(result.begin())).second;
stdcout << psd << "\n";
polys.clear();
psd.get(polys);
if(polys.size() == 0)
{
si.clear();
si.insert(poly1, 333);
result.clear();
si.merge(result);
psd = (*(result.begin())).second;
std::vector<polygon_data<Unit> > polys1;
psd.get(polys1);
si.clear();
si.insert(poly2, 333);
result.clear();
si.merge(result);
psd = (*(result.begin())).second;
std::vector<polygon_data<Unit> > polys2;
psd.get(polys2);
if(!polys1.empty() || !polys2.empty())
{
stdcout << "fail random merge " << i << "\n";
return false;
}
}
}
if(!polys.empty())
stdcout << polys.size() << ": " << (polys[0]) << "\n";
}
return true;
}
template <typename stream_type>
static inline bool check_rectangle_trio(rectangle_data<Unit> rect1, rectangle_data<Unit> rect2, rectangle_data<Unit> rect3, stream_type& stdcout)
{
property_merge si;
std::map<std::set<property_type>, polygon_set_data<Unit> > result;
std::vector<polygon_data<Unit> > polys;
property_merge_90<property_type, Unit> si90;
std::map<std::set<property_type>, polygon_90_set_data<Unit> > result90;
std::vector<polygon_data<Unit> > polys90;
si.insert(rect1, 111);
si90.insert(rect1, 111);
stdcout << rect1 << "\n";
si.insert(rect2, 222);
si90.insert(rect2, 222);
stdcout << rect2 << "\n";
si.insert(rect3, 333);
si90.insert(rect3, 333);
stdcout << rect3 << "\n";
si.merge(result);
si90.merge(result90);
if(result.size() != result90.size())
{
stdcout << "merge failed with size mismatch\n";
return 0;
}
typename std::map<std::set<property_type>, polygon_90_set_data<Unit> >::iterator itr90 = result90.begin();
for(typename std::map<std::set<property_type>, polygon_set_data<Unit> >::iterator itr = result.begin();
itr != result.end(); ++itr)
{
for(typename std::set<property_type>::const_iterator set_itr = (*itr).first.begin();
set_itr != (*itr).first.end(); ++set_itr)
{
stdcout << (*set_itr) << " ";
}
stdcout << ") \n";
polygon_set_data<Unit> psd = (*itr).second;
polygon_90_set_data<Unit> psd90 = (*itr90).second;
polys.clear();
polys90.clear();
psd.get(polys);
psd90.get(polys90);
if(polys.size() != polys90.size())
{
stdcout << "merge failed with polygon count mismatch\n";
stdcout << psd << "\n";
for(std::size_t j = 0; j < polys.size(); ++j)
{
stdcout << polys[j] << "\n";
}
stdcout << "reference\n";
for(std::size_t j = 0; j < polys90.size(); ++j)
{
stdcout << polys90[j] << "\n";
}
return 0;
}
bool failed = false;
for(std::size_t j = 0; j < polys.size(); ++j)
{
stdcout << polys[j] << "\n";
stdcout << polys90[j] << "\n";
#ifdef BOOST_POLYGON_ICC
#pragma warning (push)
#pragma warning (disable:1572)
#endif
if(area(polys[j]) != area(polys90[j]))
{
#ifdef BOOST_POLYGON_ICC
#pragma warning (pop)
#endif
stdcout << "merge failed with area mismatch\n";
failed = true;
}
}
if(failed) return 0;
++itr90;
}
return true;
}
template <typename stream_type>
static inline bool test_manhattan_intersection(stream_type& stdcout)
{
rectangle_data<Unit> rect1, rect2, rect3;
set_points(rect1, (Point(-1, 2)), (Point(1, 4)));
set_points(rect2, (Point(-1, 2)), (Point(2, 3)));
set_points(rect3, (Point(-3, 0)), (Point(4, 2)));
if(!check_rectangle_trio(rect1, rect2, rect3, stdcout))
{
return false;
}
for(unsigned int i = 0; i < 100; ++i)
{
property_merge si;
std::map<std::set<property_type>, polygon_set_data<Unit> > result;
std::vector<polygon_data<Unit> > polys;
property_merge_90<property_type, Unit> si90;
std::map<std::set<property_type>, polygon_90_set_data<Unit> > result90;
std::vector<polygon_data<Unit> > polys90;
stdcout << "random case # " << i << "\n";
set_points(rect1, (Point(rand()%9-4, rand()%9-4)), (Point(rand()%9-4, rand()%9-4)));
set_points(rect2, (Point(rand()%9-4, rand()%9-4)), (Point(rand()%9-4, rand()%9-4)));
set_points(rect3, (Point(rand()%9-4, rand()%9-4)), (Point(rand()%9-4, rand()%9-4)));
if(!check_rectangle_trio(rect1, rect2, rect3, stdcout))
{
return false;
}
}
return true;
}
template <typename stream_type>
static inline bool test_intersection(stream_type& stdcout)
{
property_merge si;
rectangle_data<Unit> rect;
xl(rect, 0);
yl(rect, 10);
xh(rect, 30);
yh(rect, 20);
si.insert(rect, 333);
xl(rect, 10);
yl(rect, 0);
xh(rect, 20);
yh(rect, 30);
si.insert(rect, 444);
xl(rect, 15);
yl(rect, 0);
xh(rect, 25);
yh(rect, 30);
si.insert(rect, 555);
std::map<std::set<property_type>, polygon_set_data<Unit> > result;
si.merge(result);
print(stdcout, si.pmd) << "\n";
for(typename std::map<std::set<property_type>, polygon_set_data<Unit> >::iterator itr = result.begin();
itr != result.end(); ++itr)
{
stdcout << "( ";
for(typename std::set<property_type>::const_iterator set_itr = (*itr).first.begin();
set_itr != (*itr).first.end(); ++set_itr)
{
stdcout << (*set_itr) << " ";
}
stdcout << ") \n";
polygon_set_data<Unit> psd = (*itr).second;
stdcout << psd << "\n";
std::vector<polygon_data<Unit> > polys;
psd.get(polys);
for(std::size_t i = 0; i < polys.size(); ++i)
{
stdcout << polys[i] << "\n";
}
}
std::vector<Point> pts;
std::vector<polygon_data<Unit> > polys;
for(unsigned int i = 0; i < 10; ++i)
{
property_merge si2;
stdcout << "random case # " << i << "\n";
si.clear();
pts.clear();
pts.push_back(Point(rand()%9-4, rand()%9-4));
pts.push_back(Point(rand()%9-4, rand()%9-4));
pts.push_back(Point(rand()%9-4, rand()%9-4));
polygon_data<Unit> poly1;
poly1.set(pts.begin(), pts.end());
stdcout << poly1 << "\n";
si.insert(poly1, 444);
si2.insert(poly1, 333);
pts.clear();
pts.push_back(Point(rand()%9-4, rand()%9-4));
pts.push_back(Point(rand()%9-4, rand()%9-4));
pts.push_back(Point(rand()%9-4, rand()%9-4));
polygon_data<Unit> poly2;
poly2.set(pts.begin(), pts.end());
stdcout << poly2 << "\n";
si.insert(poly2, 444);
si2.insert(poly2, 444);
pts.clear();
pts.push_back(Point(rand()%9-4, rand()%9-4));
pts.push_back(Point(rand()%9-4, rand()%9-4));
pts.push_back(Point(rand()%9-4, rand()%9-4));
polygon_data<Unit> poly3;
poly3.set(pts.begin(), pts.end());
stdcout << poly3 << "\n";
si.insert(poly3, 444);
si2.insert(poly3, 555);
result.clear();
std::map<std::set<property_type>, polygon_set_data<Unit> > result2;
si.merge(result);
si2.merge(result2);
stdcout << "merged result\n";
for(typename std::map<std::set<property_type>, polygon_set_data<Unit> >::iterator itr = result.begin();
itr != result.end(); ++itr)
{
stdcout << "( ";
for(typename std::set<property_type>::const_iterator set_itr = (*itr).first.begin();
set_itr != (*itr).first.end(); ++set_itr)
{
stdcout << (*set_itr) << " ";
}
stdcout << ") \n";
polygon_set_data<Unit> psd = (*itr).second;
stdcout << psd << "\n";
std::vector<polygon_data<Unit> > polys2;
psd.get(polys2);
for(std::size_t ii = 0; ii < polys2.size(); ++ii)
{
stdcout << polys2[ii] << "\n";
}
}
stdcout << "intersected pmd\n";
print(stdcout, si2.pmd) << "\n";
stdcout << "intersected result\n";
for(typename std::map<std::set<property_type>, polygon_set_data<Unit> >::iterator itr = result2.begin();
itr != result2.end(); ++itr)
{
stdcout << "( ";
for(typename std::set<property_type>::const_iterator set_itr = (*itr).first.begin();
set_itr != (*itr).first.end(); ++set_itr)
{
stdcout << (*set_itr) << " ";
}
stdcout << ") \n";
polygon_set_data<Unit> psd = (*itr).second;
stdcout << psd << "\n";
std::vector<polygon_data<Unit> > polys2;
psd.get(polys2);
for(std::size_t ii = 0; ii < polys2.size(); ++ii)
{
stdcout << polys2[ii] << "\n";
}
}
si.clear();
for(typename std::map<std::set<property_type>, polygon_set_data<Unit> >::iterator itr = result2.begin();
itr != result2.end(); ++itr)
{
polys.clear();
(*itr).second.get(polys);
for(std::size_t j = 0; j < polys.size(); ++j)
{
si.insert(polys[j], 444);
}
}
result2.clear();
si.merge(result2);
stdcout << "remerged result\n";
for(typename std::map<std::set<property_type>, polygon_set_data<Unit> >::iterator itr = result2.begin();
itr != result2.end(); ++itr)
{
stdcout << "( ";
for(typename std::set<property_type>::const_iterator set_itr = (*itr).first.begin();
set_itr != (*itr).first.end(); ++set_itr)
{
stdcout << (*set_itr) << " ";
}
stdcout << ") \n";
polygon_set_data<Unit> psd = (*itr).second;
stdcout << psd << "\n";
std::vector<polygon_data<Unit> > polys2;
psd.get(polys2);
for(std::size_t ii = 0; ii < polys2.size(); ++ii)
{
stdcout << polys2[ii] << "\n";
}
}
std::vector<polygon_data<Unit> > polys2;
polys.clear();
(*(result.begin())).second.get(polys);
(*(result2.begin())).second.get(polys2);
if(!(polys == polys2))
{
stdcout << "failed intersection check # " << i << "\n";
return false;
}
}
return true;
}
};
template <typename Unit>
class arbitrary_boolean_op : public scanline_base<Unit>
{
private:
typedef int property_type;
typedef typename scanline_base<Unit>::Point Point;
//the first point is the vertex and and second point establishes the slope of an edge eminating from the vertex
//typedef std::pair<Point, Point> half_edge;
typedef typename scanline_base<Unit>::half_edge half_edge;
//scanline comparator functor
typedef typename scanline_base<Unit>::less_half_edge less_half_edge;
typedef typename scanline_base<Unit>::less_point less_point;
//this data structure assocates a property and count to a half edge
typedef std::pair<half_edge, std::pair<property_type, int> > vertex_property;
//this data type stores the combination of many half edges
typedef std::vector<vertex_property> property_merge_data;
//this is the data type used internally to store the combination of property counts at a given location
typedef std::vector<std::pair<property_type, int> > property_map;
//this data type is used internally to store the combined property data for a given half edge
typedef std::pair<half_edge, property_map> vertex_data;
property_merge_data pmd;
typename scanline_base<Unit>::evalAtXforYPack evalAtXforYPack_;
template<typename vertex_data_type>
class less_vertex_data
{
typename scanline_base<Unit>::evalAtXforYPack* pack_;
public:
less_vertex_data() : pack_() {}
less_vertex_data(typename scanline_base<Unit>::evalAtXforYPack* pack) : pack_(pack) {}
bool operator()(const vertex_data_type& lvalue, const vertex_data_type& rvalue) const
{
less_point lp;
if(lp(lvalue.first.first, rvalue.first.first)) return true;
if(lp(rvalue.first.first, lvalue.first.first)) return false;
Unit x = lvalue.first.first.get(HORIZONTAL);
int just_before_ = 0;
less_half_edge lhe(&x, &just_before_, pack_);
return lhe(lvalue.first, rvalue.first);
}
};
template <typename result_type, typename key_type, int op_type>
class boolean_output_functor
{
public:
boolean_output_functor() {}
void operator()(result_type& result, const half_edge& edge, const key_type& left, const key_type& right)
{
typename std::pair<half_edge, int> elem;
elem.first = edge;
elem.second = 1;
if(edge.second < edge.first) elem.second *= -1;
if(scanline_base<Unit>::is_vertical(edge)) elem.second *= -1;
#ifdef BOOST_POLYGON_MSVC
#pragma warning (push)
#pragma warning (disable: 4127)
#endif
if(op_type == 0) //OR
{
if(!left.empty() && right.empty())
{
result.insert_clean(elem);
}
else if(!right.empty() && left.empty())
{
elem.second *= -1;
result.insert_clean(elem);
}
}
else if(op_type == 1) //AND
{
if(left.size() == 2 && right.size() != 2)
{
result.insert_clean(elem);
}
else if(right.size() == 2 && left.size() != 2)
{
elem.second *= -1;
result.insert_clean(elem);
}
}
else if(op_type == 2) //XOR
{
if(left.size() == 1 && right.size() != 1)
{
result.insert_clean(elem);
}
else if(right.size() == 1 && left.size() != 1)
{
elem.second *= -1;
result.insert_clean(elem);
}
}
else //SUBTRACT
{
if(left.size() == 1)
{
if((*(left.begin())) == 0)
{
result.insert_clean(elem);
}
}
#ifdef BOOST_POLYGON_MSVC
#pragma warning (pop)
#endif
if(right.size() == 1)
{
if((*(right.begin())) == 0)
{
elem.second *= -1;
result.insert_clean(elem);
}
}
}
}
};
inline void sort_property_merge_data()
{
less_vertex_data<vertex_property> lvd(&evalAtXforYPack_);
polygon_sort(pmd.begin(), pmd.end(), lvd);
}
public:
inline arbitrary_boolean_op() : pmd(), evalAtXforYPack_() {}
inline arbitrary_boolean_op(const arbitrary_boolean_op& pm) : pmd(pm.pmd), evalAtXforYPack_(pm.evalAtXforYPack_) {}
inline arbitrary_boolean_op& operator=(const arbitrary_boolean_op& pm)
{
pmd = pm.pmd;
return *this;
}
enum BOOLEAN_OP_TYPE
{
BOOLEAN_OR = 0,
BOOLEAN_AND = 1,
BOOLEAN_XOR = 2,
BOOLEAN_NOT = 3
};
template <typename result_type, typename iT1, typename iT2>
inline void execute(result_type& result, iT1 b1, iT1 e1, iT2 b2, iT2 e2, int op)
{
//intersect data
insert(b1, e1, 0);
insert(b2, e2, 1);
property_merge_data tmp_pmd;
//#define BOOST_POLYGON_DEBUG_FILE
#ifdef BOOST_POLYGON_DEBUG_FILE
std::fstream debug_file;
debug_file.open("gtl_debug.txt", std::ios::out);
property_merge<Unit, property_type, std::vector<property_type> >::print(debug_file, pmd);
debug_file.close();
#endif
if(pmd.empty())
return;
line_intersection<Unit>::validate_scan(tmp_pmd, pmd.begin(), pmd.end());
pmd.swap(tmp_pmd);
sort_property_merge_data();
scanline<Unit, property_type, std::vector<property_type> > sl;
if(op == BOOLEAN_OR)
{
boolean_output_functor<result_type, std::vector<property_type>, 0> bof;
sl.scan(result, bof, pmd.begin(), pmd.end());
}
else if(op == BOOLEAN_AND)
{
boolean_output_functor<result_type, std::vector<property_type>, 1> bof;
sl.scan(result, bof, pmd.begin(), pmd.end());
}
else if(op == BOOLEAN_XOR)
{
boolean_output_functor<result_type, std::vector<property_type>, 2> bof;
sl.scan(result, bof, pmd.begin(), pmd.end());
}
else if(op == BOOLEAN_NOT)
{
boolean_output_functor<result_type, std::vector<property_type>, 3> bof;
sl.scan(result, bof, pmd.begin(), pmd.end());
}
}
inline void clear()
{
*this = arbitrary_boolean_op();
}
private:
template <typename iT>
void insert(iT b, iT e, int id)
{
for(;
b != e; ++b)
{
pmd.push_back(vertex_property(half_edge((*b).first.first, (*b).first.second),
std::pair<property_type, int>(id, (*b).second)));
}
}
};
template <typename Unit, typename stream_type>
bool test_arbitrary_boolean_op(stream_type& stdcout)
{
polygon_set_data<Unit> psd;
rectangle_data<Unit> rect;
set_points(rect, point_data<Unit>(0, 0), point_data<Unit>(10, 10));
psd.insert(rect);
polygon_set_data<Unit> psd2;
set_points(rect, point_data<Unit>(5, 5), point_data<Unit>(15, 15));
psd2.insert(rect);
std::vector<polygon_data<Unit> > pv;
pv.clear();
arbitrary_boolean_op<Unit> abo;
polygon_set_data<Unit> psd3;
abo.execute(psd3, psd.begin(), psd.end(), psd2.begin(), psd2.end(), arbitrary_boolean_op<Unit>::BOOLEAN_OR);
psd3.get(pv);
for(std::size_t i = 0; i < pv.size(); ++i)
{
stdcout << pv[i] << "\n";
}
pv.clear();
abo.clear();
psd3.clear();
abo.execute(psd3, psd.begin(), psd.end(), psd2.begin(), psd2.end(), arbitrary_boolean_op<Unit>::BOOLEAN_AND);
psd3.get(pv);
for(std::size_t i = 0; i < pv.size(); ++i)
{
stdcout << pv[i] << "\n";
}
pv.clear();
abo.clear();
psd3.clear();
abo.execute(psd3, psd.begin(), psd.end(), psd2.begin(), psd2.end(), arbitrary_boolean_op<Unit>::BOOLEAN_XOR);
psd3.get(pv);
for(std::size_t i = 0; i < pv.size(); ++i)
{
stdcout << pv[i] << "\n";
}
pv.clear();
abo.clear();
psd3.clear();
abo.execute(psd3, psd.begin(), psd.end(), psd2.begin(), psd2.end(), arbitrary_boolean_op<Unit>::BOOLEAN_NOT);
psd3.get(pv);
for(std::size_t i = 0; i < pv.size(); ++i)
{
stdcout << pv[i] << "\n";
}
return true;
}
template <typename Unit, typename property_type>
class arbitrary_connectivity_extraction : public scanline_base<Unit>
{
private:
typedef typename scanline_base<Unit>::Point Point;
//the first point is the vertex and and second point establishes the slope of an edge eminating from the vertex
//typedef std::pair<Point, Point> half_edge;
typedef typename scanline_base<Unit>::half_edge half_edge;
//scanline comparator functor
typedef typename scanline_base<Unit>::less_half_edge less_half_edge;
typedef typename scanline_base<Unit>::less_point less_point;
//this data structure assocates a property and count to a half edge
typedef std::pair<half_edge, std::pair<property_type, int> > vertex_property;
//this data type stores the combination of many half edges
typedef std::vector<vertex_property> property_merge_data;
//this is the data type used internally to store the combination of property counts at a given location
typedef std::vector<std::pair<property_type, int> > property_map;
//this data type is used internally to store the combined property data for a given half edge
typedef std::pair<half_edge, property_map> vertex_data;
property_merge_data pmd;
typename scanline_base<Unit>::evalAtXforYPack evalAtXforYPack_;
template<typename vertex_data_type>
class less_vertex_data
{
typename scanline_base<Unit>::evalAtXforYPack* pack_;
public:
less_vertex_data() : pack_() {}
less_vertex_data(typename scanline_base<Unit>::evalAtXforYPack* pack) : pack_(pack) {}
bool operator()(const vertex_data_type& lvalue, const vertex_data_type& rvalue) const
{
less_point lp;
if(lp(lvalue.first.first, rvalue.first.first)) return true;
if(lp(rvalue.first.first, lvalue.first.first)) return false;
Unit x = lvalue.first.first.get(HORIZONTAL);
int just_before_ = 0;
less_half_edge lhe(&x, &just_before_, pack_);
return lhe(lvalue.first, rvalue.first);
}
};
template <typename cT>
static void process_previous_x(cT& output)
{
std::map<point_data<Unit>, std::set<property_type> >& y_prop_map = output.first.second;
if(y_prop_map.empty()) return;
Unit x = output.first.first;
for(typename std::map<point_data<Unit>, std::set<property_type> >::iterator itr =
y_prop_map.begin(); itr != y_prop_map.end(); ++itr)
{
if((*itr).first.x() < x)
{
y_prop_map.erase(y_prop_map.begin(), itr);
continue;
}
for(typename std::set<property_type>::iterator inner_itr = itr->second.begin();
inner_itr != itr->second.end(); ++inner_itr)
{
std::set<property_type>& output_edges = (*(output.second))[*inner_itr];
typename std::set<property_type>::iterator inner_inner_itr = inner_itr;
++inner_inner_itr;
for( ; inner_inner_itr != itr->second.end(); ++inner_inner_itr)
{
output_edges.insert(output_edges.end(), *inner_inner_itr);
std::set<property_type>& output_edges_2 = (*(output.second))[*inner_inner_itr];
output_edges_2.insert(output_edges_2.end(), *inner_itr);
}
}
}
}
template <typename result_type, typename key_type>
class connectivity_extraction_output_functor
{
public:
connectivity_extraction_output_functor() {}
void operator()(result_type& result, const half_edge& edge, const key_type& left, const key_type& right)
{
Unit& x = result.first.first;
std::map<point_data<Unit>, std::set<property_type> >& y_prop_map = result.first.second;
point_data<Unit> pt = edge.first;
if(pt.x() != x) process_previous_x(result);
x = pt.x();
std::set<property_type>& output_set = y_prop_map[pt];
{
for(typename key_type::const_iterator itr1 =
left.begin(); itr1 != left.end(); ++itr1)
{
output_set.insert(output_set.end(), *itr1);
}
for(typename key_type::const_iterator itr2 =
right.begin(); itr2 != right.end(); ++itr2)
{
output_set.insert(output_set.end(), *itr2);
}
}
std::set<property_type>& output_set2 = y_prop_map[edge.second];
for(typename key_type::const_iterator itr1 =
left.begin(); itr1 != left.end(); ++itr1)
{
output_set2.insert(output_set2.end(), *itr1);
}
for(typename key_type::const_iterator itr2 =
right.begin(); itr2 != right.end(); ++itr2)
{
output_set2.insert(output_set2.end(), *itr2);
}
}
};
inline void sort_property_merge_data()
{
less_vertex_data<vertex_property> lvd(&evalAtXforYPack_);
polygon_sort(pmd.begin(), pmd.end(), lvd);
}
public:
inline arbitrary_connectivity_extraction() : pmd(), evalAtXforYPack_() {}
inline arbitrary_connectivity_extraction
(const arbitrary_connectivity_extraction& pm) : pmd(pm.pmd), evalAtXforYPack_(pm.evalAtXforYPack_) {}
inline arbitrary_connectivity_extraction& operator=
(const arbitrary_connectivity_extraction& pm)
{
pmd = pm.pmd;
return *this;
}
template <typename result_type>
inline void execute(result_type& result)
{
//intersect data
property_merge_data tmp_pmd;
line_intersection<Unit>::validate_scan(tmp_pmd, pmd.begin(), pmd.end());
pmd.swap(tmp_pmd);
sort_property_merge_data();
scanline<Unit, property_type, std::vector<property_type> > sl;
std::pair<std::pair<Unit, std::map<point_data<Unit>, std::set<property_type> > >,
result_type*> output
(std::make_pair(std::make_pair((std::numeric_limits<Unit>::max)(),
std::map<point_data<Unit>,
std::set<property_type> >()), &result));
connectivity_extraction_output_functor<std::pair<std::pair<Unit,
std::map<point_data<Unit>, std::set<property_type> > >, result_type*>,
std::vector<property_type> > ceof;
sl.scan(output, ceof, pmd.begin(), pmd.end());
process_previous_x(output);
}
inline void clear()
{
*this = arbitrary_connectivity_extraction();
}
template <typename iT>
void populateTouchSetData(iT begin, iT end,
property_type property)
{
for( ; begin != end; ++begin)
{
pmd.push_back(vertex_property(half_edge((*begin).first.first, (*begin).first.second),
std::pair<property_type, int>(property, (*begin).second)));
}
}
};
}
}
#endif
| [
"[email protected]"
] | |
3ffb2586f5a47b6c9a2b4654157c29f48f53bad6 | f94da7ec05e92e1a8593908143606e545b64c339 | /Visual Studio 2013/projects/MFC2-Edit/DrawLines/DrawLinesWin.cpp | f70571d742d99beba6f5b589510cc8db0eb07cc7 | [] | no_license | jonhassall/AdvancedSoftwareEngineeringSOFT40051 | 4eaafa655335878fb108c56ec0d59ef11b9481e8 | 968c2df2aa670193313c1b157a4da6dadff15334 | refs/heads/master | 2016-09-03T06:50:46.398250 | 2014-12-01T21:44:13 | 2014-12-01T21:44:13 | 26,221,759 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,607 | cpp | // DrawLinesWin.cpp
// Draw lines on screen
#include <afxwin.h> // MFC application framework
#include "DrawLinesWin.h" // application class
#include "Points.h" // application class
CDrawLinesWin::CDrawLinesWin() // main window
{
// to add text to screen
m_CurrentLine = 0; // initialise current line receiving key stroke
m_LineLengths [m_CurrentLine] = 0; // initialise current line of text
Create( NULL, CString("Draw Lines") ); // Frame window with title
// add menu and submenu dynamically
m_menu.CreateMenu();
m_popupmenu.CreatePopupMenu();
// Add items to the sub menu and menu
m_popupmenu.AppendMenuW(MF_STRING, ID_FILE_LINEDRAW, CString("Draw"));
m_popupmenu.AppendMenuW(MF_STRING, ID_FILE_ADD, CString("Add"));
m_popupmenu.AppendMenuW(MF_STRING, ID_FILE_EXIT, CString("Exit"));
m_menu.AppendMenuW(MF_STRING | MF_POPUP, (UINT)m_popupmenu.m_hMenu, CString("File"));
SetMenu(&m_menu); // ??
// create a pen for solid, 2 pixel wide, red lines
m_Pen.CreatePen( PS_SOLID, 2, RGB( 255, 0, 0 ) ); // red
m_Brush.CreateSolidBrush( RGB( 0, 255, 0 ) ); // green
m_redComponent = 0;
m_greenComponent = 0;
m_blueComponent = 0;
// data to draw lines from
//itsPoints = thePoints;
}
// afx_msg precedes each message handler function
// refresh window when requested to by the system
afx_msg void CDrawLinesWin::OnPaint()
{
CPaintDC dc( this ); // get device context for paint
// get current window size - not required
//CRect rect;
//GetClientRect( rect ); // get current client area size
// get initial and next points to draw line between
int x = itsPoints.getNextX(); // initial x
int y = itsPoints.getNextY(); // initial y
itsPoints.incrementIndex();
int nextX = itsPoints.getNextX(); // next x
int nextY = itsPoints.getNextY(); // next y
// select solid coloured brush, saving default brush
CBrush *pBrushSv = dc.SelectObject( &m_Brush );
// select coloured pen, saving default pen
CPen *pPenSv = dc.SelectObject( &m_Pen );
// write some text to the screen
dc.SetTextColor( RGB( m_redComponent, m_greenComponent, m_blueComponent ) );
dc.SetBkColor( RGB(255,255,255) );
dc.TextOutW(x+50,y,CString("A line drawn"),strlen("A line drawn"));
// write the coordinates after formatting to a CString
CString aLocation;
aLocation.Format(_T("%d,%d"), x, y);
dc.TextOutW(x + 50, y + 50, aLocation, aLocation.GetLength());
// draw a line between the initial and next points
dc.MoveTo( x, y ); // set starting point
dc.LineTo( nextX, nextY ); // draw line
// output to screen the characters stored from key strokes (starting at top left corner)
int aCurrentCharPosition = m_LineLengths[m_CurrentLine]++;
m_LineArray [m_CurrentLine] [aCurrentCharPosition] = '_'; // add cursor at end of characters to display
for (int i=0;i<=m_CurrentLine;i++) // paint lines of text
{
dc.TextOutW(1,lineHeight*i,CString(m_LineArray [i]),m_LineLengths [i]); // x-coordinate, y-coordinate, string to be drawn, length of string
}
m_LineLengths [m_CurrentLine]--; // remove cursor from end of characters
// restore default pen and brush
dc.SelectObject( pBrushSv );
dc.SelectObject( pPenSv );
}
// afx_msg precedes each message handler function
afx_msg void CDrawLinesWin::OnExit()
{
SendMessage( WM_CLOSE );
}
// afx_msg precedes each message handler function
afx_msg void CDrawLinesWin::OnLineDraw()
{
// REDRAW WINDOW
RedrawWindow(NULL, NULL,
RDW_INVALIDATE | RDW_UPDATENOW | RDW_ERASE);
}
// afx_msg precedes each message handler function
afx_msg void CDrawLinesWin::OnAdd()
{
itsPoints.addCirclePoints();
//MessageBox(CString("Test OnAdd"),CString("Title"));
}
// afx_msg precedes each message handler function
afx_msg void CDrawLinesWin::OnChar( UINT uChar, UINT uRepCnt, UINT uFlg)
{
// add key strokes to array of line strings
switch(uChar)
{
case '\r': // start new line
m_CurrentLine++;
if (m_CurrentLine>=noLines) m_CurrentLine = 0; // wrap to first line
m_LineLengths[m_CurrentLine] = 0;
break;
case '\b': // backspace removes previous char
if (m_LineLengths[m_CurrentLine] > 0) m_LineLengths[m_CurrentLine]--; // remove last char
break;
default: // add character to end of current line of text
int aCurrentCharPosition = m_LineLengths[m_CurrentLine]++;
m_LineArray [m_CurrentLine] [aCurrentCharPosition] = uChar;
if (m_LineLengths[m_CurrentLine] >= noCharsInLine)
{
if (++m_CurrentLine >= noLines) m_CurrentLine = 0; // wrap around to start of top line
m_LineLengths[m_CurrentLine] = 0; // around to start of next line
}
}
InvalidateRect(NULL); // update paint area when next WM_PAINT message is sent
}
// afx_msg precedes each message handler function
afx_msg void CDrawLinesWin::OnTimer(UINT nIDEvent)
{
// do something
CFrameWnd::OnTimer(nIDEvent);
m_redComponent = (m_redComponent+20)%256;
m_greenComponent = (m_greenComponent+60)%256;
m_blueComponent = (m_blueComponent+100)%256;
}
// afx_msg precedes each message handler function
afx_msg void CDrawLinesWin::OnDestroy()
{
KillTimer(1);
}
BEGIN_MESSAGE_MAP( CDrawLinesWin, CFrameWnd )
ON_WM_PAINT() // OnPaint() when screen changes
ON_COMMAND( ID_FILE_LINEDRAW, OnLineDraw ) // OnLineDraw()
ON_COMMAND( ID_FILE_EXIT, OnExit ) // OnExit()
ON_COMMAND( ID_FILE_ADD, OnAdd ) // OnAdd()
ON_WM_CHAR() // OnChar() when key pressed
ON_WM_TIMER() // OnTimer() when key pressed
ON_WM_DESTROY() // OnDestroy() when key pressed
END_MESSAGE_MAP()
| [
"[email protected]"
] | |
8356016a0325574c57fe217a333223f44f6b6fc2 | 5188aed199e50683ada5193f68da4805e60e114b | /Sem_5/Compilers/Laboratory/Assignment_6/ass6_17CS10038_17CS30022_target_translator.cxx | 81aee6b301786362f20060cf18596104aab808f6 | [] | no_license | TheLethalCode/KGP_Academics | 4c35bc5ef08b52d9bfbd52ccbfcc284abe2a13cf | 744494f38b6cfc63600b24bb610df848d1299f2f | refs/heads/master | 2022-06-06T03:45:37.065064 | 2022-05-08T16:19:34 | 2022-05-08T16:19:34 | 223,632,661 | 73 | 42 | null | null | null | null | UTF-8 | C++ | false | false | 32,698 | cxx | #include "ass6_17CS10038_17CS30022_translator.h"
#include "y.tab.h"
#define perc %
extern quad_arr glob_quad;
extern int next_instr;
map<int,int> mp_set;
stack<string> params_stack;
string names1 = "Kousshik Raj";
string names2 = "Prashant";
stack<int> types_stack;
stack<int> offset_stack;
stack<int> ptrarr_stack;
extern std::vector< string > vs;
extern std::vector<string> cs;
int add_off;
void symtab::mark_labels()
{
int count=1;
int i = 0;
while( i < next_instr)
{
switch(glob_quad.arr[i].op)
{
case Q_GOTO:
case Q_IF_EQUAL:
case Q_IF_NOT_EQUAL:
case Q_IF_EXPRESSION:
case Q_IF_NOT_EXPRESSION:
case Q_IF_LESS:
case Q_IF_GREATER:
case Q_IF_LESS_OR_EQUAL:
case Q_IF_GREATER_OR_EQUAL:
if(glob_quad.arr[i].result!="-1")
{
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
if(mp_set.find(atoi(glob_quad.arr[i].result.c_str()))==mp_set.end())
{
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
mp_set[atoi(glob_quad.arr[i].result.c_str())]=count;
count++;
}
}
}
i++;
}
}
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
void symtab::function_prologue(FILE *fp,int count)
{
fprintf(fp,"\n\t.globl\t%s",name.c_str());
fprintf(fp,"\n\t.type\t%s, @function",name.c_str());
fprintf(fp,"\n%s:",name.c_str());
fprintf(fp,"\n.LFB%d:",count);
fprintf(fp,"\n\tpushq\t%%rbp");
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovq\t%%rsp, %%rbp");
int t=-offset;
fprintf(fp,"\n\tsubq\t$%d, %%rsp",t);
}
void symtab::global_variables(FILE *fp)
{
int i = 0;
while( i < symbol_tab.size())
{
if(symbol_tab[i]->name[0]!='t' &&symbol_tab[i]->tp_n!=NULL&&symbol_tab[i]->var_type!="func")
{
if(symbol_tab[i]->tp_n->basetp==tp_int)
{
vs.push_back(symbol_tab[i]->name);
if(symbol_tab[i]->isInitialized==false)
{
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\t.comm\t%s,4,4",symbol_tab[i]->name.c_str());
}
else
{
fprintf(fp,"\n\t.globl\t%s",symbol_tab[i]->name.c_str());
fprintf(fp,"\n\t.data");
fprintf(fp,"\n\t.align 4");
fprintf(fp,"\n\t.type\t%s, @object",symbol_tab[i]->name.c_str());
fprintf(fp,"\n\t.size\t%s ,4",symbol_tab[i]->name.c_str());
fprintf(fp,"\n%s:",symbol_tab[i]->name.c_str());
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\t.long %d",symbol_tab[i]->i_val.int_val);
}
}
if(symbol_tab[i]->tp_n->basetp==tp_char)
{
cs.push_back(symbol_tab[i]->name);
if(symbol_tab[i]->isInitialized==false)
{
fprintf(fp,"\n\t.comm\t%s,1,1",symbol_tab[i]->name.c_str());
}
else
{
fprintf(fp,"\n\t.globl\t%s",symbol_tab[i]->name.c_str());
fprintf(fp,"\n\t.data");
fprintf(fp,"\n\t.type\t%s, @object",symbol_tab[i]->name.c_str());
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\t.size\t%s ,1",symbol_tab[i]->name.c_str());
fprintf(fp,"\n%s:",symbol_tab[i]->name.c_str());
fprintf(fp,"\n\t.byte %c",symbol_tab[i]->i_val.char_val);
}
}
}
i++;
}
fprintf(fp,"\n\t.text");
}
int fact421(int n)
{
if( n > 12) return -1;
else
{
int i =1, ans = 1;
while(i <= n)
{
ans *= i;
i++;
}
return ans;
}
}
void symtab::assign_offset()
{
int curr_offset=0;
int param_offset=16;
no_params=0;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
for(int i = (symbol_tab).size()-1; i>=0; i--)
{
if(symbol_tab[i]->ispresent==false)
continue;
if(symbol_tab[i]->var_type=="param" && symbol_tab[i]->isdone==false)
{
no_params++;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
if(symbol_tab[i]->tp_n && symbol_tab[i]->tp_n->basetp==tp_arr)
{
if(symbol_tab[i]->tp_n->size==-1)
{
symbol_tab[i]->isptrarr=true;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
}
symbol_tab[i]->size=8;
}
symbol_tab[i]->offset=curr_offset-symbol_tab[i]->size;
curr_offset=curr_offset-symbol_tab[i]->size;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
symbol_tab[i]->isdone=true;
}
if(no_params==6)
break;
}
for(int i = 0; i<(symbol_tab).size(); i++)
{
if(symbol_tab[i]->ispresent==false)
continue;
if(symbol_tab[i]->var_type!="return"&&symbol_tab[i]->var_type!="param" && symbol_tab[i]->isdone==false)
{
symbol_tab[i]->offset=curr_offset-symbol_tab[i]->size;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
curr_offset=curr_offset-symbol_tab[i]->size;
symbol_tab[i]->isdone=true;
}
else if(symbol_tab[i]->var_type=="param" && symbol_tab[i]->isdone==false)
{
if(symbol_tab[i]->tp_n && symbol_tab[i]->tp_n->basetp==tp_arr)
{
if(symbol_tab[i]->tp_n->size==-1)
{
symbol_tab[i]->isptrarr=true;
}
symbol_tab[i]->size=8;
}
symbol_tab[i]->isdone=true;
no_params++;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
symbol_tab[i]->offset=param_offset;
param_offset=param_offset+symbol_tab[i]->size;
}
}
offset=curr_offset;
}
int partition(int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than the pivot
if (arr[j] < pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
return (i + 1);
}
bool checkPrime123(int n)
{
int ans = 0;
for(int i=2;i <= sqrt(n); i++)
{
if( n perc i)
return false;
}
return true;
}
string symtab::assign_reg(int type_of,int no)
{
string s="NULL";
if(type_of==tp_char){
switch(no){
case 0: s = "dil";
break;
case 1: s = "sil";
break;
case 2: s = "dl";
break;
case 3: s = "cl";
break;
case 4: s = "r8b";
break;
case 5: s = "r9b";
break;
}
}
else if(type_of == tp_int){
switch(no){
case 0: s = "edi";
break;
case 1: s = "esi";
break;
case 2: s = "edx";
break;
case 3: s = "ecx";
break;
case 4: s = "r8d";
break;
case 5: s = "r9d";
break;
}
}
else
{
switch(no){
case 0: s = "rdi";
break;
case 1: s = "rsi";
break;
case 2: s = "rdx";
break;
case 3: s = "rcx";
break;
case 4: s = "r8";
break;
case 5: s = "r9";
break;
}
}
return s;
}
void quickSort(int arr[],int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is now
at right place */
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1); // Before pi
quickSort(arr, pi + 1, high); // After pi
}
}
bool com123po(int n)
{
bool val = checkPrime123(n);
return !val;
}
int symtab::function_call(FILE *fp)
{
int c=0;
fprintf(fp,"\n\tpushq %%rbp");
int count=0;
while(count<6 && params_stack.size())
{
string p=params_stack.top();
int btp=types_stack.top();
int off=offset_stack.top();
int parr=ptrarr_stack.top();
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
params_stack.pop();
types_stack.pop();
offset_stack.pop();
ptrarr_stack.pop();
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
string temp_str=assign_reg(btp,count);
if(temp_str!="NULL")
{
if(btp==tp_int)
{
fprintf(fp,"\n\tmovl\t%d(%%rbp) , %%%s",off,temp_str.c_str());
}
else if(btp==tp_char)
{
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovb\t%d(%%rbp), %%%s",off,temp_str.c_str());
}
else if(btp==tp_arr && parr==1)
{
fprintf(fp,"\n\tmovq\t%d(%%rbp), %%%s",off,temp_str.c_str());
}
else if(btp==tp_arr)
{
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tleaq\t%d(%%rbp), %%%s",off,temp_str.c_str());
}
else
{
fprintf(fp,"\n\tmovq\t%d(%%rbp), %%%s",off,temp_str.c_str());
}
count++;
}
}
while(params_stack.size())
{
string p=params_stack.top();
int btp=types_stack.top();
int off=offset_stack.top();
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
int parr=ptrarr_stack.top();
params_stack.pop();
types_stack.pop();
offset_stack.pop();
ptrarr_stack.pop();
if(btp==tp_int)
{
fprintf(fp,"\n\tsubq $4, %%rsp");
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovl\t%%eax, (%%rsp)");
c+=4;
}
else if(btp==tp_arr && parr==1)
{
fprintf(fp,"\n\tsubq $8, %%rsp");
fprintf(fp,"\n\tmovq\t%d(%%rbp), %%rax",off);
fprintf(fp,"\n\tmovq\t%%rax, (%%rsp)");
c+=8;
}
else if(btp==tp_arr)
{
fprintf(fp,"\n\tsubq $8, %%rsp");
fprintf(fp,"\n\tleaq\t%d(%%rbp), %%rax",off);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovq\t%%rax, (%%rsp)");
c+=8;
}
else if(btp==tp_char)
{
fprintf(fp,"\n\tsubq $4, %%rsp");
fprintf(fp,"\n\tmovsbl\t%d(%%rbp), %%eax",off);
fprintf(fp,"\n\tmovl\t%%eax, (%%rsp)");
c+=4;
}
else
{
fprintf(fp,"\n\tsubq $8, %%rsp");
fprintf(fp,"\n\tmovq\t%d(%%rbp), %%rax",off);
fprintf(fp,"\n\tmovq\t%%rax, (%%rsp)");
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
c+=8;
}
}
return c;
}
bool check1Prime1(int n)
{
int ans = 0;
for(int i=2;i <= sqrt(n); i++)
{
if( n perc i)
return false;
}
for(int i=2;i <= n; i+=3)
{
if( n perc i)
return false;
}
while(false) break;
return true;
}
void symtab::function_restore(FILE *fp)
{
int count=0;
string regname;
for(int i=symbol_tab.size()-1;i>=0;i--)
{
if(symbol_tab[i]->ispresent==false)
continue;
if(symbol_tab[i]->var_type=="param" && symbol_tab[i]->offset<0)
{
if(symbol_tab[i]->tp_n->basetp == tp_char){
regname = assign_reg(tp_char,count);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovb\t%%%s, %d(%%rbp)",regname.c_str(),symbol_tab[i]->offset);
}
else if(symbol_tab[i]->tp_n->basetp == tp_int){
regname = assign_reg(tp_int,count);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovl\t%%%s, %d(%%rbp)",regname.c_str(),symbol_tab[i]->offset);
}
else {
regname = assign_reg(10,count);
fprintf(fp,"\n\tmovq\t%%%s, %d(%%rbp)",regname.c_str(),symbol_tab[i]->offset);
}
count++;
}
if(count==6)
break;
}
}
bool check2Prime2(int n, string name)
{
if(name == "whatebn")
return false;
int ans = 0;
for(int i=2;i <= sqrt(n); i+=2)
{
if( n perc i)
return false;
}
for(int i=2;i <= n; i+=3)
{
if( n perc i)
return false;
}
vector< set< pair< pair< int, int> , int > > > twmp;
while(false) break;
return true;
}
void symtab::gen_internal_code(FILE *fp,int ret_count)
{
int i;
for(i = start_quad; i <=end_quad; i++)
{
opcode &opx =glob_quad.arr[i].op;
string &arg1x =glob_quad.arr[i].arg1;
string &arg2x =glob_quad.arr[i].arg2;
string &resx =glob_quad.arr[i].result;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
int offr,off1,off2;
int flag1=1;
int flag2=1;
int flag3=1;
int j;
fprintf(fp,"\n# %d:",i);
//printf("dsda %s\n",resx.c_str());
if(search(resx))
{
offr = search(resx)->offset;
fprintf(fp,"res = %s ",search(resx)->name.c_str());
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
}
else if(glob_quad.arr[i].result!=""&& findg(glob_quad.arr[i].result))
{
flag3=0;
}
if(search(arg1x))
{
off1 = search(arg1x)->offset;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"arg1 = %s ",search(arg1x)->name.c_str());
}
else if(glob_quad.arr[i].arg1!="" && findg(glob_quad.arr[i].arg1))
{
flag1=0;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
}
if(search(arg2x))
{
off2 = search(arg2x)->offset;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"arg2 = %s ",search(arg2x)->name.c_str());
}
else if(glob_quad.arr[i].arg2!="" && findg(glob_quad.arr[i].arg2))
{
flag2=0;
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
}
if(flag1==0)
{
if(findg(arg1x)==2)
fprintf(fp,"\n\tmovzbl\t%s(%%rip), %%eax",arg1x.c_str());
else
fprintf(fp,"\n\tmovl\t%s(%%rip), %%eax",arg1x.c_str());
}
if(flag2==0)
{
if(findg(arg1x)==2)
fprintf(fp,"\n\tmovzbl\t%s(%%rip), %%edx",arg2x.c_str());
else
fprintf(fp,"\n\tmovl\t%s(%%rip), %%edx",arg2x.c_str());
}
if(mp_set.find(i)!=mp_set.end())
{
//Generate Label here
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n.L%d:",mp_set[i]);
}
switch(opx)
{
case Q_PLUS:
if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_char)
{
if(flag1!=0)
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
if(flag2!=0)
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%edx",off2);
fprintf(fp,"\n\taddl\t%%edx, %%eax");
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
if(flag3!=0)
fprintf(fp,"\n\tmovb\t%%al, %d(%%rbp)",offr);
else
fprintf(fp,"\n\tmovb\t%%al, %s(%%rip)",resx.c_str());
}
else
{
if(flag1!=0)
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
if(flag2!=0)
{if(arg2x[0]>='0' && arg2x[0]<='9')
fprintf(fp,"\n\tmovl\t$%s, %%edx",arg2x.c_str());
else
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%edx",off2);
}
fprintf(fp,"\n\taddl\t%%edx, %%eax");
if(flag3!=0)
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);
else
fprintf(fp,"\n\tmovl\t%%eax, %s(%%rip)",resx.c_str());
}
break;
case Q_MINUS:
if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_char)
{
if(flag1!=0)
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
if(flag2!=0)
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%edx",off2);
fprintf(fp,"\n\tsubl\t%%edx, %%eax");
if(flag3!=0)
fprintf(fp,"\n\tmovb\t%%al, %d(%%rbp)",offr);
else
fprintf(fp,"\n\tmovb\t%%al, %s(%%rip)",resx.c_str());
}
else
{
if(flag1!=0)
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
// Direct Number access
if(flag2!=0)
{if(arg2x[0]>='0' && arg2x[0]<='9')
fprintf(fp,"\n\tmovl\t$%s, %%edx",arg2x.c_str());
else
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%edx",off2);}
fprintf(fp,"\n\tsubl\t%%edx, %%eax");
if(flag3!=0)
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);
else
fprintf(fp,"\n\tmovl\t%%eax, %s(%%rip)",resx.c_str());
}
break;
case Q_MULT:
if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_char)
{
if(flag1!=0)
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
if(flag2!=0)
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%edx",off2);
fprintf(fp,"\n\timull\t%%edx, %%eax");
if(flag3!=0)
fprintf(fp,"\n\tmovb\t%%al, %d(%%rbp)",offr);
else
fprintf(fp,"\n\tmovb\t%%al, %s(%%rip)",resx.c_str());
}
else
{
if(flag1!=0)
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
if(flag2!=0)
{if(arg2x[0]>='0' && arg2x[0]<='9')
{
fprintf(fp,"\n\tmovl\t$%s, %%ecx",arg2x.c_str());
fprintf(fp,"\n\timull\t%%ecx, %%eax");
}
else
fprintf(fp,"\n\timull\t%d(%%rbp), %%eax",off2);}
if(flag3!=0)
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);
else
fprintf(fp,"\n\tmovl\t%%eax, %s(%%rip)",resx.c_str());
}
break;
case Q_DIVIDE:
if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_char)
{
if(flag1!=0)
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tcltd");
if(flag2!=0)
fprintf(fp,"\n\tidivl\t%d(%%rbp), %%eax",off2);
else
fprintf(fp,"\n\tidivl\t%%edx, %%eax");
if(flag3!=0)
fprintf(fp,"\n\tmovb\t%%al, %d(%%rbp)",offr);
else
fprintf(fp,"\n\tmovb\t%%al, %s(%%rip)",resx.c_str());
}
else{
if(flag1!=0)
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tcltd");
if(flag2!=0)
fprintf(fp,"\n\tidivl\t%d(%%rbp), %%eax",off2);
else
fprintf(fp,"\n\tidivl\t%%edx, %%eax");
if(flag3!=0)
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);
else
fprintf(fp,"\n\tmovl\t%%eax, %s(%%rip)",resx.c_str());
}
break;
case Q_MODULO:
if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tcltd");
fprintf(fp,"\n\tidivl\t%d(%%rbp), %%eax",off2);
fprintf(fp,"\n\tmovl\t%%edx, %%eax");
fprintf(fp,"\n\tmovb\t%%al, %d(%%rbp)",offr);
}
else{
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tcltd");
fprintf(fp,"\n\tidivl\t%d(%%rbp), %%eax",off2);
fprintf(fp,"\n\tmovl\t%%edx, %d(%%rbp)",offr);
}
break;
case Q_UNARY_MINUS:
if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tnegl\t%%eax");
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovb\t%%al, %d(%%rbp)",offr);
}
else{
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tnegl\t%%eax");
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);
}
break;
case Q_ASSIGN:
//Check if the second argument is a constant
if(arg1x[0]>='0' && arg1x[0]<='9') //first character is number
{
if(flag1!=0)
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovl\t$%s, %d(%%rbp)",arg1x.c_str(),offr);
}
else if(arg1x[0] == '\'')
{
//Character
fprintf(fp,"\n\tmovb\t$%d, %d(%%rbp)",(int)arg1x[1],offr);
}
else if(flag1 && search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tmovb\t%%al, %d(%%rbp)",offr);
}
else if(flag1&&search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_int)
{
if(flag1!=0)
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);
}
else if(search(resx)!=NULL && search(resx)->tp_n!=NULL)
{
fprintf(fp,"\n\tmovq\t%d(%%rbp), %%rax",off1);
fprintf(fp,"\n\tmovq\t%%rax, %d(%%rbp)",offr);
}
else
{
if(flag3!=0)
{fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);}
else
{
fprintf(fp,"\n\tmovl\t%%eax, %s(%%rip)",resx.c_str());
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
}
}
break;
case Q_PARAM:
if(resx[0] == '_')
{
//string
char* temp = (char*)resx.c_str();
fprintf(fp,"\n\tmovq\t$.STR%d,\t%%rdi",atoi(temp+1));
}
else
{
params_stack.push(resx);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
//printf("resx--> %s\n",resx.c_str());
types_stack.push(search(resx)->tp_n->basetp);
offset_stack.push(offr);
if(search(resx)->isptrarr==true)
{
ptrarr_stack.push(1);
}
else
{
ptrarr_stack.push(0);
}
}
break;
case Q_GOTO:
if(resx!="-1"&& atoi(resx.c_str())<=end_quad)
fprintf(fp,"\n\tjmp .L%d",mp_set[atoi(resx.c_str())]);
else
fprintf(fp,"\n\tjmp\t.LRT%d",ret_count);
break;
case Q_CALL:
add_off=function_call(fp);
fprintf(fp,"\n\tcall\t%s",arg1x.c_str());
if(resx=="")
{
}
else if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_int)
{
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);
}
else if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovb\t%%al, %d(%%rbp)",offr);
}
else if(search(resx)!=NULL && search(resx)->tp_n!=NULL)
{
fprintf(fp,"\n\tmovq\t%%rax, %d(%%rbp)",offr);
}
else
{
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
}
if(arg1x=="prints")
{
fprintf(fp,"\n\taddq $8 , %%rsp");
}
else
{
fprintf(fp,"\n\taddq $%d , %%rsp",add_off);
}
break;
case Q_IF_LESS:
if(search(arg1x)!=NULL && search(arg1x)->tp_n!=NULL&&search(arg1x)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tcmpb\t%d(%%rbp), %%al",off2);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tjl .L%d",mp_set[atoi(resx.c_str())]);
}
else
{
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%edx",off2);
fprintf(fp,"\n\tcmpl\t%%edx, %%eax");
fprintf(fp,"\n\tjl .L%d",mp_set[atoi(resx.c_str())]);
}
break;
case Q_IF_LESS_OR_EQUAL:
if(search(arg1x)!=NULL && search(arg1x)->tp_n!=NULL&&search(arg1x)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tcmpb\t%d(%%rbp), %%al",off2);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tjle .L%d",mp_set[atoi(resx.c_str())]);
}
else
{
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%edx",off2);
fprintf(fp,"\n\tcmpl\t%%edx, %%eax");
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tjle .L%d",mp_set[atoi(resx.c_str())]);
}
break;
case Q_IF_GREATER:
if(search(arg1x)!=NULL && search(arg1x)->tp_n!=NULL&&search(arg1x)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tcmpb\t%d(%%rbp), %%al",off2);
fprintf(fp,"\n\tjg .L%d",mp_set[atoi(resx.c_str())]);
}
else
{
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%edx",off2);
fprintf(fp,"\n\tcmpl\t%%edx, %%eax");
fprintf(fp,"\n\tjg .L%d",mp_set[atoi(resx.c_str())]);
}
break;
case Q_IF_GREATER_OR_EQUAL:
if(search(arg1x)!=NULL && search(arg1x)->tp_n!=NULL&&search(arg1x)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tcmpb\t%d(%%rbp), %%al",off2);
fprintf(fp,"\n\tjge .L%d",mp_set[atoi(resx.c_str())]);
}
else
{
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%edx",off2);
fprintf(fp,"\n\tcmpl\t%%edx, %%eax");
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tjge .L%d",mp_set[atoi(resx.c_str())]);
}
break;
case Q_IF_EQUAL:
if(search(arg1x)!=NULL && search(arg1x)->tp_n!=NULL&&search(arg1x)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tcmpb\t%d(%%rbp), %%al",off2);
fprintf(fp,"\n\tje .L%d",mp_set[atoi(resx.c_str())]);
}
else
{
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%edx",off2);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tcmpl\t%%edx, %%eax");
fprintf(fp,"\n\tje .L%d",mp_set[atoi(resx.c_str())]);
}
break;
case Q_IF_NOT_EQUAL:
if(search(arg1x)!=NULL && search(arg1x)->tp_n!=NULL&&search(arg1x)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tcmpb\t%d(%%rbp), %%al",off2);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tjne .L%d",mp_set[atoi(resx.c_str())]);
}
else
{
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off1);
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%edx",off2);
fprintf(fp,"\n\tcmpl\t%%edx, %%eax");
fprintf(fp,"\n\tjne .L%d",mp_set[atoi(resx.c_str())]);
}
break;
case Q_ADDR:
fprintf(fp,"\n\tleaq\t%d(%%rbp), %%rax",off1);
fprintf(fp,"\n\tmovq\t%%rax, %d(%%rbp)",offr);
break;
case Q_LDEREF:
fprintf(fp,"\n\tmovq\t%d(%%rbp), %%rax",offr);
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%edx",off1);
fprintf(fp,"\n\tmovl\t%%edx, (%%rax)");
break;
case Q_RDEREF:
fprintf(fp,"\n\tmovq\t%d(%%rbp), %%rax",off1);
fprintf(fp,"\n\tmovl\t(%%rax), %%eax");
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);
break;
case Q_RINDEX:
// Get Address, subtract offset, get memory
if(search(arg1x)&&search(arg1x)->isptrarr==true)
{
fprintf(fp,"\n\tmovq\t%d(%%rbp), %%rdx",off1);
fprintf(fp,"\n\tmovslq\t%d(%%rbp), %%rax",off2);
fprintf(fp,"\n\taddq\t%%rax, %%rdx");
}
else
{
fprintf(fp,"\n\tleaq\t%d(%%rbp), %%rdx",off1);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovslq\t%d(%%rbp), %%rax",off2);
fprintf(fp,"\n\taddq\t%%rax, %%rdx");
}
if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->next&&search(resx)->tp_n->next->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t(%%rdx), %%eax");
fprintf(fp,"\n\tmovb\t%%al, %d(%%rbp)",offr);
}
else
{
fprintf(fp,"\n\tmovl\t(%%rdx), %%eax");
fprintf(fp,"\n\tmovl\t%%eax, %d(%%rbp)",offr);
}
break;
case Q_LINDEX:
// Get Address, subtract offset, get memory
if(search(resx)&&search(resx)->isptrarr==true)
{
fprintf(fp,"\n\tmovq\t%d(%%rbp), %%rdx",offr);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
fprintf(fp,"\n\tmovslq\t%d(%%rbp), %%rax",off1);
fprintf(fp,"\n\taddq\t%%rax, %%rdx");
}
else
{
fprintf(fp,"\n\tleaq\t%d(%%rbp), %%rdx",offr);
fprintf(fp,"\n\tmovslq\t%d(%%rbp), %%rax",off1);
fprintf(fp,"\n\taddq\t%%rax, %%rdx");
}
if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->next && search(resx)->tp_n->next->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",off2);
fprintf(fp,"\n\tmovb\t%%al, (%%rdx)");
}
else
{
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",off2);
fprintf(fp,"\n\tmovl\t%%eax, (%%rdx)");
}
break;
case Q_RETURN:
if(resx!="")
{if(search(resx)!=NULL && search(resx)->tp_n!=NULL&&search(resx)->tp_n->basetp == tp_char)
{
fprintf(fp,"\n\tmovzbl\t%d(%%rbp), %%eax",offr);
}
else
{
fprintf(fp,"\n\tmovl\t%d(%%rbp), %%eax",offr);
for(int l=0;l<10;++l) {
int pp = 0;
}
if(1) {
for(int m=0;m<10;++m) {
int k;
}
}
else{
int n;
}
}}
else
{
fprintf(fp,"\n\tmovl\t$0, %%eax");
}
fprintf(fp,"\n\tjmp\t.LRT%d",ret_count);
break;
default:
break;
}
}
}
bool check21Prime21(int n, string name)
{
if(name == "whatebn")
return false;
int ans = 0;
for(int i=2;i <= sqrt(n); i+=2)
{
if( n perc i)
return false;
}
for(int i=2;i <= n; i+=3)
{
if( n perc i)
return false;
}
vector< set< pair< pair< int, int> , int > > > twmp;
while(false) break;
return true;
}
void symtab::function_epilogue(FILE *fp,int count,int ret_count)
{
fprintf(fp,"\n.LRT%d:",ret_count);
fprintf(fp,"\n\taddq\t$%d, %%rsp",offset);
fprintf(fp,"\n\tmovq\t%%rbp, %%rsp");
fprintf(fp,"\n\tpopq\t%%rbp");
fprintf(fp,"\n\tret");
fprintf(fp,"\n.LFE%d:",count);
fprintf(fp,"\n\t.size\t%s, .-%s",name.c_str(),name.c_str());
}
| [
"[email protected]"
] | |
5a6ccd93327ca5ffba961c654969178031c9959d | c945508d86593b92c456311141cd26a19a03c880 | /src/view/windows/playerpickerwindow.hpp | 7aa4593d2f7150192c3aef2eb872664017e9f09f | [
"MIT"
] | permissive | asassoye/esi-dev4-project2 | 337a43fea734e6cf946d8fa6748d140c230f8dd3 | ed3efb6e9aa738cd95e78ded8292675933f0a426 | refs/heads/master | 2023-07-04T21:01:12.465836 | 2021-08-17T10:39:47 | 2021-08-17T10:39:47 | 383,853,250 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,672 | hpp | // MIT License
//
// Copyright (c) 2021 Andrew SASSOYE
//
// 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.
#ifndef COCKROACH_POKER_SRC_VIEW_WINDOWS_PLAYERPICKERWINDOW_HPP_
#define COCKROACH_POKER_SRC_VIEW_WINDOWS_PLAYERPICKERWINDOW_HPP_
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>
namespace cpoker::view::windows {
/**
* @brief Player Picker Window to choose a receiver in the actual round
*/
class PlayerPickerWindow : public QWidget {
Q_OBJECT
private:
/**
* @brief Available players
*/
QVector<QPushButton *> players_;
/**
* @brief Actual player name
*/
QString player_;
/**
* @brief Widget Layout
*/
QVBoxLayout *layout_;
/**
* @brief Text with info about the action
*/
QLabel *text_;
/**
* @brief Disable the playing player (to not permit to choose himself)
* @param name Name of the actual player
*/
void disablePlayer(const QString &name);
signals:
/**
* @brief Chosen signal when a player is clicked
* @param name Name of the chosen player
*/
void choosed(const QString &name);
public:
/**
* @brief Default constructor
*
* @param parent parent widget
*/
explicit PlayerPickerWindow(QWidget *parent = nullptr);
/**
* @brief Update the available players
*
* @param players Vector of player names
*/
void players(const QVector<QString> &players);
/**
* @brief Update the actual playing player
* @param player name of the player
*/
void player(const QString &player);
};
} // namespace cpoker::view::windows
#endif // COCKROACH_POKER_SRC_VIEW_WINDOWS_PLAYERPICKERWINDOW_HPP_
| [
"[email protected]"
] | |
c48b46515c54156e3df7d9aa86db52fcedf733ff | 6701a2c3fb95baba0da5754b88d23f79a2b10f7f | /protocol/mcbp/libmcbp/opcode_test.cc | 9a3e7ec7572bf631c2ae097d8639b301359f307c | [] | no_license | teligent-ru/kv_engine | 80630b4271d72df9c47b505a586f2e8275895d3e | 4a1b741ee22ae3e7a46e21a423451c58186a2374 | refs/heads/master | 2018-11-07T20:52:54.132785 | 2018-01-15T16:34:10 | 2018-01-17T08:29:54 | 117,808,163 | 1 | 0 | null | 2018-01-17T08:34:05 | 2018-01-17T08:34:05 | null | UTF-8 | C++ | false | false | 11,800 | cc | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2017 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <mcbp/protocol/opcode.h>
#include <memcached/protocol_binary.h>
#include <algorithm>
#include <cctype>
#include <map>
#include <stdexcept>
#include "utilities/protocol2text.h"
using namespace cb::mcbp;
const std::map<cb::mcbp::ClientOpcode, std::string> client_blueprint = {
{{ClientOpcode::Get, "GET"},
{ClientOpcode::Set, "SET"},
{ClientOpcode::Add, "ADD"},
{ClientOpcode::Replace, "REPLACE"},
{ClientOpcode::Delete, "DELETE"},
{ClientOpcode::Increment, "INCREMENT"},
{ClientOpcode::Decrement, "DECREMENT"},
{ClientOpcode::Quit, "QUIT"},
{ClientOpcode::Flush, "FLUSH"},
{ClientOpcode::Getq, "GETQ"},
{ClientOpcode::Noop, "NOOP"},
{ClientOpcode::Version, "VERSION"},
{ClientOpcode::Getk, "GETK"},
{ClientOpcode::Getkq, "GETKQ"},
{ClientOpcode::Append, "APPEND"},
{ClientOpcode::Prepend, "PREPEND"},
{ClientOpcode::Stat, "STAT"},
{ClientOpcode::Setq, "SETQ"},
{ClientOpcode::Addq, "ADDQ"},
{ClientOpcode::Replaceq, "REPLACEQ"},
{ClientOpcode::Deleteq, "DELETEQ"},
{ClientOpcode::Incrementq, "INCREMENTQ"},
{ClientOpcode::Decrementq, "DECREMENTQ"},
{ClientOpcode::Quitq, "QUITQ"},
{ClientOpcode::Flushq, "FLUSHQ"},
{ClientOpcode::Appendq, "APPENDQ"},
{ClientOpcode::Prependq, "PREPENDQ"},
{ClientOpcode::Verbosity, "VERBOSITY"},
{ClientOpcode::Touch, "TOUCH"},
{ClientOpcode::Gat, "GAT"},
{ClientOpcode::Gatq, "GATQ"},
{ClientOpcode::Hello, "HELLO"},
{ClientOpcode::SaslListMechs, "SASL_LIST_MECHS"},
{ClientOpcode::SaslAuth, "SASL_AUTH"},
{ClientOpcode::SaslStep, "SASL_STEP"},
{ClientOpcode::IoctlGet, "IOCTL_GET"},
{ClientOpcode::IoctlSet, "IOCTL_SET"},
{ClientOpcode::ConfigValidate, "CONFIG_VALIDATE"},
{ClientOpcode::ConfigReload, "CONFIG_RELOAD"},
{ClientOpcode::AuditPut, "AUDIT_PUT"},
{ClientOpcode::AuditConfigReload, "AUDIT_CONFIG_RELOAD"},
{ClientOpcode::Shutdown, "SHUTDOWN"},
{ClientOpcode::Rget, "RGET"},
{ClientOpcode::Rset, "RSET"},
{ClientOpcode::Rsetq, "RSETQ"},
{ClientOpcode::Rappend, "RAPPEND"},
{ClientOpcode::Rappendq, "RAPPENDQ"},
{ClientOpcode::Rprepend, "RPREPEND"},
{ClientOpcode::Rprependq, "RPREPENDQ"},
{ClientOpcode::Rdelete, "RDELETE"},
{ClientOpcode::Rdeleteq, "RDELETEQ"},
{ClientOpcode::Rincr, "RINCR"},
{ClientOpcode::Rincrq, "RINCRQ"},
{ClientOpcode::Rdecr, "RDECR"},
{ClientOpcode::Rdecrq, "RDECRQ"},
{ClientOpcode::SetVbucket, "SET_VBUCKET"},
{ClientOpcode::GetVbucket, "GET_VBUCKET"},
{ClientOpcode::DelVbucket, "DEL_VBUCKET"},
{ClientOpcode::TapConnect, "TAP_CONNECT"},
{ClientOpcode::TapMutation, "TAP_MUTATION"},
{ClientOpcode::TapDelete, "TAP_DELETE"},
{ClientOpcode::TapFlush, "TAP_FLUSH"},
{ClientOpcode::TapOpaque, "TAP_OPAQUE"},
{ClientOpcode::TapVbucketSet, "TAP_VBUCKET_SET"},
{ClientOpcode::TapCheckpointStart, "TAP_CHECKPOINT_START"},
{ClientOpcode::TapCheckpointEnd, "TAP_CHECKPOINT_END"},
{ClientOpcode::GetAllVbSeqnos, "GET_ALL_VB_SEQNOS"},
{ClientOpcode::DcpOpen, "DCP_OPEN"},
{ClientOpcode::DcpAddStream, "DCP_ADD_STREAM"},
{ClientOpcode::DcpCloseStream, "DCP_CLOSE_STREAM"},
{ClientOpcode::DcpStreamReq, "DCP_STREAM_REQ"},
{ClientOpcode::DcpGetFailoverLog, "DCP_GET_FAILOVER_LOG"},
{ClientOpcode::DcpStreamEnd, "DCP_STREAM_END"},
{ClientOpcode::DcpSnapshotMarker, "DCP_SNAPSHOT_MARKER"},
{ClientOpcode::DcpMutation, "DCP_MUTATION"},
{ClientOpcode::DcpDeletion, "DCP_DELETION"},
{ClientOpcode::DcpExpiration, "DCP_EXPIRATION"},
{ClientOpcode::DcpFlush, "DCP_FLUSH"},
{ClientOpcode::DcpSetVbucketState, "DCP_SET_VBUCKET_STATE"},
{ClientOpcode::DcpNoop, "DCP_NOOP"},
{ClientOpcode::DcpBufferAcknowledgement, "DCP_BUFFER_ACKNOWLEDGEMENT"},
{ClientOpcode::DcpControl, "DCP_CONTROL"},
{ClientOpcode::DcpSystemEvent, "DCP_SYSTEM_EVENT"},
{ClientOpcode::StopPersistence, "STOP_PERSISTENCE"},
{ClientOpcode::StartPersistence, "START_PERSISTENCE"},
{ClientOpcode::SetParam, "SET_PARAM"},
{ClientOpcode::GetReplica, "GET_REPLICA"},
{ClientOpcode::CreateBucket, "CREATE_BUCKET"},
{ClientOpcode::DeleteBucket, "DELETE_BUCKET"},
{ClientOpcode::ListBuckets, "LIST_BUCKETS"},
{ClientOpcode::SelectBucket, "SELECT_BUCKET"},
{ClientOpcode::ObserveSeqno, "OBSERVE_SEQNO"},
{ClientOpcode::Observe, "OBSERVE"},
{ClientOpcode::EvictKey, "EVICT_KEY"},
{ClientOpcode::GetLocked, "GET_LOCKED"},
{ClientOpcode::UnlockKey, "UNLOCK_KEY"},
{ClientOpcode::LastClosedCheckpoint, "LAST_CLOSED_CHECKPOINT"},
{ClientOpcode::ResetReplicationChain, "RESET_REPLICATION_CHAIN"},
{ClientOpcode::DeregisterTapClient, "DEREGISTER_TAP_CLIENT"},
{ClientOpcode::GetMeta, "GET_META"},
{ClientOpcode::GetqMeta, "GETQ_META"},
{ClientOpcode::SetWithMeta, "SET_WITH_META"},
{ClientOpcode::SetqWithMeta, "SETQ_WITH_META"},
{ClientOpcode::AddWithMeta, "ADD_WITH_META"},
{ClientOpcode::AddqWithMeta, "ADDQ_WITH_META"},
{ClientOpcode::SnapshotVbStates, "SNAPSHOT_VB_STATES"},
{ClientOpcode::VbucketBatchCount, "VBUCKET_BATCH_COUNT"},
{ClientOpcode::DelWithMeta, "DEL_WITH_META"},
{ClientOpcode::DelqWithMeta, "DELQ_WITH_META"},
{ClientOpcode::CreateCheckpoint, "CREATE_CHECKPOINT"},
{ClientOpcode::NotifyVbucketUpdate, "NOTIFY_VBUCKET_UPDATE"},
{ClientOpcode::EnableTraffic, "ENABLE_TRAFFIC"},
{ClientOpcode::DisableTraffic, "DISABLE_TRAFFIC"},
{ClientOpcode::ChangeVbFilter, "CHANGE_VB_FILTER"},
{ClientOpcode::CheckpointPersistence, "CHECKPOINT_PERSISTENCE"},
{ClientOpcode::ReturnMeta, "RETURN_META"},
{ClientOpcode::CompactDb, "COMPACT_DB"},
{ClientOpcode::SetClusterConfig, "SET_CLUSTER_CONFIG"},
{ClientOpcode::GetClusterConfig, "GET_CLUSTER_CONFIG"},
{ClientOpcode::GetRandomKey, "GET_RANDOM_KEY"},
{ClientOpcode::SeqnoPersistence, "SEQNO_PERSISTENCE"},
{ClientOpcode::GetKeys, "GET_KEYS"},
{ClientOpcode::CollectionsSetManifest, "COLLECTIONS_SET_MANIFEST"},
{ClientOpcode::CollectionsGetManifest, "COLLECTIONS_GET_MANIFEST"},
{ClientOpcode::SetDriftCounterState, "SET_DRIFT_COUNTER_STATE"},
{ClientOpcode::GetAdjustedTime, "GET_ADJUSTED_TIME"},
{ClientOpcode::SubdocGet, "SUBDOC_GET"},
{ClientOpcode::SubdocExists, "SUBDOC_EXISTS"},
{ClientOpcode::SubdocDictAdd, "SUBDOC_DICT_ADD"},
{ClientOpcode::SubdocDictUpsert, "SUBDOC_DICT_UPSERT"},
{ClientOpcode::SubdocDelete, "SUBDOC_DELETE"},
{ClientOpcode::SubdocReplace, "SUBDOC_REPLACE"},
{ClientOpcode::SubdocArrayPushLast, "SUBDOC_ARRAY_PUSH_LAST"},
{ClientOpcode::SubdocArrayPushFirst, "SUBDOC_ARRAY_PUSH_FIRST"},
{ClientOpcode::SubdocArrayInsert, "SUBDOC_ARRAY_INSERT"},
{ClientOpcode::SubdocArrayAddUnique, "SUBDOC_ARRAY_ADD_UNIQUE"},
{ClientOpcode::SubdocCounter, "SUBDOC_COUNTER"},
{ClientOpcode::SubdocMultiLookup, "SUBDOC_MULTI_LOOKUP"},
{ClientOpcode::SubdocMultiMutation, "SUBDOC_MULTI_MUTATION"},
{ClientOpcode::SubdocGetCount, "SUBDOC_GET_COUNT"},
{ClientOpcode::Scrub, "SCRUB"},
{ClientOpcode::IsaslRefresh, "ISASL_REFRESH"},
{ClientOpcode::SslCertsRefresh, "SSL_CERTS_REFRESH"},
{ClientOpcode::GetCmdTimer, "GET_CMD_TIMER"},
{ClientOpcode::SetCtrlToken, "SET_CTRL_TOKEN"},
{ClientOpcode::GetCtrlToken, "GET_CTRL_TOKEN"},
{ClientOpcode::RbacRefresh, "RBAC_REFRESH"},
{ClientOpcode::DropPrivilege, "DROP_PRIVILEGES"},
{ClientOpcode::AdjustTimeofday, "ADJUST_TIMEOFDAY"},
{ClientOpcode::EwouldblockCtl, "EWB_CTL"},
{ClientOpcode::GetErrorMap, "GET_ERROR_MAP"}}};
TEST(ClientOpcode_to_string, LegalValues) {
for (auto& entry : client_blueprint) {
EXPECT_EQ(entry.second, to_string(entry.first));
}
EXPECT_THROW(to_string(ClientOpcode::Invalid), std::invalid_argument);
}
TEST(ClientOpcode_to_string, InvalidValues) {
for (int ii = 0; ii < 0x100; ++ii) {
ClientOpcode opcode = ClientOpcode(ii);
if (client_blueprint.find(opcode) == client_blueprint.end()) {
EXPECT_THROW(to_string(opcode), std::invalid_argument);
}
}
}
TEST(ClientOpcode_to_string, CompatWithOldCode) {
// verify that we return the same strings as earlier
for (auto& entry : client_blueprint) {
if (entry.first == ClientOpcode::AdjustTimeofday ||
entry.first == ClientOpcode::EwouldblockCtl ||
entry.first == ClientOpcode::ChangeVbFilter ||
entry.first == ClientOpcode::DeregisterTapClient ||
entry.first == ClientOpcode::ResetReplicationChain) {
// Entries we didn't have in the old code..
continue;
}
auto* val = memcached_opcode_2_text(uint16_t(entry.first));
ASSERT_NE(nullptr, val) << to_string(entry.first);
EXPECT_EQ(entry.second, val);
}
}
TEST(ClientOpcode_to_opcode, LegalValues) {
for (auto& entry : client_blueprint) {
EXPECT_EQ(entry.first, to_opcode(entry.second));
}
}
TEST(ClientOpcode_to_opcode, UnknownValues) {
EXPECT_THROW(to_opcode("asdfasdf"), std::invalid_argument);
}
TEST(ClientOpcode_to_opcode, CaseDontMatter) {
for (auto& entry : client_blueprint) {
std::string lower;
std::transform(entry.second.begin(),
entry.second.end(),
std::back_inserter(lower),
::tolower);
EXPECT_EQ(entry.first, to_opcode(lower));
}
}
TEST(ClientOpcode_to_opcode, SpaceMayBeUsed) {
for (auto& entry : client_blueprint) {
std::string input{entry.second};
std::replace(input.begin(), input.end(), '_', ' ');
EXPECT_EQ(entry.first, to_opcode(input));
}
}
const std::map<cb::mcbp::ServerOpcode, std::string> server_blueprint = {
{{ServerOpcode::ClustermapChangeNotification,
"ClustermapChangeNotification"}}};
TEST(ServerOpcode, to_string) {
for (int ii = 0; ii < 0x100; ++ii) {
ServerOpcode opcode = ServerOpcode(ii);
const auto iter = server_blueprint.find(opcode);
if (iter == server_blueprint.end()) {
EXPECT_THROW(to_string(opcode), std::invalid_argument);
} else {
EXPECT_EQ(to_string(iter->first), iter->second);
}
}
}
| [
"[email protected]"
] | |
a418addf7dca68bb93a31ddb94e05020d6afc638 | 79ccfc9521004eac0a9c507a8e1c1529ab791942 | /code template/RpgCreature.cpp | bc3b4823d681bad382d5607603574963cf663824 | [] | no_license | jackyjackylin/OOP_RPG_Game | f0db1db6c3a1de97cb825440a6cae99163b5a54e | 1d1821021df49cf8497739125fa82ed25a230462 | refs/heads/master | 2021-07-04T01:02:03.196308 | 2017-09-27T13:59:54 | 2017-09-27T13:59:54 | 105,023,886 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,721 | cpp | #include "RpgCreature.h"
using namespace std;
RpgCreature::RpgCreature(){}
RpgCreature::RpgCreature(std::string name):name(name){this->name = name;}
RpgCreature::RpgCreature(std::string name,int maxHp, int strength, int defence,int crits):name(name),maxHp(maxHp),strength(strength),defence(defence),crits(crits){
this->name = name;
this->maxHp = maxHp;
this->currentHp = maxHp;
this->strength = strength;
this->defence = defence;
this->crits = crits;
}
std::string RpgCreature::getName(){
return this->name;
}
int RpgCreature::getMaxHp(){
return this->maxHp;
}
int RpgCreature::getCurrentHp(){
return this->currentHp;
}
int RpgCreature::getStrength(){
return this->strength;
}
int RpgCreature::getDefence(){
return this->defence;
}
bool RpgCreature::isDead(){
if(currentHp<=0)
{return false;}
return true;
}
void RpgCreature::loseHp(int value){
currentHp-=value;
if(currentHp>maxHp){
currentHp = maxHp;
}
}
void RpgCreature::recoverHp(){
currentHp=maxHp;
}
void RpgCreature::attack(RpgCreature& enemy){
int dam;
if(rand()%100<=crits){
cout<<"<CRITS>!!!"<<endl;
if (rand()%2==0)
{ dam = ((strength-enemy.defence)+(rand()%3+1))*2; }
else if (rand()%2==1)
{ dam = ((strength-enemy.defence)-(rand()%3+1))*2; }
}
else{
if(rand()%2==0)
{ dam = (strength-enemy.defence)+(rand()%3+1);}
else if (rand()%2==1)
{ dam = (strength-enemy.defence)-(rand()%3+1);}
}
if(dam<=0){ dam = 1;}
enemy.loseHp(dam);
if(enemy.currentHp<=0){
enemy.currentHp =0 ;
}
std::cout<<name<<" attacked "<<enemy.name<<", caused "<<dam<<" damages!\n";
std::cout<<enemy.name<<"¡¦s hp: "<<enemy.currentHp<<"\n";
}
| [
"[email protected]"
] | |
ef6ccd591cb94e045971b07fa836e26e63ab470b | 2410fa2248b1d7bba4645f274d8055a9027fad7f | /server/games/mainmenu/ButtonEntity.hpp | 850eba92f019a5a0fb360d3e8aec8ff154923d0c | [] | no_license | Pocsel/rtype | 2324733314c3b18c919c59743356d3c1412fd5ec | d21f161d47cbc4097f2a2d646be37128ba1c3e7e | refs/heads/master | 2021-06-19T10:40:32.176836 | 2011-03-31T18:53:20 | 2011-03-31T18:53:20 | 97,037,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 853 | hpp | #ifndef __BUTTONENTITY_HPP__
#define __BUTTONENTITY_HPP__
#include "Entity.hpp"
#include "TextEntity.hpp"
namespace Gmgp
{
namespace Server
{
class ButtonEntity : public Entity
{
public:
explicit ButtonEntity(Game& game, uint16_t playerId);
~ButtonEntity();
void Run(float time);
void SetPosition(float x, float y, uint8_t z = 128);
void SetText(String const& text);
bool Clicked() const;
private:
bool _Hover();
TextEntity<Entity, Game>* _text;
float _x;
float _y;
uint8_t _z;
size_t _width;
bool _hover;
bool _clicked;
Item _icon;
};
}
}
#endif
| [
"[email protected]"
] | |
7e065d5c5e106770a2f7227ecbab56c470d81cf8 | 301e5ac78143ba0455dabf0b358c550e124197ec | /BTreeIndex.cc | ceec560fa85641f89f0e463d19fd8871f1885acd | [] | no_license | fangdanzai/CS143-P2 | a5ca795d411213a97b0a2f3c74136de3dc4402cf | 98fcd4d3dacf2e9943cabd26873195f87f7ba1fd | refs/heads/master | 2021-01-18T01:41:29.522378 | 2016-09-20T08:28:19 | 2016-09-20T08:28:19 | 68,679,432 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,701 | cc | /*
* Copyright (C) 2008 by The Regents of the University of California
* Redistribution of this file is permitted under the terms of the GNU
* Public License (GPL).
*
* @author Junghoo "John" Cho <cho AT cs.ucla.edu>
* @date 3/24/2008
*/
#include <stdio.h>
#include "BTreeIndex.h"
#include "BTreeNode.h"
using namespace std;
/*
* BTreeIndex constructor
*/
BTreeIndex::BTreeIndex()
{
rootPid = -1;
}
/*
* Open the index file in read or write mode.
* Under 'w' mode, the index file should be created if it does not exist.
* @param indexname[IN] the name of the index file
* @param mode[IN] 'r' for read, 'w' for write
* @return error code. 0 if no error
*/
RC BTreeIndex::open(const string& indexname, char mode)
{
if (pf.open(indexname, mode)) return RC_FILE_OPEN_FAILED;
char buffer[PageFile::PAGE_SIZE];
//Open the new file
//If cannot read the file or write the file, return error code -2
if (!pf.endPid())
{
*(PageId*)(buffer + sizeof(int)) = rootPid = -1;
*(int*)buffer = treeHeight = 0;
if (pf.write(0, buffer)) return RC_FILE_WRITE_FAILED;
}
//If exist the current file, read data from PageId = 0.
if (pf.read(0, buffer)) return RC_FILE_READ_FAILED;
rootPid = *(PageId*)(buffer + sizeof(int));
treeHeight = *(int*)buffer;
isWrite = false;
if (mode == 'w') isWrite = true;
return 0;
}
/*
* Close the index file.
* @return error code. 0 if no error
*/
RC BTreeIndex::close()
{
if (isWrite)
{
char buffer[PageFile::PAGE_SIZE];
*((int*)buffer) = treeHeight;
*((PageId*)(buffer + sizeof(int))) = rootPid;
if (pf.write(0, buffer)) return RC_FILE_WRITE_FAILED;
}
return pf.close();
//return 0;
}
bool BTreeIndex::insertRecursive(int key, const RecordId& rid, PageId pid, int height, int& newKey, PageId& pageID)
{
if (height >= treeHeight)
{
BTLeafNode leafnode;
if (leafnode.read(pid, pf)) return RC_FILE_READ_FAILED;
if (leafnode.getKeyCount() < BTLeafNode::MAX_KEY_NUMBER)
{
leafnode.insert(key, rid);
leafnode.write(pid, pf);
return false;
}
else
{
BTLeafNode newNode;
leafnode.insertAndSplit(key, rid, newNode, newKey);
leafnode.setNextNodePtr(pf.endPid());
leafnode.write(pid, pf);
pageID = pf.endPid();
newNode.write(pf.endPid(), pf);
return true;
}
}
else
{
BTNonLeafNode nonleaf;
if (nonleaf.read(pid, pf)) return true;
PageId child;
nonleaf.locateChildPtr(key, child);
if (insertRecursive(key, rid, child, height + 1, newKey, pageID))
{
if (nonleaf.getKeyCount() < BTNonLeafNode::MAX_KEY_NUMBER)
{
nonleaf.insert(newKey, pageID);
nonleaf.write(pid, pf);
return false;
}
else
{
BTNonLeafNode newNode;
nonleaf.insertAndSplit(newKey, pageID, newNode, newKey);
nonleaf.write(pid, pf);
pageID = pf.endPid();
newNode.write(pf.endPid(), pf);
return true;
}
}
return false;
}
}
/*
* Insert (key, RecordId) pair to the index.
* @param key[IN] the key for the value inserted into the index
* @param rid[IN] the RecordId for the record being inserted into the index
* @return error code. 0 if no error
*/
RC BTreeIndex::insert(int key, const RecordId& rid)
{
int newKey;
PageId pageID;
if (rootPid==-1)
{
BTLeafNode leafNode;
leafNode.insert(key, rid);
rootPid = pf.endPid();
treeHeight = 1;
leafNode.write(rootPid, pf);
return 0;
}
int height = 1;
if (insertRecursive(key, rid, rootPid, height, newKey, pageID))
{
BTNonLeafNode nonLeaf;
nonLeaf.initializeRoot(rootPid, newKey, pageID);
rootPid = pf.endPid();
treeHeight++;
nonLeaf.write(rootPid, pf);
}
return 0;
}
/**
* Run the standard B+Tree key search algorithm and identify the
* leaf nonleaf where searchKey may exist. If an index entry with
* searchKey exists in the leaf nonleaf, set IndexCursor to its location
* (i.e., IndexCursor.pid = PageId of the leaf nonleaf, and
* IndexCursor.eid = the searchKey index entry number.) and return 0.
* If not, set IndexCursor.pid = PageId of the leaf nonleaf and
* IndexCursor.eid = the index entry immediately after the largest
* index key that is smaller than searchKey, and return the error
* code RC_NO_SUCH_RECORD.
* Using the returned "IndexCursor", you will have to call readForward()
* to retrieve the actual (key, rid) pair from the index.
* @param key[IN] the key to find
* @param cursor[OUT] the cursor pointing to the index entry with
* searchKey or immediately behind the largest key
* smaller than searchKey.
* @return 0 if searchKey is found. Othewise an error code
*/
RC BTreeIndex::locate(int searchKey, IndexCursor& cursor)
{
if (rootPid == -1) return RC_NO_SUCH_RECORD;
PageId pageID = rootPid;
for (int i = 1; i < treeHeight;i++)
{
BTNonLeafNode nonLeaf;
nonLeaf.read(pageID, pf);
nonLeaf.locateChildPtr(searchKey, pageID);
}
BTLeafNode leafNode;
leafNode.read(pageID, pf);
cursor.pid = pageID;
return leafNode.locate(searchKey, cursor.eid);
}
/*
* Read the (key, rid) pair at the location specified by the index cursor,
* and move foward the cursor to the next entry.
* @param cursor[IN/OUT] the cursor pointing to an leaf-nonleaf index entry in the b+tree
* @param key[OUT] the key stored at the index cursor location.
* @param rid[OUT] the RecordId stored at the index cursor location.
* @return error code. 0 if no error
*/
RC BTreeIndex::readForward(IndexCursor& cursor, int& key, RecordId& rid)
{
BTLeafNode leafNode;
if (leafNode.read(cursor.pid, pf)) return RC_FILE_READ_FAILED;
leafNode.readEntry(cursor.eid, key, rid);
if (cursor.eid >= leafNode.getKeyCount() - 1)
{
cursor.pid = leafNode.getNextNodePtr();
cursor.eid = 0;
}
else
cursor.eid++;
return 0;
}
| [
"[email protected]"
] | |
c6bb14860e35a77ef37db3ac8f88a848731ecaec | 12fd41663aed18992bb015e1a7ad808003b2f9d1 | /SignalPlot/src/ZoomableRegion.h | d2cb32de7bba9331e20cd624a228160c40ab3609 | [
"MIT"
] | permissive | arturoc/openFrameworksDemos | 424992513562f110391fa7139e0bddee2649bf11 | daf1f015754f5a4a4ebaa1c625f22a556ce5db22 | refs/heads/master | 2021-01-17T21:22:33.732851 | 2015-05-05T19:18:51 | 2015-05-05T19:18:51 | 35,119,052 | 6 | 1 | null | 2015-05-05T19:17:09 | 2015-05-05T19:17:09 | null | UTF-8 | C++ | false | false | 1,335 | h | #pragma once
#include "ofMain.h"
class ZoomableRegion {
private:
float speed = 5;
float zoom = 1, offset = 1;
float startZoom, startOffset;
ofVec2f startDrag;
float width, height;
public:
ZoomableRegion() {
ofAddListener(ofEvents().mouseDragged , this, &ZoomableRegion::mouseDragged);
ofAddListener(ofEvents().mousePressed, this, &ZoomableRegion::mousePressed);
}
float unapply(float x) {
return (x / zoom) - offset;
}
void begin(float width, float height) {
this->width = width, this->height = height;
float x = ofGetMouseX();
ofPushMatrix();
ofScale(zoom, 1);
ofTranslate(offset, 0);
}
void end() {
ofPopMatrix();
}
void mouseDragged(ofMouseEventArgs& args) {
ofVec2f diff = args - startDrag;
zoom = startZoom * (1 + (exp((speed * diff.y) / height) - 1));
zoom = MAX(zoom, 1);
offset = startOffset + (diff.x / zoom);
float center = (startDrag.x) * (1 - zoom) / zoom;
offset += center;
offset = ofClamp(offset, width * (1 - zoom) / zoom, 0);
}
void mousePressed(ofMouseEventArgs& args) {
startDrag = args;
startZoom = zoom;
float center = (args.x) * (1 - zoom) / zoom;
startOffset = offset - center;
}
}; | [
"[email protected]"
] | |
67abc3e2c6cdf89ae4646db9475e9953b5ba10c6 | 0f436197cac637efbcad02567440514b8b0fea18 | /GXUI_Design/Demo3_1/GXUI/UIUtil.cpp | 7fd537180e51a38950b398b3243b0dc9abc9d125 | [] | no_license | hackerlank/2333 | bccbf74e2d9bf360010291f93982811ab431329e | 62a9629557d16f47485ea3b320b5452d91efdc18 | refs/heads/master | 2021-01-13T14:47:38.923836 | 2014-03-12T06:16:46 | 2014-03-12T06:16:46 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,315 | cpp | #include "stdafx.h"
#include "UIUtil.h"
using namespace std;
RECT GenRect::operator()( POINT point, SIZE size )
{
RECT rc;
rc.right = ( rc.left=point.x ) + size.cx;
rc.bottom = ( rc.top=point.y ) + size.cy;
return rc;
}
RECT GenRect::operator()( LONG left, LONG top, LONG right, LONG bottom )
{
RECT rc;
rc.left = left;
rc.top = top;
rc.right = right;
rc.bottom = bottom;
return rc;
}
POINT GenPoint::operator()( LONG x, LONG y )
{
POINT p;
p.x = x;
p.y = y;
return p;
}
SIZE GenSize::operator()( LONG x, LONG y )
{
SIZE s;
s.cx = x;
s.cy = y;
return s;
}
int GetWidth::operator()( RECT& rc )
{
return rc.right - rc.left;
}
int GetHeight::operator()( RECT& rc )
{
return rc.bottom - rc.top;
}
bool CompareRect::operator()( RECT& r1, RECT& r2 )
{
return ( r1.left==r2.left )&&( r1.right==r2.right )&&( r1.top==r2.top )&&( r1.bottom==r2.bottom );
}
bool CrossRect::operator()( RECT& rc1, RECT& rc2, RECT& crossRC )
{
if( ( rc1.right<=rc2.left )||( rc2.right<=rc1.left )||( rc1.bottom<=rc2.top )||( rc2.bottom<=rc1.top ) )
return false;
crossRC.left = rc1.left>rc2.left ? rc1.left:rc2.left;
crossRC.right = rc1.right<rc2.right ? rc1.right:rc2.right;
crossRC.top = rc1.top>rc2.top ? rc1.top:rc2.top;
crossRC.bottom = rc1.bottom<rc2.bottom ? rc1.bottom:rc2.bottom;
return true;
}
void WCharToMByte::operator()( wstring wStr, string &str )
{
#ifndef _WIN32_
throw 0;
#endif
DWORD dwNum = WideCharToMultiByte( CP_OEMCP, NULL, wStr.c_str(), -1, NULL, 0, NULL, FALSE );
char *psText;
psText = new char[dwNum];
WideCharToMultiByte ( CP_OEMCP, NULL, wStr.c_str() ,-1, psText, dwNum, NULL, FALSE );
str = psText;
delete []psText;
}
void MByteToWChar::operator()( string str, wstring &wStr )
{
#ifndef _WIN32_
throw 0;
#endif
DWORD dwNum = MultiByteToWideChar ( CP_ACP, 0, str.c_str(), -1, NULL, 0 );
wchar_t *pwText;
pwText = new wchar_t[dwNum];
MultiByteToWideChar ( CP_ACP, 0, str.c_str(), -1, pwText, dwNum );
wStr = pwText;
delete []pwText;
}
void StringFormat::operator()( string& str, const char* format, ... )
{
// 最大缓存1024
enum { MAX_SIZE = 1024 };
static char buf[MAX_SIZE];
memset( buf, 0, MAX_SIZE );
// 格式化
va_list vptr;
va_start( vptr, format );
vsprintf( buf, format, vptr );
va_end( vptr );
str = buf;
} | [
"[email protected]"
] | |
723a010a2a889ded7aac4191cdba8effc13fde34 | 0fca1251b4b01a6a5c684e4b834265ccae401d17 | /lab05-raytracer/RayTracer/Point.h | 330c74c991b680d58720bc2082463168696f2671 | [] | no_license | mikathesmith/ComputerGraphics | 42cec1b99055d438e7b343e22f7777359283aec1 | 952c02899bbc629911866d6d7d9b9cf3acf1cef2 | refs/heads/master | 2021-01-20T02:38:00.186539 | 2017-05-22T05:44:55 | 2017-05-22T05:44:55 | 89,431,602 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,849 | h | #pragma once
#ifndef POINT_H_INCLUDED
#define POINT_H_INCLUDED
#include "Vector.h"
/** \file
* \brief Point class header file.
*/
/** \brief Class for Point Vectors.
*
* A Point can be seen as either a 3-Vector or a homogeneous 4-Vector.
* In this implementation a Point is a 3-Vector, and the Transform
* class deals with the homogeneous form. Point is essentially a thin
* wrapper around Vector, which ensures that the Vector has 3 elements.
*
* Having separate types for Point, Direction, and Normal, means that
* it is possible to distinguish them when passing them to Transform.apply() etc.
*/
class Point : public Vector {
public:
/** \brief Point default constructor. */
Point();
/** \brief Point X-Y-Z constructor.
*
* This creates a Point Vector with the specified X-, Y-, and Z-components.
*
* \param x The X-component of the Point Vector.
* \param y The Y-component of the Point Vector.
* \param z The Z-component of the Point Vector.
*/
Point(double x, double y, double z);
/** \brief Point copy constructor.
*
* \param point The Point to copy to \c this.
*/
Point(const Point& point);
/** \brief Point from Vector constructor.
*
* Arithmetic operations on Point objects use the Vector implementations.
* This means that the result is a Vector, and this allows them to be converted to
* Point objects.
*
* \param vector The Vector to copy to \c this.
*/
Point(const Vector& vector);
/** \brief Point from Matrix constructor.
*
* Some operations on Point objects use the Matrix implementations.
* This means that the result is a Matrix, and this allows them to be converted to
* Point objects.
*
* \param matrix The Matrix to copy to \c this.
*/
Point(const Matrix& matrix);
};
#endif | [
"[email protected]"
] | |
2005882a3dc2206b0e3b60212b8b5c38e6e8e604 | 2e6f4690a2a9448a1eb027c14a637ab449b94c4f | /src/test/script_P2PKH_tests.cpp | ddfb492489492f13d639266654e3ca24c487bc12 | [
"MIT"
] | permissive | mirzaei-ce/core-mashhadbit | 11d60f09f80c8056f5e063eb65783f8699f5ede8 | 1d9d45336cbbda7ffd700d3f1c3dd9e8b4ce2745 | refs/heads/master | 2021-07-18T11:43:26.440889 | 2017-10-26T14:31:07 | 2017-10-26T14:31:07 | 108,422,933 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,266 | cpp | // Copyright (c) 2012-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "script/script.h"
#include "test/test_mashhadbit.h"
#include <boost/test/unit_test.hpp>
using namespace std;
BOOST_FIXTURE_TEST_SUITE(script_P2PKH_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(IsPayToPublicKeyHash)
{
// Test CScript::IsPayToPublicKeyHash()
uint160 dummy;
CScript p2pkh;
p2pkh << OP_DUP << OP_HASH160 << ToByteVector(dummy) << OP_EQUALVERIFY << OP_CHECKSIG;
BOOST_CHECK(p2pkh.IsPayToPublicKeyHash());
static const unsigned char direct[] = {
OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG
};
BOOST_CHECK(CScript(direct, direct+sizeof(direct)).IsPayToPublicKeyHash());
static const unsigned char notp2pkh1[] = {
OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG, OP_CHECKSIG
};
BOOST_CHECK(!CScript(notp2pkh1, notp2pkh1+sizeof(notp2pkh1)).IsPayToPublicKeyHash());
static const unsigned char p2sh[] = {
OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUAL
};
BOOST_CHECK(!CScript(p2sh, p2sh+sizeof(p2sh)).IsPayToPublicKeyHash());
static const unsigned char extra[] = {
OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG, OP_CHECKSIG
};
BOOST_CHECK(!CScript(extra, extra+sizeof(extra)).IsPayToPublicKeyHash());
static const unsigned char missing[] = {
OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, OP_EQUALVERIFY, OP_CHECKSIG, OP_RETURN
};
BOOST_CHECK(!CScript(missing, missing+sizeof(missing)).IsPayToPublicKeyHash());
static const unsigned char missing2[] = {
OP_DUP, OP_HASH160, 20, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
};
BOOST_CHECK(!CScript(missing2, missing2+sizeof(missing)).IsPayToPublicKeyHash());
static const unsigned char tooshort[] = {
OP_DUP, OP_HASH160, 2, 0,0, OP_EQUALVERIFY, OP_CHECKSIG
};
BOOST_CHECK(!CScript(tooshort, tooshort+sizeof(direct)).IsPayToPublicKeyHash());
}
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]"
] | |
2e18569184f1ffcb62601f31bb3239115274c175 | 9bf05e213d5448a0b41556032ffc2c4ee916dff0 | /EXERCISE.h | dfda9be619c5184beb2428d8a67eb040bb210a81 | [] | no_license | CPPLondonUni/OOP-Module-Lesson-2 | 52208491a5f7f168359086889f940eb9a7badb85 | 1a51317f89a2eced5bc77cf2591520e2da234460 | refs/heads/master | 2020-04-23T18:36:12.158206 | 2019-02-18T23:45:24 | 2019-02-19T00:16:11 | 171,373,326 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 105 | h | #pragma once
//This is for part 1
class ILogger {
};
// This is for Part 2/3
class StringLogger {
};
| [
"[email protected]"
] | |
312f46161c7186ff2a3a153a581b270dbe102449 | 6ac96a57f2d6e1f1fca264209b76811909df8681 | /spring2017_kzcamp2/day3/b5.cpp | cfc71399a05197e8bfe512d63ec0d53607f4498d | [] | no_license | SBidaibek/acm | ac85ca9b5ae158113e95c3d851c76c61ccd04c6f | b358a79f8753d2c3f9888ab8a5b22b0ec25d15db | refs/heads/master | 2020-04-22T17:19:43.625322 | 2019-02-15T06:22:14 | 2019-02-15T06:22:14 | 170,537,539 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,909 | cpp | #include <bits/stdc++.h>
using namespace std;
#define forn(i, x, n) for (int i = int(x); i <= int(n); ++i)
#define for1(i, n, x) for (int i = int(n); i >= int(x); --i)
#define x first
#define y second
#define pb push_back
typedef long long ll;
typedef pair <int, int> pii;
typedef long double ld;
typedef vector <ll> vi;
const int N = 2e6 + 1;
const ll INF = 1e18 + 9;
const int B = 1e9 + 7;
int st[N];
vi g[N];
int u[N];
bool match(vector <pii> v) {
forn(i, 0, v.size() - 1) u[i] = 0;
for (int s = v.size(); s;) {
int q = s;
forn(i, 0, v.size() - 1) {
if (u[i]) continue;
int c = 0, k = 0;
forn(j, 0, v.size() - 1)
if (!u[j] && i != j && (v[i].x == v[j].x || v[i].y == v[j].y)) ++c, k = j;
if (c == 0) return 0;
if (c == 1) {
u[i] = 1;
u[k] = 1;
s -= 2;
break;
}
}
if (s == q) return 1;
}
return 1;
}
int n, m;
pii a[N];
int main() {
#ifdef black
freopen("in", "r", stdin);
#else
freopen("points.in", "r", stdin);
freopen("points.out", "w", stdout);
#endif // black
ios_base :: sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
forn(i, 1, n * 2 + 1) {
cin >> a[i].x >> a[i].y;
assert(a[i].y > 0);
assert(a[i].x > 0);
}
forn(i, 1, m) {
vector <pii> v;
int x;
cin >> x;
forn(j, 1, n * 2 + 1)
if (j != x)
v.pb(a[j]);
if (match(v)) {
cout << "1\n";
continue;
}
/*for (auto &p : v)
swap(p.x, p.y);
if (match(v)) {
cout << "1\n";
continue;
}*/
cout << "0\n";
}
return 0;
}
| [
"[email protected]"
] | |
332a3797f4f5591fb7ac1d582612a317b466a4b1 | a5c85f43453c5a98bd09e94234e19fb3402b88ba | /CCC/CCC '17 S2 - High Tide, Low Tide.cpp | 57556722d020a5438cf641f3b79f0ed232cdbd0e | [] | no_license | PuffyShoggoth/Competitive | 14d08794ea339e8bd9ce68be0b155c3a2973b39c | d99d45cc4b9f1baa15924eaeccfe737aa2824794 | refs/heads/master | 2021-09-16T02:43:40.876418 | 2018-06-14T23:37:18 | 2018-06-14T23:37:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 399 | cpp | #include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> tides;
int main(){
int n;
int sc;
scanf("%i", &n);
for(int i=0; i<n; i++){
scanf("%i", &sc);
tides.push_back(sc);
}
sort(tides.begin(), tides.end());
int st=n/2-1+n%2, ed=n/2+n%2;
while(ed<n){
printf("%i %i ", tides[st], tides[ed]);
st--; ed++;
}
if (st==0){
printf("%i", tides[st]);
}
} | [
"[email protected]"
] | |
b0332ce5974d21bc82a09cd96806d92bb52ddd6f | b8ed71f3d1a36c119d846e97f1aa7d8ba6774f52 | /101_Symmetric_Tree.cpp | 0a70d58178dace104541aea8f064938ca5a8f699 | [] | no_license | imjaya/Leetcode_solved | 0831c4114dd919864452430c4e46d3f69b4bd0cd | 374eb0f23ae14d9638d20bbfe622209f71397ae0 | refs/heads/master | 2023-05-24T17:57:56.633611 | 2023-05-16T06:31:42 | 2023-05-16T06:31:42 | 284,203,426 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
queue<TreeNode*> queue;
if(root==NULL) return true;
queue.push(root); queue.push(root);
while(!queue.empty())
{
TreeNode* left = queue.front(); queue.pop();
TreeNode *right = queue.front(); queue.pop();
if(left==NULL && right==NULL) continue;
if(left==NULL || right==NULL) return false;
if(left->val != right->val) return false;
queue.push(left->left);
queue.push(right->right);
queue.push(left->right);
queue.push(right->left);
}
return true;
}
}; | [
"[email protected]"
] | |
4d5d1c6f7967da943c431680e5b2b2d5cc558007 | af1ca1da86f6601e7d9774dc164fd99095f64639 | /src/MobCombat.cpp | e3cab8f629883e1b6f091cd42d3b5862f6548506 | [] | no_license | pylgrym/basin | ba07751b98607900339113583f52ce0e07539501 | de067738c369c6f0dbdea752676ecf38952e583a | refs/heads/master | 2023-03-04T06:48:02.377659 | 2023-03-02T08:25:35 | 2023-03-02T08:25:35 | 30,758,171 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,913 | cpp | #include "stdafx.h"
#include "MobCombat.h"
#include "mob.h"
// MobCombat::MobCombat() {}
// MobCombat::~MobCombat(){}
double AttackInf::calcHitChance() const {
double hitRatio = hitThres / 20.0;
return hitRatio;
}
void AttackInf::repHitChance(std::ostream& os) {
double chance = calcHitChance();
int percent = int(chance*100.0 + 0.5);
//os << std::fixed << std::setw(4) << std::setprecision(2) << chance;
os << percent;
}
bool Mob::hitTest(class Mob& adv, AttackInf& ai) {
// int& hitRoll, int hitBonus) { // FIXME: consider passing entire weapon-obj instead of just the hitbonus.
ai.hitRoll = rnd::Dx(20);
// toHit is your ability to hit,
// your opponent's ac will counter your ability to hit.
ai.advAC = adv.stats.ac;
ai.finalToHit = (stats.toHit + ai.wpHitBonus);
ai.hitThres = ai.finalToHit - ai.advAC;
bool bHit = false;
if (ai.hitRoll == 20) { // a 20 is automatic MISS.
bHit = false;
} else if (ai.hitRoll == 1) { // a 1 is automatic HIT.
bHit = true;
} else {
bHit = (ai.hitRoll <= ai.hitThres);
}
return bHit;
}
bool Mob::calcAttack(std::ostream& os, AttackInf& ai, Mob& adv, Obj* attackItem, AttackSchool school, SpellEnum spell, bool overrideHit) {
// Collect 'attack info' in an AttackInfo struct.
//ai.school = school; // FIXME, record that..
adv.makeAngry();
if (isPlayer()) {
if (attackItem != NULL) { ai.wpHitBonus = attackItem->toHit; }
}
ai.bHit = hitTest(adv, ai);
if (overrideHit) { ai.bHit = true; }
if (!ai.bHit) { return false; }
if (spell == SP_NoSpell) { // A physical/melee attack.. (or an arrow/throw-item?)
ai.attackDice = mobWeaponDice();
if (isPlayer()) {
if (attackItem != NULL) {
ai.attackDice = attackItem->dmgDice;
ai.dmgBonus = attackItem->toDmg;
}
}
} else { // A spell-based attack.
const SpellDesc& desc = Spell::spell(spell);
ai.attackDice = Dice(desc.dice.num, desc.dice.side);
}
{
std::stringstream inf;
inf << "attack roll " << ai.attackDice.n << "d" << ai.attackDice.x << ": ";
// We save the above info for later, because we only generate attack-log-info at a later point
// (and I want to list the info in a sensible order.)
ai.dmgRoll = ai.attackDice.roll(inf);
ai.dmgRollInfo = inf.str();
}
if (school == SC_Phys) {
ai.dmgMod = stats.statMod("str"); // You get your strength bonus added to dmg. IF it's physical.
}
ai.dmg += ai.dmgRoll + ai.dmgMod + ai.dmgBonus;
if (ai.dmg < 1) { ai.dmg = 1; } // You always hit for at least 1
ai.dmgTaken = adv.takeDamage(ai.dmg, school);
return true;
}
int Mob::takeDamage(int dmg, AttackSchool damageType) { // returns dmgTaken
int dmgTaken = dmg; // Might be adjusted by resistances or vulnerabilities. (should we calculate this here, or outside in dmg code?)
stats.hp -= dmgTaken;
return dmgTaken;
}
| [
"[email protected]"
] | |
1802de23d643ee7a0ab53aead074768f4511f3ee | e384f5467d8bcfd70845997bcbd68d950e874a61 | /example/cpp/_render_util/include/OpenGL/OpenGLPolygon_core_and_es.h | a3a64df4f01e7b5b85d6bec2607a11a167d39dd2 | [] | no_license | Rabbid76/graphics-snippets | ee642f1ed9ceafc6d320e467d3a084d2446d22c2 | fa187afeabb9630bc1d988304fb5787e95a91385 | refs/heads/master | 2023-08-04T04:32:06.884318 | 2023-07-21T09:15:43 | 2023-07-21T09:15:43 | 109,126,544 | 177 | 12 | null | 2023-04-11T20:05:52 | 2017-11-01T12:05:56 | C++ | UTF-8 | C++ | false | false | 6,723 | h | /******************************************************************//**
* \brief Implementation of OpenGL polygon renderer,
* with the use of "modern" OpenGL 4+ core and
* GLSL version 4.30 (`#version 4230 core`) or
* OpenGL es 3(+) and GLSL ES version 3.00 (`#version 300 es`).
*
* \author gernot
* \date 2018-12-05
* \version 1.0
**********************************************************************/
#pragma once
#ifndef OpenGLPolygon_4_h_INCLUDED
#define OpenGLPolygon_4_h_INCLUDED
// includes
#include "../render/Render_IDrawType.h"
#include "../render/Render_IDrawPolygon.h"
#include "../render/Render_IBuffer.h"
#include "OpenGLDataBuffer_std140.h"
// class definitions
/******************************************************************//**
* \brief General namespace for OpenGL implementation.
*
* \author gernot
* \date 2018-12-05
* \version 1.0
**********************************************************************/
namespace OpenGL
{
class CPrimitiveOpenGL_core_and_es;
/******************************************************************//**
* \brief Namespace for drawing polygons with the use of OpenGL.
*
* \author gernot
* \date 2018-12-05
* \version 1.0
**********************************************************************/
namespace Polygon
{
/******************************************************************//**
* \brief Basic implementation of OpenGL polygon renderer,
* with the use of OpenGL 4 core profile or OpenGL ES 3.
*
* \author gernot
* \date 2019-01-07
* \version 1.0
**********************************************************************/
class CPolygon_base_OpenGL4_OpenGLES3
: public Render::Polygon::IRender
{
public:
using TProgramPtr = std::shared_ptr<CPrimitiveOpenGL_core_and_es>;
CPolygon_base_OpenGL4_OpenGLES3( size_t min_cache_elems );
virtual ~CPolygon_base_OpenGL4_OpenGLES3();
const Render::Polygon::TStyle & PoylgonStyle( void ) const { return _polygon_style; }
void PoylgonStyle( const Render::Polygon::TStyle &style ) { _polygon_style = style; }
//! Initialize the polygon renderer
virtual bool Init( void ) override;
virtual bool Init( Render::TModelAndViewPtr mvp_data );
virtual bool Init( TMVPBufferPtr mvp_buffer );
virtual bool Init( TProgramPtr program );
//! Notify the render that a sequence of successive polygons will follow, which is not interrupted by any other drawing operation.
//! This allows the render to do some performance optimizations and to prepare for the polygon rendering.
//! The render can keep states persistent from one polygon drawing to the other, without initializing and restoring them.
//!
//! Not implemented (Software OpenGL).
virtual bool StartSuccessivePolygonDrawings( void ) override;
//! Notify the renderer that a sequence of polygons has been finished, and that the internal states have to be restored.
//!
//! Not implemented (Software OpenGL).
virtual bool FinishSuccessivePolygonDrawings( void ) override;
virtual Render::Polygon::IRender & SetColor( const Render::TColor & color ) override;
virtual Render::Polygon::IRender & SetColor( const Render::TColor8 & color ) override;
virtual Render::Polygon::IRender & SetStyle( const Render::Polygon::TStyle & style ) override;
//! Draw a polygon sequence
virtual bool Draw( Render::TPrimitive primitive_type, unsigned int tuple_size, size_t coords_size, const float *coords ) override;
virtual bool Draw( Render::TPrimitive primitive_type, unsigned int tuple_size, size_t coords_size, const double *coords ) override;
virtual bool Draw( Render::TPrimitive primitive_type, size_t no_of_coords, const float *x_coords, const float *y_coords ) override;
virtual bool Draw( Render::TPrimitive primitive_type, size_t no_of_coords, const double *x_coords, const double *y_coords ) override;
//! Start a new polygon sequence
virtual bool StartSequence( Render::TPrimitive primitive_type, unsigned int tuple_size ) override;
//! Complete an active polygon sequence
virtual bool EndSequence( void ) override;
//! Specify a new vertex coordinate in an active polygon sequence
virtual bool DrawSequence( float x, float y, float z ) override;
virtual bool DrawSequence( double x, double y, double z ) override;
//! Specify a sequence of new vertex coordinates in an active polygon sequence
virtual bool DrawSequence( size_t coords_size, const float *coords ) override;
virtual bool DrawSequence( size_t coords_size, const double *coords ) override;
private:
bool _initialized{ false }; //!< initialization state of the object
bool _successive_draw_started{ false }; //!< successive drawing was started by this renderer
size_t _min_buffer_size; //!< minimum size of the vertex buffer
TProgramPtr _primitive_prog; //!< primitive render program
Render::Polygon::TStyle _polygon_style; //!< polygon style parameters
Render::TPrimitive _squence_type{ Render::TPrimitive::NO_OF }; //!< primitive type pf the sequence
Render::TVertexCache _vertex_cache; //!< cache for vertex coordinates
};
/******************************************************************//**
* \brief Implementation of OpenGL polygon renderer,
* with the use of OpenGL core profile with forward compatibility flag
* set.
* For the use of OpenGL version 4+ and GLSL version 4.20 (`#version 420 core`)
*
* \author gernot
* \date 2019-01-07
* \version 1.0
**********************************************************************/
using CPolygonOpenGL_core_forward_compatibility = CPolygon_base_OpenGL4_OpenGLES3;
/******************************************************************//**
* \brief Implementation of OpenGL polygon renderer,
* with the use of OpenGL core profile.
* For the use of OpenGL version 4+ and GLSL version 4.20 (`#version 420 core`)
*
* \author gernot
* \date 2019-01-07
* \version 1.0
**********************************************************************/
using CPolygonOpenGL_core_4 = CPolygon_base_OpenGL4_OpenGLES3;
/******************************************************************//**
* \brief Implementation of OpenGL polygon renderer,
* with the use of OpenGL core profile.
* For the use of OpenGL es 3(+) and GLSL ES version 3.00 (`#version 300 es`).
*
* \author gernot
* \date 2019-01-07
* \version 1.0
**********************************************************************/
using CPolygonOpenGL_ES_3 = CPolygon_base_OpenGL4_OpenGLES3;
} // Polygon
} // OpenGL
#endif | [
"[email protected]"
] | |
800810a59d5d6d5705afbde2a75528de53450c07 | 49a0b621ed03c5c95ba1779ded7db3ecb44b522c | /rapidjson/fwd.h | b59e37f0572c1453fd9c367ea5bd81823b20f92d | [] | no_license | SeeMorton1/search-engine-public | e25a1c2c113c448a44f25403b9dc79bfb77de072 | 604dff0136a6c176b6965ff07622f3338a4075c4 | refs/heads/master | 2023-03-02T00:54:55.771914 | 2020-12-07T13:30:45 | 2020-12-07T13:30:45 | 336,358,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,305 | h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#ifndef RAPIDJSON_FWD_H_
#define RAPIDJSON_FWD_H_
#include "rapidjson.h"
RAPIDJSON_NAMESPACE_BEGIN
// encodings.h
template<typename CharType>
struct UTF8;
template<typename CharType>
struct UTF16;
template<typename CharType>
struct UTF16BE;
template<typename CharType>
struct UTF16LE;
template<typename CharType>
struct UTF32;
template<typename CharType>
struct UTF32BE;
template<typename CharType>
struct UTF32LE;
template<typename CharType>
struct ASCII;
template<typename CharType>
struct AutoUTF;
template<typename SourceEncoding, typename TargetEncoding>
struct Transcoder;
// allocators.h
class CrtAllocator;
template<typename BaseAllocator>
class MemoryPoolAllocator;
// stream.h
template<typename Encoding>
struct GenericStringStream;
typedef GenericStringStream<UTF8<char> > StringStream;
template<typename Encoding>
struct GenericInsituStringStream;
typedef GenericInsituStringStream<UTF8<char> > InsituStringStream;
// stringbuffer.h
template<typename Encoding, typename Allocator>
class GenericStringBuffer;
typedef GenericStringBuffer<UTF8<char>, CrtAllocator> StringBuffer;
// filereadstream.h
class FileReadStream;
// filewritestream.h
class FileWriteStream;
// memorybuffer.h
template<typename Allocator>
struct GenericMemoryBuffer;
typedef GenericMemoryBuffer<CrtAllocator> MemoryBuffer;
// memorystream.h
struct MemoryStream;
// reader.h
template<typename Encoding, typename Derived>
struct BaseReaderHandler;
template<typename SourceEncoding, typename TargetEncoding, typename StackAllocator>
class GenericReader;
typedef GenericReader<UTF8<char>, UTF8<char>, CrtAllocator> Reader;
// writer.h
template<typename OutputStream, typename SourceEncoding, typename TargetEncoding, typename StackAllocator, unsigned writeFlags>
class Writer;
// prettywriter.h
template<typename OutputStream, typename SourceEncoding, typename TargetEncoding, typename StackAllocator, unsigned writeFlags>
class PrettyWriter;
// document.h
template<typename Encoding, typename Allocator>
class GenericMember;
template<bool Const, typename Encoding, typename Allocator>
class GenericMemberIterator;
template<typename CharType>
struct GenericStringRef;
template<typename Encoding, typename Allocator>
class GenericValue;
typedef GenericValue<UTF8<char>, MemoryPoolAllocator<CrtAllocator> > Value;
template<typename Encoding, typename Allocator, typename StackAllocator>
class GenericDocument;
typedef GenericDocument<UTF8<char>, MemoryPoolAllocator<CrtAllocator>, CrtAllocator> Document;
// pointer.h
template<typename ValueType, typename Allocator>
class GenericPointer;
typedef GenericPointer<Value, CrtAllocator> Pointer;
// schema.h
template<typename SchemaDocumentType>
class IGenericRemoteSchemaDocumentProvider;
template<typename ValueT, typename Allocator>
class GenericSchemaDocument;
typedef GenericSchemaDocument<Value, CrtAllocator> SchemaDocument;
typedef IGenericRemoteSchemaDocumentProvider<SchemaDocument> IRemoteSchemaDocumentProvider;
template<
typename SchemaDocumentType,
typename OutputHandler,
typename StateAllocator>
class GenericSchemaValidator;
typedef GenericSchemaValidator<SchemaDocument, BaseReaderHandler<UTF8<char>, void>, CrtAllocator> SchemaValidator;
RAPIDJSON_NAMESPACE_END
#endif // RAPIDJSON_RAPIDJSONFWD_H_
| [
"[email protected]"
] | |
7bc276b24af539283aae802bc1d45f5016d9ce2b | 3a4b861cf0085953a6f58df2c63f8dfdfca75f84 | /LeetCode/c++/007_reverseInteger.cc | c3cd670c5bcaaed2e4899922baba47ae0b5b6cc2 | [] | no_license | ElvisKwok/code | f490c1acfb4025ff2dbe00e61379304f2526176f | b2d5560e7fc1f7e14ff3a7eb827282f2732d22a3 | refs/heads/master | 2020-04-15T17:31:37.265803 | 2016-05-09T13:57:42 | 2016-05-09T13:57:42 | 23,882,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,337 | cc | // Source : https://leetcode.com/problems/reverse-integer/
// Author : Elvis Kwok
// Date : 2015-10-13
/**********************************************************************************
*
* Reverse digits of an integer.
*
* Example1: x = 123, return 321
* Example2: x = -123, return -321
*
* click to show spoilers.
*
* Have you thought about this?
*
* Here are some good questions to ask before coding. Bonus points for you if you have
* already thought through this!
*
* If the integer's last digit is 0, what should the output be? ie, cases such as 10,
* 100.
*
* Did you notice that the reversed integer might overflow? Assume the input is a
* 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such
* cases?
*
* For the purpose of this problem, assume that your function returns 0 when the
* reversed integer overflows.
*
* Update (2014-11-10):
* Test cases had been added to test the overflow behavior.
*
*
*
*
*
**********************************************************************************/
/* my wrong answer occured:
* input: 1534236469,
* output: 1056389759, -.......
* expected: 0 , 0
* Do not need to think about input like 8463847412 BECAUSE type int as a passing parameter
*/
#include <iostream>
#include <vector>
#include <cstdlib>
#include <limits>
using namespace std;
class Solution {
public:
int reverse(int x) {
//int MAX_INT = (-1u)>>1, MIN_INT = (-MAX_INT-1);
int MAX_INT = numeric_limits<int>::max(), MIN_INT = numeric_limits<int>::min();
int base = 0;
int bit;
while (x != 0) { // 这里x!=0兼容了正负情形
bit = x % 10;
x /= 10;
if (base > MAX_INT/10 || base < MIN_INT/10)
return 0;
base = base*10 + bit;
}
cout << "MAX_INT % 10 == " << MAX_INT % 10 << endl;
cout << "MIN_INT % 10 == " << MIN_INT % 10 << endl;
return base;
}
};
int main(int argc, char **argv)
{
Solution s;
int MAX_INT = (-1u)>>1, MIN_INT = (-MAX_INT-1);
cout << "MAX_INT: " << MAX_INT << endl;
cout << "MIN_INT: " << MIN_INT << endl;
cout << s.reverse(atoi(argv[1])) << endl;
return 0;
}
| [
"[email protected]"
] | |
aedd31e316ec48be1ebf6257409a86f5dbb182d3 | 2ee2f455ec17dd78e01e59d958554205fb00930a | /spec/models/force_spec.cpp | 032fe27ee8de6799583e24f7e3cfdbd2b9a7aab6 | [] | no_license | ChrisLundquist/Waveform | e7aa37b48128d618ebbfb68a1783a14777cf503a | 7926847f520312b264fc64ca2b0f715e7b83f70c | refs/heads/master | 2021-01-21T05:05:52.060600 | 2012-09-26T22:37:31 | 2012-09-26T22:37:31 | 5,522,255 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 179 | cpp | #include <gtest/gtest.h>
#include "../../src/models/force.h"
TEST(Force, Construct) {
Force f = Force();
EXPECT_EQ(f.position[0], 0);
EXPECT_EQ(f.direction[0], 0);
}
| [
"[email protected]"
] | |
fab2859daf459720b539aec342f5975d9d86459e | 64fe4f897f21a075e27b3c05b736b2fd70329e6b | /CombinationsII.cpp | 14aa68e7703cb1709b7143fd8e4b72b0d79a50e3 | [] | no_license | re3el/LeetCode | ec70383adc0455b7582674aa95695251ce5b5854 | 82a4ba979cc7cb3d3ddb726a5084a3362d2d6993 | refs/heads/master | 2023-06-09T15:45:52.804579 | 2018-01-27T22:07:05 | 2018-01-27T22:07:05 | 104,426,137 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 847 | cpp | class Solution {
public:
void compute(vector<int> &candidates, int target, vector<vector<int>> &res, vector<int> &curr, int begin)
{
if(!target)
{
res.push_back(curr);
return;
}
int n = candidates.size();
for(int i=begin; i<n && candidates[i] <= target; i++)
{
curr.push_back(candidates[i]);
compute(candidates,target-candidates[i],res,curr,i+1);
curr.pop_back();
while(i < n-1 && candidates[i] == candidates[i+1]) i++;
}
}
vector<vector<int>> combinationSum2(vector<int>& candidates, int target)
{
sort(candidates.begin(),candidates.end());
vector<vector<int>> res;
vector<int> curr;
compute(candidates,target,res,curr,0);
return res;
}
}; | [
"[email protected]"
] | |
da7faacfb50e86d8abdaf430c3ba2338e9c57082 | 215dd7a6798c341e3b7b51f5b8880859db40aec8 | /OrderingSystem/OrderDetailsWidget.cpp | 27a9ae0f84a40a5cd8b76b14f93f925324089000 | [] | no_license | dousp1220/OrderingSystem | 1cf60212948fbcf554328115ae9bfecfcd7c9a0d | a189f8e8008da3aeed2e45d0a6fa326b7c9db554 | refs/heads/master | 2020-03-25T13:46:03.203831 | 2018-09-20T04:17:00 | 2018-09-20T04:17:00 | 143,841,929 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 321 | cpp | #include "OrderDetailsWidget.h"
OrderDetailsWidget::OrderDetailsWidget(QWidget *parent) :
QWidget(parent)
{
this->setAttribute(Qt::WA_StyledBackground, true);
// this->setStyleSheet("background: #ffff00;");
init();
}
OrderDetailsWidget::~OrderDetailsWidget()
{
}
void OrderDetailsWidget::init()
{
}
| [
"[email protected]"
] | |
ec9ce8feb59a6ab96ce6c592c2a9b0fa1a768e64 | b4828cf9403fedde5dd346b3338a5f4bf0f1eb96 | /leetcode_sol/2520-Count_The_Digits_That_Divide_A_Number.cpp | af9816560368a4ec410c308c8873483d086c2155 | [] | no_license | Masters-Akt/CS_codes | 9ab3d87ca384ebd364c7b87c8da94b753082a7e3 | 1aaa107439f2e208bb67b0bcca676f90b6bc6a11 | refs/heads/master | 2023-01-24T00:11:05.151592 | 2023-01-21T18:45:57 | 2023-01-21T18:45:57 | 292,529,160 | 6 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 355 | cpp | class Solution {
public:
int countDigits(int num) {
int duplicateNum = num;
int numberOfDigitsThatDivideNum = 0;
while(duplicateNum){
int digit = duplicateNum%10;
if(num%digit==0) numberOfDigitsThatDivideNum++;
duplicateNum/=10;
}
return numberOfDigitsThatDivideNum;
}
}; | [
"[email protected]"
] | |
b8e3e1f60df2d9bc6943f48d5e60cab121a59a84 | f207164511f0dfe3f01f6e0c21fd7548e626397f | /dom/media/VideoUtils.h | 6a9c940ada2b05f2e9829047ba5b9f0a44690eac | [] | no_license | PortableApps/palemoon27 | 24dbac1a4b6fe620611f4fb6800a29ae6f008d37 | 3d7e107cc639bc714906baad262a3492372e05d7 | refs/heads/master | 2023-08-15T12:32:23.822300 | 2021-10-11T01:54:45 | 2021-10-11T01:54:45 | 416,058,642 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,255 | h | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim:set ts=2 sw=2 sts=2 et cindent: */
/* 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/. */
#ifndef VideoUtils_h
#define VideoUtils_h
#include "mozilla/Attributes.h"
#include "mozilla/ReentrantMonitor.h"
#include "mozilla/CheckedInt.h"
#include "nsIThread.h"
#include "nsSize.h"
#include "nsRect.h"
#if !(defined(XP_WIN) || defined(XP_MACOSX) || defined(LINUX)) || \
defined(MOZ_ASAN)
// For MEDIA_THREAD_STACK_SIZE
#include "nsIThreadManager.h"
#endif
#include "nsThreadUtils.h"
#include "prtime.h"
#include "AudioSampleFormat.h"
#include "mozilla/RefPtr.h"
#include "TimeUnits.h"
using mozilla::CheckedInt64;
using mozilla::CheckedUint64;
using mozilla::CheckedInt32;
using mozilla::CheckedUint32;
// This file contains stuff we'd rather put elsewhere, but which is
// dependent on other changes which we don't want to wait for. We plan to
// remove this file in the near future.
// This belongs in xpcom/monitor/Monitor.h, once we've made
// mozilla::Monitor non-reentrant.
namespace mozilla {
/**
* ReentrantMonitorConditionallyEnter
*
* Enters the supplied monitor only if the conditional value |aEnter| is true.
* E.g. Used to allow unmonitored read access on the decode thread,
* and monitored access on all other threads.
*/
class MOZ_STACK_CLASS ReentrantMonitorConditionallyEnter
{
public:
ReentrantMonitorConditionallyEnter(bool aEnter,
ReentrantMonitor &aReentrantMonitor) :
mReentrantMonitor(nullptr)
{
MOZ_COUNT_CTOR(ReentrantMonitorConditionallyEnter);
if (aEnter) {
mReentrantMonitor = &aReentrantMonitor;
NS_ASSERTION(mReentrantMonitor, "null monitor");
mReentrantMonitor->Enter();
}
}
~ReentrantMonitorConditionallyEnter(void)
{
if (mReentrantMonitor) {
mReentrantMonitor->Exit();
}
MOZ_COUNT_DTOR(ReentrantMonitorConditionallyEnter);
}
private:
// Restrict to constructor and destructor defined above.
ReentrantMonitorConditionallyEnter();
ReentrantMonitorConditionallyEnter(const ReentrantMonitorConditionallyEnter&);
ReentrantMonitorConditionallyEnter& operator =(const ReentrantMonitorConditionallyEnter&);
static void* operator new(size_t) CPP_THROW_NEW;
static void operator delete(void*);
ReentrantMonitor* mReentrantMonitor;
};
// Shuts down a thread asynchronously.
class ShutdownThreadEvent : public nsRunnable
{
public:
explicit ShutdownThreadEvent(nsIThread* aThread) : mThread(aThread) {}
~ShutdownThreadEvent() {}
NS_IMETHOD Run() override {
mThread->Shutdown();
mThread = nullptr;
return NS_OK;
}
private:
nsCOMPtr<nsIThread> mThread;
};
template<class T>
class DeleteObjectTask: public nsRunnable {
public:
explicit DeleteObjectTask(nsAutoPtr<T>& aObject)
: mObject(aObject)
{
}
NS_IMETHOD Run() {
NS_ASSERTION(NS_IsMainThread(), "Must be on main thread.");
mObject = nullptr;
return NS_OK;
}
private:
nsAutoPtr<T> mObject;
};
template<class T>
void DeleteOnMainThread(nsAutoPtr<T>& aObject) {
NS_DispatchToMainThread(new DeleteObjectTask<T>(aObject));
}
class MediaResource;
// Estimates the buffered ranges of a MediaResource using a simple
// (byteOffset/length)*duration method. Probably inaccurate, but won't
// do file I/O, and can be used when we don't have detailed knowledge
// of the byte->time mapping of a resource. aDurationUsecs is the duration
// of the media in microseconds. Estimated buffered ranges are stored in
// aOutBuffered. Ranges are 0-normalized, i.e. in the range of (0,duration].
media::TimeIntervals GetEstimatedBufferedTimeRanges(mozilla::MediaResource* aStream,
int64_t aDurationUsecs);
// Converts from number of audio frames (aFrames) to microseconds, given
// the specified audio rate (aRate). Stores result in aOutUsecs. Returns true
// if the operation succeeded, or false if there was an integer overflow
// while calulating the conversion.
CheckedInt64 FramesToUsecs(int64_t aFrames, uint32_t aRate);
// Converts from number of audio frames (aFrames) TimeUnit, given
// the specified audio rate (aRate).
media::TimeUnit FramesToTimeUnit(int64_t aFrames, uint32_t aRate);
// Converts from microseconds (aUsecs) to number of audio frames, given the
// specified audio rate (aRate). Stores the result in aOutFrames. Returns
// true if the operation succeeded, or false if there was an integer
// overflow while calulating the conversion.
CheckedInt64 UsecsToFrames(int64_t aUsecs, uint32_t aRate);
// Format TimeUnit as number of frames at given rate.
CheckedInt64 TimeUnitToFrames(const media::TimeUnit& aTime, uint32_t aRate);
// Converts milliseconds to seconds.
#define MS_TO_SECONDS(ms) ((double)(ms) / (PR_MSEC_PER_SEC))
// Converts seconds to milliseconds.
#define SECONDS_TO_MS(s) ((int)((s) * (PR_MSEC_PER_SEC)))
// Converts from seconds to microseconds. Returns failure if the resulting
// integer is too big to fit in an int64_t.
nsresult SecondsToUsecs(double aSeconds, int64_t& aOutUsecs);
// The maximum height and width of the video. Used for
// sanitizing the memory allocation of the RGB buffer.
// The maximum resolution we anticipate encountering in the
// wild is 2160p - 3840x2160 pixels.
static const int32_t MAX_VIDEO_WIDTH = 4000;
static const int32_t MAX_VIDEO_HEIGHT = 3000;
// Scales the display rect aDisplay by aspect ratio aAspectRatio.
// Note that aDisplay must be validated by IsValidVideoRegion()
// before being used!
void ScaleDisplayByAspectRatio(nsIntSize& aDisplay, float aAspectRatio);
// The amount of virtual memory reserved for thread stacks.
#if defined(MOZ_ASAN)
// Use the system default in ASAN builds, because the default is assumed to be
// larger than the size we want to use and is hopefully sufficient for ASAN.
#define MEDIA_THREAD_STACK_SIZE nsIThreadManager::DEFAULT_STACK_SIZE
#elif defined(XP_WIN) || defined(XP_MACOSX) || defined(LINUX)
#define MEDIA_THREAD_STACK_SIZE (256 * 1024)
#else
// All other platforms use their system defaults.
#define MEDIA_THREAD_STACK_SIZE nsIThreadManager::DEFAULT_STACK_SIZE
#endif
// Downmix multichannel Audio samples to Stereo.
// Input are the buffer contains multichannel data,
// the number of channels and the number of frames.
int DownmixAudioToStereo(mozilla::AudioDataValue* buffer,
int channels,
uint32_t frames);
bool IsVideoContentType(const nsCString& aContentType);
// Returns true if it's safe to use aPicture as the picture to be
// extracted inside a frame of size aFrame, and scaled up to and displayed
// at a size of aDisplay. You should validate the frame, picture, and
// display regions before using them to display video frames.
bool IsValidVideoRegion(const nsIntSize& aFrame, const nsIntRect& aPicture,
const nsIntSize& aDisplay);
// Template to automatically set a variable to a value on scope exit.
// Useful for unsetting flags, etc.
template<typename T>
class AutoSetOnScopeExit {
public:
AutoSetOnScopeExit(T& aVar, T aValue)
: mVar(aVar)
, mValue(aValue)
{}
~AutoSetOnScopeExit() {
mVar = mValue;
}
private:
T& mVar;
const T mValue;
};
class SharedThreadPool;
// The MediaDataDecoder API blocks, with implementations waiting on platform
// decoder tasks. These platform decoder tasks are queued on a separate
// thread pool to ensure they can run when the MediaDataDecoder clients'
// thread pool is blocked. Tasks on the PLATFORM_DECODER thread pool must not
// wait on tasks in the PLAYBACK thread pool.
enum class MediaThreadType {
PLAYBACK, // MediaDecoderStateMachine and MediaDecoderReader
PLATFORM_DECODER
};
// Returns the thread pool that is shared amongst all decoder state machines
// for decoding streams.
already_AddRefed<SharedThreadPool> GetMediaThreadPool(MediaThreadType aType);
enum H264_PROFILE {
H264_PROFILE_UNKNOWN = 0,
H264_PROFILE_BASE = 0x42,
H264_PROFILE_MAIN = 0x4D,
H264_PROFILE_EXTENDED = 0x58,
H264_PROFILE_HIGH = 0x64,
};
enum H264_LEVEL {
H264_LEVEL_1 = 10,
H264_LEVEL_1_b = 11,
H264_LEVEL_1_1 = 11,
H264_LEVEL_1_2 = 12,
H264_LEVEL_1_3 = 13,
H264_LEVEL_2 = 20,
H264_LEVEL_2_1 = 21,
H264_LEVEL_2_2 = 22,
H264_LEVEL_3 = 30,
H264_LEVEL_3_1 = 31,
H264_LEVEL_3_2 = 32,
H264_LEVEL_4 = 40,
H264_LEVEL_4_1 = 41,
H264_LEVEL_4_2 = 42,
H264_LEVEL_5 = 50,
H264_LEVEL_5_1 = 51,
H264_LEVEL_5_2 = 52
};
// Extracts the H.264/AVC profile and level from an H.264 codecs string.
// H.264 codecs parameters have a type defined as avc1.PPCCLL, where
// PP = profile_idc, CC = constraint_set flags, LL = level_idc.
// See http://blog.pearce.org.nz/2013/11/what-does-h264avc1-codecs-parameters.html
// for more details.
// Returns false on failure.
bool
ExtractH264CodecDetails(const nsAString& aCodecs,
int16_t& aProfile,
int16_t& aLevel);
// Use a cryptographic quality PRNG to generate raw random bytes
// and convert that to a base64 string.
nsresult
GenerateRandomName(nsCString& aOutSalt, uint32_t aLength);
// This version returns a string suitable for use as a file or URL
// path. This is based on code from nsExternalAppHandler::SetUpTempFile.
nsresult
GenerateRandomPathName(nsCString& aOutSalt, uint32_t aLength);
class MediaTaskQueue;
class FlushableMediaTaskQueue;
already_AddRefed<MediaTaskQueue>
CreateMediaDecodeTaskQueue();
already_AddRefed<FlushableMediaTaskQueue>
CreateFlushableMediaDecodeTaskQueue();
bool
ParseCodecsString(const nsAString& aCodecs, nsTArray<nsString>& aOutCodecs);
bool
IsH264ContentType(const nsAString& aContentType);
bool
IsAACContentType(const nsAString& aContentType);
bool
IsAACCodecString(const nsAString& aCodec);
} // end namespace mozilla
#endif
| [
"[email protected]"
] | |
14c94c017b3bb7ddfd6a1e5a668162a8a95f9334 | 600df3590cce1fe49b9a96e9ca5b5242884a2a70 | /extensions/browser/updater/update_install_shim.h | 518866a6062c2fd316621bde2bc2d30a03f3fb02 | [
"BSD-3-Clause"
] | permissive | metux/chromium-suckless | efd087ba4f4070a6caac5bfbfb0f7a4e2f3c438a | 72a05af97787001756bae2511b7985e61498c965 | refs/heads/orig | 2022-12-04T23:53:58.681218 | 2017-04-30T10:59:06 | 2017-04-30T23:35:58 | 89,884,931 | 5 | 3 | BSD-3-Clause | 2022-11-23T20:52:53 | 2017-05-01T00:09:08 | null | UTF-8 | C++ | false | false | 2,924 | h | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_UPDATER_UPDATE_INSTALL_SHIM_H_
#define EXTENSIONS_BROWSER_UPDATER_UPDATE_INSTALL_SHIM_H_
#include <string>
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "components/update_client/update_client.h"
namespace base {
class DictionaryValue;
}
namespace extensions {
// A callback to implement the install of a new version of the extension.
// Takes ownership of the directory at |temp_dir|.
using UpdateInstallShimCallback =
base::Callback<void(const std::string& extension_id,
const base::FilePath& temp_dir)>;
// This class is used as a shim between the components::update_client and
// extensions code, to help the generic update_client code prepare and then
// install an updated version of an extension. Because the update_client code
// doesn't have the notion of extension ids, we use instances of this class to
// map an install request back to the original update check for a given
// extension.
class UpdateInstallShim : public update_client::CrxInstaller {
public:
// This method takes the id and root directory for an extension we're doing
// an update check for, as well as a callback to call if we get a new version
// of it to install.
UpdateInstallShim(std::string extension_id,
const base::FilePath& extension_root,
const UpdateInstallShimCallback& callback);
// Called when an update attempt failed.
void OnUpdateError(int error) override;
// This is called when a new version of an extension is unpacked at
// |unpack_path| and is ready for install.
bool Install(const base::DictionaryValue& manifest,
const base::FilePath& unpack_path) override;
// This is called by the generic differential update code in the
// update_client to provide the path to an existing file in the current
// version of the extension, so that it can be copied (or serve as the input
// to diff-patching) with output going to the directory with the new version
// being staged on disk for install.
bool GetInstalledFile(const std::string& file,
base::FilePath* installed_file) override;
// This method is not relevant to extension updating.
bool Uninstall() override;
private:
friend class base::RefCountedThreadSafe<UpdateInstallShim>;
~UpdateInstallShim() override;
// Takes ownership of the directory at path |temp_dir|.
void RunCallbackOnUIThread(const base::FilePath& temp_dir);
std::string extension_id_;
base::FilePath extension_root_;
UpdateInstallShimCallback callback_;
DISALLOW_COPY_AND_ASSIGN(UpdateInstallShim);
};
} // namespace extensions
#endif // EXTENSIONS_BROWSER_UPDATER_UPDATE_INSTALL_SHIM_H_
| [
"[email protected]"
] | |
657636be8d6b9eb94656db1af83bdb08077ede7f | fb3c1e036f18193d6ffe59f443dad8323cb6e371 | /application/SpiritTool/SpiritTool/ApkMake.h | d0ba30acd138883a4d4acd4a13e0c2dd5c5e18f0 | [] | no_license | playbar/nstest | a61aed443af816fdc6e7beab65e935824dcd07b2 | d56141912bc2b0e22d1652aa7aff182e05142005 | refs/heads/master | 2021-06-03T21:56:17.779018 | 2016-08-01T03:17:39 | 2016-08-01T03:17:39 | 64,627,195 | 3 | 1 | null | null | null | null | GB18030 | C++ | false | false | 1,532 | h | #pragma once
#include "PointerArray.h"
#include "SpiritData.h"
class CApkMake
{
public:
class MakeListener
{
public:
virtual void onListen(int type,unsigned long data)=0;
};
public:
static CApkMake* Singleton()
{
static CApkMake* sl = NULL;
if(sl == NULL)
{
sl = new CApkMake();
}
return sl;
}
public:
CApkMake(void);
~CApkMake(void);
public:
//设置源码路径和sdk路径
void setPath(const char* srcpath,const char* sdkpath);
//开始打包
void startMake();
void stopMake();
void setListener(MakeListener* listener);
//打包器控制
void start();
void end();
void setDataArray(CPointerArray<CSpiritData>* data);
int getMakedCount();
int getMakingId();
public:
DWORD CallBack();
private:
void ready();
void go();
void modulatepath(const char *packagename,char *path); //调制路径
void changestring(const char *appname,const char* ua,const char* channel,const char* fname); //修改strings.xml
void changeDesktop(bool bDesktop,const char* fname);
private:
static DWORD WINAPI ThreadProc(LPVOID lpParam);
private:
char *m_plOldPackageName; //程序包名
CPointerArray<CSpiritData> *m_pArray; //数据队列
int m_nMakedCount; //已打包数
HANDLE m_hthread; //线程句柄
HANDLE m_hevent; //事件对象
HANDLE m_hclose; //关闭事件
HANDLE m_hclosed; //以关闭事件
MakeListener* m_pListener; //监听者
char* m_plSrcpath; //源码路径
char* m_plSdkpath; //sdk路径
};
| [
"[email protected]"
] | |
8d3667983bea1e7ae541ac2446e40c1d66edfbfc | 037faae47a5b22d3e283555e6b5ac2a0197faf18 | /plugins/gs/gsdx9/GSSoftVertexFP.h | 10269456db6d1da2c8696dd63c6e9c84a370274e | [] | no_license | isabella232/pcsx2-sourceforge | 6e5aac8d0b476601bfc8fa83ded66c1564b8c588 | dbb2c3a010081b105a8cba0c588f1e8f4e4505c6 | refs/heads/master | 2023-03-18T22:23:15.102593 | 2008-11-17T20:10:17 | 2008-11-17T20:10:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,299 | h | /*
* Copyright (C) 2003-2005 Gabest
* http://www.gabest.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 GNU Make; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
#pragma once
//
// GSSoftVertexFP
//
__declspec(align(16)) union GSSoftVertexFP
{
class __declspec(novtable) Scalar
{
float val;
public:
Scalar() {}
explicit Scalar(float f) {val = f;}
explicit Scalar(int i) {val = (float)i;}
float Value() const {return val;}
#if _M_IX86_FP >= 2 || defined(_M_AMD64)
void sat() {_mm_store_ss(&val, _mm_min_ss(_mm_max_ss(_mm_set_ss(val), _mm_setzero_ps()), _mm_set_ss(255)));}
void rcp() {_mm_store_ss(&val, _mm_rcp_ss(_mm_set_ss(val)));}
#else
void sat() {val = val < 0 ? 0 : val > 255 ? 255 : val;}
void rcp() {val = 1.0f / val;}
#endif
void abss() {val = abs(val);}
Scalar floors() const {return Scalar(floor(val));}
int floori() const {return (int)floor(val);}
Scalar ceils() const {return Scalar(-floor(-val));}
int ceili() const {return -(int)floor(-val);}
void operator = (float f) {val = f;}
void operator = (int i) {val = (float)i;}
operator float() const {return val;}
operator int() const {return (int)val;}
void operator += (const Scalar& s) {val += s.val;}
void operator -= (const Scalar& s) {val -= s.val;}
void operator *= (const Scalar& s) {val *= s.val;}
void operator /= (const Scalar& s) {val /= s.val;}
friend Scalar operator + (const Scalar& s1, const Scalar& s2) {return Scalar(s1.val + s2.val);}
friend Scalar operator - (const Scalar& s1, const Scalar& s2) {return Scalar(s1.val - s2.val);}
friend Scalar operator * (const Scalar& s1, const Scalar& s2) {return Scalar(s1.val * s2.val);}
friend Scalar operator / (const Scalar& s1, const Scalar& s2) {return Scalar(s1.val / s2.val);}
friend Scalar operator + (const Scalar& s1, int i) {return Scalar(s1.val + i);}
friend Scalar operator - (const Scalar& s1, int i) {return Scalar(s1.val - i);}
friend Scalar operator * (const Scalar& s1, int i) {return Scalar(s1.val * i);}
friend Scalar operator / (const Scalar& s1, int i) {return Scalar(s1.val / i);}
friend bool operator == (const Scalar& s1, const Scalar& s2) {return s1.val == s2.val;}
friend bool operator <= (const Scalar& s1, const Scalar& s2) {return s1.val <= s2.val;}
friend bool operator < (const Scalar& s1, const Scalar& s2) {return s1.val < s2.val;}
};
__declspec(align(16)) class __declspec(novtable) Vector
{
public:
union
{
union {struct {Scalar x, y, z, q;}; struct {Scalar r, g, b, a;};};
union {struct {Scalar v[4];}; struct {Scalar c[4];};};
#if _M_IX86_FP >= 2 || defined(_M_AMD64)
union {__m128 xyzq; __m128 rgba;};
#endif
};
Vector() {}
Vector(const Vector& v) {*this = v;}
Vector(Scalar s) {*this = s;}
Vector(Scalar s0, Scalar s1, Scalar s2, Scalar s3) {x = s0; y = s1; z = s2; q = s3;}
explicit Vector(DWORD dw) {*this = dw;}
#if _M_IX86_FP >= 2 || defined(_M_AMD64)
Vector(__m128 f0123) {*this = f0123;}
#endif
#if _M_IX86_FP >= 2 || defined(_M_AMD64)
void operator = (const Vector& v) {xyzq = v.xyzq;}
void operator = (__m128 f0123) {xyzq = f0123;}
void operator = (Scalar s) {xyzq = _mm_set1_ps(s);}
void operator = (DWORD dw) {__m128i zero = _mm_setzero_si128(); xyzq = _mm_cvtepi32_ps(_mm_unpacklo_epi16(_mm_unpacklo_epi8(_mm_cvtsi32_si128(dw), zero), zero));}
operator __m128() const {return xyzq;}
operator DWORD() const {__m128i r0 = _mm_cvttps_epi32(xyzq); r0 = _mm_packs_epi32(r0, r0); r0 = _mm_packus_epi16(r0, r0); return (DWORD)_mm_cvtsi128_si32(r0);}
void sat() {xyzq = _mm_min_ps(_mm_max_ps(xyzq, _mm_setzero_ps()), _mm_set1_ps(255));}
void rcp() {xyzq = _mm_rcp_ps(xyzq);}
void operator += (const Vector& v) {xyzq = _mm_add_ps(xyzq, v);}
void operator -= (const Vector& v) {xyzq = _mm_sub_ps(xyzq, v);}
void operator *= (const Vector& v) {xyzq = _mm_mul_ps(xyzq, v);}
void operator /= (const Vector& v) {xyzq = _mm_div_ps(xyzq, v);}
#else
void operator = (const Vector& v) {x = v.x; y = v.y; z = v.z; q = v.q;}
void operator = (Scalar s) {x = y = z = q = s;}
void operator = (DWORD dw)
{
x = Scalar((int)(dw&0xff));
y = Scalar((int)((dw>>8)&0xff));
z = Scalar((int)((dw>>16)&0xff));
q = Scalar((int)((dw>>24)&0xff));
}
operator DWORD() const
{
return (DWORD)((((DWORD)(int)x&0xff)<<0) | (((DWORD)(int)y&0xff)<<8) | (((DWORD)(int)z&0xff)<<16) | (((DWORD)(int)q&0xff)<<24));
}
void sat() {x.sat(); y.sat(); z.sat(); q.sat();}
void rcp() {x.rcp(); y.rcp(); z.rcp(); q.rcp();}
void operator += (const Vector& v) {*this = *this + v;}
void operator -= (const Vector& v) {*this = *this - v;}
void operator *= (const Vector& v) {*this = *this * v;}
void operator /= (const Vector& v) {*this = *this / v;}
#endif
void absv() {x.abss(); y.abss(); z.abss(); q.abss();}
friend Vector operator + (const Vector& v1, const Vector& v2);
friend Vector operator - (const Vector& v1, const Vector& v2);
friend Vector operator * (const Vector& v1, const Vector& v2);
friend Vector operator / (const Vector& v1, const Vector& v2);
friend Vector operator + (const Vector& v, Scalar s);
friend Vector operator - (const Vector& v, Scalar s);
friend Vector operator * (const Vector& v, Scalar s);
friend Vector operator / (const Vector& v, Scalar s);
};
struct {__declspec(align(16)) Vector c, p, t;};
struct {__declspec(align(16)) Vector sv[3];};
struct {__declspec(align(16)) Scalar s[12];};
GSSoftVertexFP() {}
GSSoftVertexFP(const GSSoftVertexFP& v) {*this = v;}
void operator = (const GSSoftVertexFP& v) {c = v.c; p = v.p; t = v.t;}
void operator += (const GSSoftVertexFP& v) {c += v.c; p += v.p; t += v.t;}
operator CPoint() const {return CPoint((int)p.x, (int)p.y);}
friend GSSoftVertexFP operator + (const GSSoftVertexFP& v1, const GSSoftVertexFP& v2);
friend GSSoftVertexFP operator - (const GSSoftVertexFP& v1, const GSSoftVertexFP& v2);
friend GSSoftVertexFP operator * (const GSSoftVertexFP& v, Scalar s);
friend GSSoftVertexFP operator / (const GSSoftVertexFP& v, Scalar s);
static void Exchange(GSSoftVertexFP* __restrict v1, GSSoftVertexFP* __restrict v2)
{
// GSSoftVertexFP v = *v1; *v1 = *v2; *v2 = v;
Vector c = v1->c, p = v1->p, t = v1->t;
v1->c = v2->c; v1->p = v2->p; v1->t = v2->t;
v2->c = c; v2->p = p; v2->t = t;
}
//__forceinline DWORD GetZ() const {return ((DWORD)p.z<<16) + (DWORD)((p.z - floorf(p.z))*65536 + p.q);}
__forceinline DWORD GetZ() const
{
ASSERT((float)p.z >= 0 && (float)p.q >= 0);
int z = (int)p.z;
return ((DWORD)z << 16) + (DWORD)(((float)p.z - z)*65536 + (float)p.q);
}
};
#if _M_IX86_FP >= 2 || defined(_M_AMD64)
__forceinline GSSoftVertexFP::Vector operator + (const GSSoftVertexFP::Vector& v1, const GSSoftVertexFP::Vector& v2) {return GSSoftVertexFP::Vector(_mm_add_ps(v1, v2));}
__forceinline GSSoftVertexFP::Vector operator - (const GSSoftVertexFP::Vector& v1, const GSSoftVertexFP::Vector& v2) {return GSSoftVertexFP::Vector(_mm_sub_ps(v1, v2));}
__forceinline GSSoftVertexFP::Vector operator * (const GSSoftVertexFP::Vector& v1, const GSSoftVertexFP::Vector& v2) {return GSSoftVertexFP::Vector(_mm_mul_ps(v1, v2));}
__forceinline GSSoftVertexFP::Vector operator / (const GSSoftVertexFP::Vector& v1, const GSSoftVertexFP::Vector& v2) {return GSSoftVertexFP::Vector(_mm_div_ps(v1, v2));}
__forceinline GSSoftVertexFP::Vector operator + (const GSSoftVertexFP::Vector& v, GSSoftVertexFP::Scalar s) {return GSSoftVertexFP::Vector(_mm_add_ps(v, _mm_set1_ps(s)));}
__forceinline GSSoftVertexFP::Vector operator - (const GSSoftVertexFP::Vector& v, GSSoftVertexFP::Scalar s) {return GSSoftVertexFP::Vector(_mm_sub_ps(v, _mm_set1_ps(s)));}
__forceinline GSSoftVertexFP::Vector operator * (const GSSoftVertexFP::Vector& v, GSSoftVertexFP::Scalar s) {return GSSoftVertexFP::Vector(_mm_mul_ps(v, _mm_set1_ps(s)));}
__forceinline GSSoftVertexFP::Vector operator / (const GSSoftVertexFP::Vector& v, GSSoftVertexFP::Scalar s) {return GSSoftVertexFP::Vector(_mm_div_ps(v, _mm_set1_ps(s)));}
#else
__forceinline GSSoftVertexFP::Vector operator + (const GSSoftVertexFP::Vector& v1, const GSSoftVertexFP::Vector& v2) {return GSSoftVertexFP::Vector(v1.x + v2.x, v1.y + v2.y, v1.z + v2.z, v1.q + v2.q);}
__forceinline GSSoftVertexFP::Vector operator - (const GSSoftVertexFP::Vector& v1, const GSSoftVertexFP::Vector& v2) {return GSSoftVertexFP::Vector(v1.x - v2.x, v1.y - v2.y, v1.z - v2.z, v1.q - v2.q);}
__forceinline GSSoftVertexFP::Vector operator * (const GSSoftVertexFP::Vector& v1, const GSSoftVertexFP::Vector& v2) {return GSSoftVertexFP::Vector(v1.x * v2.x, v1.y * v2.y, v1.z * v2.z, v1.q * v2.q);}
__forceinline GSSoftVertexFP::Vector operator / (const GSSoftVertexFP::Vector& v1, const GSSoftVertexFP::Vector& v2) {return GSSoftVertexFP::Vector(v1.x / v2.x, v1.y / v2.y, v1.z / v2.z, v1.q / v2.q);}
__forceinline GSSoftVertexFP::Vector operator + (const GSSoftVertexFP::Vector& v, GSSoftVertexFP::Scalar s) {return GSSoftVertexFP::Vector(v.x + s, v.y + s, v.z + s, v.q + s);}
__forceinline GSSoftVertexFP::Vector operator - (const GSSoftVertexFP::Vector& v, GSSoftVertexFP::Scalar s) {return GSSoftVertexFP::Vector(v.x - s, v.y - s, v.z - s, v.q - s);}
__forceinline GSSoftVertexFP::Vector operator * (const GSSoftVertexFP::Vector& v, GSSoftVertexFP::Scalar s) {return GSSoftVertexFP::Vector(v.x * s, v.y * s, v.z * s, v.q * s);}
__forceinline GSSoftVertexFP::Vector operator / (const GSSoftVertexFP::Vector& v, GSSoftVertexFP::Scalar s) {return GSSoftVertexFP::Vector(v.x / s, v.y / s, v.z / s, v.q / s);}
#endif
__forceinline GSSoftVertexFP operator + (const GSSoftVertexFP& v1, const GSSoftVertexFP& v2)
{
GSSoftVertexFP v0;
v0.c = v1.c + v2.c;
v0.p = v1.p + v2.p;
v0.t = v1.t + v2.t;
return v0;
}
__forceinline GSSoftVertexFP operator - (const GSSoftVertexFP& v1, const GSSoftVertexFP& v2)
{
GSSoftVertexFP v0;
v0.c = v1.c - v2.c;
v0.p = v1.p - v2.p;
v0.t = v1.t - v2.t;
return v0;
}
__forceinline GSSoftVertexFP operator * (const GSSoftVertexFP& v, GSSoftVertexFP::Scalar s)
{
GSSoftVertexFP v0;
GSSoftVertexFP::Vector vs(s);
v0.c = v.c * vs;
v0.p = v.p * vs;
v0.t = v.t * vs;
return v0;
}
__forceinline GSSoftVertexFP operator / (const GSSoftVertexFP& v, GSSoftVertexFP::Scalar s)
{
GSSoftVertexFP v0;
GSSoftVertexFP::Vector vs(s);
v0.c = v.c / vs;
v0.p = v.p / vs;
v0.t = v.t / vs;
return v0;
}
| [
"zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84"
] | zerofrog@23c756db-88ba-2448-99d7-e6e4c676ec84 |
dcfd81c299c0ea698b5fb18756316c504c00d79e | f39ec2243a5569f432e63de073363296a71f75bc | /codec/encoder/core/src/svc_motion_estimate.cpp | 34a6350fc9406cee04cf2fd18fdef96d6c4791b0 | [
"BSD-2-Clause"
] | permissive | zhuling13/gitTest | 4afdcfba20f262cce0226d1c7122ed3906bf907e | 4f46f237bac33f647f04717c9cfeec2ba0db9a95 | refs/heads/master | 2021-01-14T11:07:27.289006 | 2014-06-18T07:55:13 | 2014-06-18T07:55:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 41,263 | cpp | /*!
* \copy
* Copyright (c) 2009-2013, Cisco Systems
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* \file svc motion estimate.c
*
* \brief Interfaces introduced in svc mb motion estimation
*
* \date 08/11/2009 Created
*
*************************************************************************************
*/
#include "cpu_core.h"
#include "ls_defines.h"
#include "svc_motion_estimate.h"
#include "wels_transpose_matrix.h"
namespace WelsSVCEnc {
const int32_t QStepx16ByQp[52] = { /* save QStep<<4 for int32_t */
10, 11, 13, 14, 16, 18, /* 0~5 */
20, 22, 26, 28, 32, 36, /* 6~11 */
40, 44, 52, 56, 64, 72, /* 12~17 */
80, 88, 104, 112, 128, 144, /* 18~23 */
160, 176, 208, 224, 256, 288, /* 24~29 */
320, 352, 416, 448, 512, 576, /* 30~35 */
640, 704, 832, 896, 1024, 1152, /* 36~41 */
1280, 1408, 1664, 1792, 2048, 2304, /* 42~47 */
2560, 2816, 3328, 3584 /* 48~51 */
};
static inline void UpdateMeResults (const SMVUnitXY ksBestMv, const uint32_t kiBestSadCost, uint8_t* pRef,
SWelsME* pMe) {
pMe->sMv = ksBestMv;
pMe->pRefMb = pRef;
pMe->uiSadCost = kiBestSadCost;
}
static inline void MeEndIntepelSearch (SWelsME* pMe) {
/* -> qpel mv */
pMe->sMv.iMvX <<= 2;
pMe->sMv.iMvY <<= 2;
pMe->uiSatdCost = pMe->uiSadCost;
}
void WelsInitMeFunc (SWelsFuncPtrList* pFuncList, uint32_t uiCpuFlag, bool bScreenContent) {
if (!bScreenContent) {
pFuncList->pfCheckDirectionalMv = CheckDirectionalMvFalse;
pFuncList->pfCalculateBlockFeatureOfFrame[0] =
pFuncList->pfCalculateBlockFeatureOfFrame[1] = NULL;
pFuncList->pfCalculateSingleBlockFeature[0] =
pFuncList->pfCalculateSingleBlockFeature[1] = NULL;
pFuncList->pfUpdateFMESwitch = UpdateFMESwitchNull;
} else {
pFuncList->pfCheckDirectionalMv = CheckDirectionalMv;
//for cross serarch
pFuncList->pfVerticalFullSearch = LineFullSearch_c;
pFuncList->pfHorizontalFullSearch = LineFullSearch_c;
#if defined (X86_ASM)
if (uiCpuFlag & WELS_CPU_SSE41) {
pFuncList->pfSampleSadHor8[0] = SampleSad8x8Hor8_sse41;
pFuncList->pfSampleSadHor8[1] = SampleSad16x16Hor8_sse41;
pFuncList->pfVerticalFullSearch = VerticalFullSearchUsingSSE41;
pFuncList->pfHorizontalFullSearch = HorizontalFullSearchUsingSSE41;
}
#endif
//for feature search
pFuncList->pfCalculateBlockFeatureOfFrame[0] = SumOf8x8BlockOfFrame_c;
pFuncList->pfCalculateBlockFeatureOfFrame[1] = SumOf16x16BlockOfFrame_c;
//TODO: it is possible to differentiate width that is times of 8, so as to accelerate the speed when width is times of 8?
pFuncList->pfCalculateSingleBlockFeature[0] = SumOf8x8SingleBlock_c;
pFuncList->pfCalculateSingleBlockFeature[1] = SumOf16x16SingleBlock_c;
pFuncList->pfUpdateFMESwitch = UpdateFMESwitchNull;
}
}
/*!
* \brief BL mb motion estimate search
*
* \param enc Wels encoder context
* \param pMe Wels me information
*
* \return NONE
*/
void WelsMotionEstimateSearch (SWelsFuncPtrList* pFuncList, void* pLplayer, void* pLpme, void* pLpslice) {
SDqLayer* pCurDqLayer = (SDqLayer*)pLplayer;
SWelsME* pMe = (SWelsME*)pLpme;
SSlice* pSlice = (SSlice*)pLpslice;
const int32_t kiStrideEnc = pCurDqLayer->iEncStride[0];
const int32_t kiStrideRef = pCurDqLayer->pRefPic->iLineSize[0];
// Step 1: Initial point prediction
if (!WelsMotionEstimateInitialPoint (pFuncList, pMe, pSlice, kiStrideEnc, kiStrideRef)) {
pFuncList->pfSearchMethod[pMe->uiBlockSize] (pFuncList, pMe, pSlice, kiStrideEnc, kiStrideRef);
MeEndIntepelSearch (pMe);
}
pFuncList->pfCalculateSatd (pFuncList->sSampleDealingFuncs.pfSampleSatd[pMe->uiBlockSize], pMe, kiStrideEnc,
kiStrideRef);
}
/*!
* \brief EL mb motion estimate initial point testing
*
* \param pix_pFuncList SSampleDealingFunc
* \param pMe Wels me information
* \param mv_range search range in motion estimate
* \param point the best match point in motion estimation
*
* \return NONE
*/
bool WelsMotionEstimateInitialPoint (SWelsFuncPtrList* pFuncList, SWelsME* pMe, SSlice* pSlice, int32_t iStrideEnc,
int32_t iStrideRef) {
PSampleSadSatdCostFunc pSad = pFuncList->sSampleDealingFuncs.pfSampleSad[pMe->uiBlockSize];
const uint16_t* kpMvdCost = pMe->pMvdCost;
uint8_t* const kpEncMb = pMe->pEncMb;
int16_t iMvc0, iMvc1;
int32_t iSadCost;
int32_t iBestSadCost;
uint8_t* pRefMb;
uint8_t* pFref2;
uint32_t i;
const uint32_t kuiMvcNum = pSlice->uiMvcNum;
const SMVUnitXY* kpMvcList = &pSlice->sMvc[0];
const SMVUnitXY ksMvStartMin = pSlice->sMvStartMin;
const SMVUnitXY ksMvStartMax = pSlice->sMvStartMax;
const SMVUnitXY ksMvp = pMe->sMvp;
SMVUnitXY sMv;
// Step 1: Initial point prediction
// init with sMvp
sMv.iMvX = WELS_CLIP3 ((2 + ksMvp.iMvX) >> 2, ksMvStartMin.iMvX, ksMvStartMax.iMvX);
sMv.iMvY = WELS_CLIP3 ((2 + ksMvp.iMvY) >> 2, ksMvStartMin.iMvY, ksMvStartMax.iMvY);
pRefMb = &pMe->pRefMb[sMv.iMvY * iStrideRef + sMv.iMvX];
iBestSadCost = pSad (kpEncMb, iStrideEnc, pRefMb, iStrideRef);
iBestSadCost += COST_MVD (kpMvdCost, ((sMv.iMvX) << 2) - ksMvp.iMvX, ((sMv.iMvY) << 2) - ksMvp.iMvY);
for (i = 0; i < kuiMvcNum; i++) {
//clipping here is essential since some pOut-of-range MVC may happen here (i.e., refer to baseMV)
iMvc0 = WELS_CLIP3 ((2 + kpMvcList[i].iMvX) >> 2, ksMvStartMin.iMvX, ksMvStartMax.iMvX);
iMvc1 = WELS_CLIP3 ((2 + kpMvcList[i].iMvY) >> 2, ksMvStartMin.iMvY, ksMvStartMax.iMvY);
if (((iMvc0 - sMv.iMvX) || (iMvc1 - sMv.iMvY))) {
pFref2 = &pMe->pRefMb[iMvc1 * iStrideRef + iMvc0];
iSadCost = pSad (kpEncMb, iStrideEnc, pFref2, iStrideRef) +
COST_MVD (kpMvdCost, (iMvc0 << 2) - ksMvp.iMvX, (iMvc1 << 2) - ksMvp.iMvY);
if (iSadCost < iBestSadCost) {
sMv.iMvX = iMvc0;
sMv.iMvY = iMvc1;
pRefMb = pFref2;
iBestSadCost = iSadCost;
}
}
}
if (pFuncList->pfCheckDirectionalMv
(pSad, pMe, ksMvStartMin, ksMvStartMax, iStrideEnc, iStrideRef, iSadCost)) {
sMv = pMe->sDirectionalMv;
pRefMb = &pMe->pColoRefMb[sMv.iMvY * iStrideRef + sMv.iMvX];
iBestSadCost = iSadCost;
}
UpdateMeResults (sMv, iBestSadCost, pRefMb, pMe);
if (iBestSadCost < static_cast<int32_t> (pMe->uSadPredISatd.uiSadPred)) {
//Initial point early Stop
MeEndIntepelSearch (pMe);
return true;
}
return false;
}
void CalculateSatdCost (PSampleSadSatdCostFunc pSatd, void* vpMe,
const int32_t kiEncStride, const int32_t kiRefStride) {
SWelsME* pMe = static_cast<SWelsME*> (vpMe);
pMe->uSadPredISatd.uiSatd = pSatd (pMe->pEncMb, kiEncStride, pMe->pRefMb, kiRefStride);
pMe->uiSatdCost = pMe->uSadPredISatd.uiSatd + COST_MVD (pMe->pMvdCost, pMe->sMv.iMvX - pMe->sMvp.iMvX,
pMe->sMv.iMvY - pMe->sMvp.iMvY);
}
void NotCalculateSatdCost (PSampleSadSatdCostFunc pSatd, void* vpMe,
const int32_t kiEncStride, const int32_t kiRefStride) {
}
/////////////////////////
// Diamond Search Basics
/////////////////////////
bool WelsMeSadCostSelect (int32_t* iSadCost, const uint16_t* kpMvdCost, int32_t* pBestCost, const int32_t kiDx,
const int32_t kiDy, int32_t* pIx, int32_t* pIy) {
int32_t iTempSadCost[4];
int32_t iInputSadCost = *pBestCost;
iTempSadCost[0] = iSadCost[0] + COST_MVD (kpMvdCost, kiDx, kiDy - 4);
iTempSadCost[1] = iSadCost[1] + COST_MVD (kpMvdCost, kiDx, kiDy + 4);
iTempSadCost[2] = iSadCost[2] + COST_MVD (kpMvdCost, kiDx - 4, kiDy);
iTempSadCost[3] = iSadCost[3] + COST_MVD (kpMvdCost, kiDx + 4, kiDy);
if (iTempSadCost[0] < *pBestCost) {
*pBestCost = iTempSadCost[0];
*pIx = 0;
*pIy = 1;
}
if (iTempSadCost[1] < *pBestCost) {
*pBestCost = iTempSadCost[1];
*pIx = 0;
*pIy = -1;
}
if (iTempSadCost[2] < *pBestCost) {
*pBestCost = iTempSadCost[2];
*pIx = 1;
*pIy = 0;
}
if (iTempSadCost[3] < *pBestCost) {
*pBestCost = iTempSadCost[3];
*pIx = -1;
*pIy = 0;
}
return (*pBestCost == iInputSadCost);
}
void WelsDiamondSearch (SWelsFuncPtrList* pFuncList, void* pLpme, void* pLpslice,
const int32_t kiStrideEnc, const int32_t kiStrideRef) {
SWelsME* pMe = (SWelsME*)pLpme;
PSample4SadCostFunc pSad = pFuncList->sSampleDealingFuncs.pfSample4Sad[pMe->uiBlockSize];
uint8_t* pFref = pMe->pRefMb;
uint8_t* const kpEncMb = pMe->pEncMb;
const uint16_t* kpMvdCost = pMe->pMvdCost;
int32_t iMvDx = ((pMe->sMv.iMvX) << 2) - pMe->sMvp.iMvX;
int32_t iMvDy = ((pMe->sMv.iMvY) << 2) - pMe->sMvp.iMvY;
uint8_t* pRefMb = pFref;
int32_t iBestCost = (pMe->uiSadCost);
int32_t iTimeThreshold = ITERATIVE_TIMES;
ENFORCE_STACK_ALIGN_1D (int32_t, iSadCosts, 4, 16)
while (iTimeThreshold--) {
pSad (kpEncMb, kiStrideEnc, pRefMb, kiStrideRef, &iSadCosts[0]);
int32_t iX, iY;
const bool kbIsBestCostWorse = WelsMeSadCostSelect (iSadCosts, kpMvdCost, &iBestCost, iMvDx, iMvDy, &iX, &iY);
if (kbIsBestCostWorse)
break;
iMvDx -= iX << 2 ;
iMvDy -= iY << 2 ;
pRefMb -= (iX + iY * kiStrideRef);
}
/* integer-pel mv */
pMe->sMv.iMvX = (iMvDx + pMe->sMvp.iMvX) >> 2;
pMe->sMv.iMvY = (iMvDy + pMe->sMvp.iMvY) >> 2;
pMe->uiSatdCost = pMe->uiSadCost = (iBestCost);
pMe->pRefMb = pRefMb;
}
/////////////////////////
// DirectionalMv Basics
/////////////////////////
bool CheckDirectionalMv (PSampleSadSatdCostFunc pSad, void* vpMe,
const SMVUnitXY ksMinMv, const SMVUnitXY ksMaxMv, const int32_t kiEncStride, const int32_t kiRefStride,
int32_t& iBestSadCost) {
SWelsME* pMe = static_cast<SWelsME*> (vpMe);
const int16_t kiMvX = pMe->sDirectionalMv.iMvX;
const int16_t kiMvY = pMe->sDirectionalMv.iMvY;
//Check MV from scrolling detection
if ((BLOCK_16x16 != pMe->uiBlockSize) //scrolled_MV with P16x16 is checked SKIP checking function
&& (kiMvX | kiMvY) //(0,0) checked in ordinary initial point checking
&& CheckMvInRange (pMe->sDirectionalMv, ksMinMv, ksMaxMv)) {
uint8_t* pRef = &pMe->pColoRefMb[kiMvY * kiRefStride + kiMvX];
uint32_t uiCurrentSadCost = pSad (pMe->pEncMb, kiEncStride, pRef, kiRefStride) +
COST_MVD (pMe->pMvdCost, (kiMvX << 2) - pMe->sMvp.iMvX, (kiMvY << 2) - pMe->sMvp.iMvY);
if (uiCurrentSadCost < pMe->uiSadCost) {
iBestSadCost = uiCurrentSadCost;
return true;
}
}
return false;
}
bool CheckDirectionalMvFalse (PSampleSadSatdCostFunc pSad, void* vpMe,
const SMVUnitXY ksMinMv, const SMVUnitXY ksMaxMv, const int32_t kiEncStride, const int32_t kiRefStride,
int32_t& iBestSadCost) {
return false;
}
/////////////////////////
// Cross Search Basics
/////////////////////////
#if defined (X86_ASM)
void CalcMvdCostx8_c (uint16_t* pMvdCost, const int32_t kiStartMv, uint16_t* pMvdTable, const uint16_t kiFixedCost) {
uint16_t* pBaseCost = pMvdCost;
const int32_t kiOffset = (kiStartMv << 2);
uint16_t* pMvd = pMvdTable + kiOffset;
for (int32_t i = 0; i < 8; ++ i) {
pBaseCost[i] = ((*pMvd) + kiFixedCost);
pMvd += 4;
}
}
void VerticalFullSearchUsingSSE41 (SWelsFuncPtrList* pFuncList, SWelsME* pMe,
uint16_t* pMvdTable, const int32_t kiFixedMvd,
const int32_t kiEncStride, const int32_t kiRefStride,
const int32_t kiMinPos, const int32_t kiMaxPos,
const bool bVerticalSearch) {
uint8_t* kpEncMb = pMe->pEncMb;
const int32_t kiCurMeBlockPix = pMe->iCurMeBlockPixY;
uint8_t* pRef = &pMe->pColoRefMb[ (kiMinPos - kiCurMeBlockPix) * kiRefStride];
const int32_t kIsBlock16x16 = pMe->uiBlockSize == BLOCK_16x16;
const int32_t kiEdgeBlocks = kIsBlock16x16 ? 16 : 8;
PSampleSadHor8Func pSampleSadHor8 = pFuncList->pfSampleSadHor8[kIsBlock16x16];
PSampleSadSatdCostFunc pSad = pFuncList->sSampleDealingFuncs.pfSampleSad[pMe->uiBlockSize];
PTransposeMatrixBlockFunc TransposeMatrixBlock = kIsBlock16x16 ? TransposeMatrixBlock16x16_sse2 :
TransposeMatrixBlock8x8_mmx;
PTransposeMatrixBlocksFunc TransposeMatrixBlocks = kIsBlock16x16 ? TransposeMatrixBlocksx16_sse2 :
TransposeMatrixBlocksx8_mmx;
const int32_t kiDiff = kiMaxPos - kiMinPos;
const int32_t kiRowNum = WELS_ALIGN ((kiDiff - kiEdgeBlocks + 1), kiEdgeBlocks);
const int32_t kiBlocksNum = kIsBlock16x16 ? (kiRowNum >> 4) : (kiRowNum >> 3);
int32_t iCountLoop8 = (kiRowNum - kiEdgeBlocks) >> 3;
const int32_t kiRemainingVectors = kiDiff - (iCountLoop8 << 3);
const int32_t kiMatrixStride = MAX_VERTICAL_MV_RANGE;
ENFORCE_STACK_ALIGN_2D (uint8_t, uiMatrixRef, 16, kiMatrixStride, 16); // transpose matrix result for ref
ENFORCE_STACK_ALIGN_2D (uint8_t, uiMatrixEnc, 16, 16, 16); // transpose matrix result for enc
assert (kiRowNum <= kiMatrixStride); // make sure effective memory
TransposeMatrixBlock (&uiMatrixEnc[0][0], 16, kpEncMb, kiEncStride);
TransposeMatrixBlocks (&uiMatrixRef[0][0], kiMatrixStride, pRef, kiRefStride, kiBlocksNum);
ENFORCE_STACK_ALIGN_1D (uint16_t, uiBaseCost, 8, 16);
int32_t iTargetPos = kiMinPos;
int16_t iBestPos = pMe->sMv.iMvX;
uint32_t uiBestCost = pMe->uiSadCost;
uint32_t uiCostMin;
int32_t iIndexMinPos;
kpEncMb = &uiMatrixEnc[0][0];
pRef = &uiMatrixRef[0][0];
while (iCountLoop8 > 0) {
CalcMvdCostx8_c (uiBaseCost, iTargetPos, pMvdTable, kiFixedMvd);
uiCostMin = pSampleSadHor8 (kpEncMb, 16, pRef, kiMatrixStride, uiBaseCost, &iIndexMinPos);
if (uiCostMin < uiBestCost) {
uiBestCost = uiCostMin;
iBestPos = iTargetPos + iIndexMinPos;
}
iTargetPos += 8;
pRef += 8;
-- iCountLoop8;
}
if (kiRemainingVectors > 0) {
kpEncMb = pMe->pEncMb;
pRef = &pMe->pColoRefMb[ (iTargetPos - kiCurMeBlockPix) * kiRefStride];
while (iTargetPos < kiMaxPos) {
const uint16_t pMvdCost = pMvdTable[iTargetPos << 2];
uint32_t uiSadCost = pSad (kpEncMb, kiEncStride, pRef, kiRefStride) + (kiFixedMvd + pMvdCost);
if (uiSadCost < uiBestCost) {
uiBestCost = uiSadCost;
iBestPos = iTargetPos;
}
pRef += kiRefStride;
++iTargetPos;
}
}
if (uiBestCost < pMe->uiSadCost) {
SMVUnitXY sBestMv;
sBestMv.iMvX = 0;
sBestMv.iMvY = iBestPos - kiCurMeBlockPix;
UpdateMeResults (sBestMv, uiBestCost, &pMe->pColoRefMb[sBestMv.iMvY * kiRefStride], pMe);
}
}
void HorizontalFullSearchUsingSSE41 (SWelsFuncPtrList* pFuncList, SWelsME* pMe,
uint16_t* pMvdTable, const int32_t kiFixedMvd,
const int32_t kiEncStride, const int32_t kiRefStride,
const int32_t kiMinPos, const int32_t kiMaxPos,
const bool bVerticalSearch) {
uint8_t* kpEncMb = pMe->pEncMb;
const int32_t kiCurMeBlockPix = pMe->iCurMeBlockPixX;
uint8_t* pRef = &pMe->pColoRefMb[kiMinPos - kiCurMeBlockPix];
const int32_t kIsBlock16x16 = pMe->uiBlockSize == BLOCK_16x16;
PSampleSadHor8Func pSampleSadHor8 = pFuncList->pfSampleSadHor8[kIsBlock16x16];
PSampleSadSatdCostFunc pSad = pFuncList->sSampleDealingFuncs.pfSampleSad[pMe->uiBlockSize];
ENFORCE_STACK_ALIGN_1D (uint16_t, uiBaseCost, 8, 16);
const int32_t kiNumVector = kiMaxPos - kiMinPos;
int32_t iCountLoop8 = kiNumVector >> 3;
const int32_t kiRemainingLoop8 = kiNumVector & 7;
int32_t iTargetPos = kiMinPos;
int16_t iBestPos = pMe->sMv.iMvX;
uint32_t uiBestCost = pMe->uiSadCost;
uint32_t uiCostMin;
int32_t iIndexMinPos;
while (iCountLoop8 > 0) {
CalcMvdCostx8_c (uiBaseCost, iTargetPos, pMvdTable, kiFixedMvd);
uiCostMin = pSampleSadHor8 (kpEncMb, kiEncStride, pRef, kiRefStride, uiBaseCost, &iIndexMinPos);
if (uiCostMin < uiBestCost) {
uiBestCost = uiCostMin;
iBestPos = iTargetPos + iIndexMinPos;
}
iTargetPos += 8;
pRef += 8;
-- iCountLoop8;
}
if (kiRemainingLoop8 > 0) {
while (iTargetPos < kiMaxPos) {
const uint16_t pMvdCost = pMvdTable[iTargetPos << 2];
uint32_t uiSadCost = pSad (kpEncMb, kiEncStride, pRef, kiRefStride) + (kiFixedMvd + pMvdCost);
if (uiSadCost < uiBestCost) {
uiBestCost = uiSadCost;
iBestPos = iTargetPos;
}
++pRef;
++iTargetPos;
}
}
if (uiBestCost < pMe->uiSadCost) {
SMVUnitXY sBestMv;
sBestMv.iMvX = iBestPos - kiCurMeBlockPix;
sBestMv.iMvY = 0;
UpdateMeResults (sBestMv, uiBestCost, &pMe->pColoRefMb[sBestMv.iMvY], pMe);
}
}
#endif
void LineFullSearch_c (SWelsFuncPtrList* pFuncList, SWelsME* pMe,
uint16_t* pMvdTable, const int32_t kiFixedMvd,
const int32_t kiEncStride, const int32_t kiRefStride,
const int32_t kiMinPos, const int32_t kiMaxPos,
const bool bVerticalSearch) {
PSampleSadSatdCostFunc pSad = pFuncList->sSampleDealingFuncs.pfSampleSad[pMe->uiBlockSize];
const int32_t kiCurMeBlockPix = bVerticalSearch ? pMe->iCurMeBlockPixY : pMe->iCurMeBlockPixX;
const int32_t kiStride = bVerticalSearch ? kiRefStride : 1;
uint8_t* pRef = &pMe->pColoRefMb[ (kiMinPos - kiCurMeBlockPix) * kiStride];
uint16_t* pMvdCost = & (pMvdTable[kiMinPos << 2]);
uint32_t uiBestCost = 0xFFFFFFFF;
int32_t iBestPos = 0;
for (int32_t iTargetPos = kiMinPos; iTargetPos < kiMaxPos; ++ iTargetPos) {
uint8_t* const kpEncMb = pMe->pEncMb;
uint32_t uiSadCost = pSad (kpEncMb, kiEncStride, pRef, kiRefStride) + (kiFixedMvd + *pMvdCost);
if (uiSadCost < uiBestCost) {
uiBestCost = uiSadCost;
iBestPos = iTargetPos;
}
pRef += kiStride;
pMvdCost += 4;
}
if (uiBestCost < pMe->uiSadCost) {
SMVUnitXY sBestMv;
sBestMv.iMvX = bVerticalSearch ? 0 : (iBestPos - kiCurMeBlockPix);
sBestMv.iMvY = bVerticalSearch ? (iBestPos - kiCurMeBlockPix) : 0;
UpdateMeResults (sBestMv, uiBestCost, &pMe->pColoRefMb[sBestMv.iMvY * kiStride], pMe);
}
}
void WelsMotionCrossSearch (SWelsFuncPtrList* pFuncList, SWelsME* pMe,
const SSlice* pSlice, const int32_t kiEncStride, const int32_t kiRefStride) {
PLineFullSearchFunc pfVerticalFullSearchFunc = pFuncList->pfVerticalFullSearch;
PLineFullSearchFunc pfHorizontalFullSearchFunc = pFuncList->pfHorizontalFullSearch;
const int32_t iCurMeBlockPixX = pMe->iCurMeBlockPixX;
const int32_t iCurMeBlockQpelPixX = ((iCurMeBlockPixX) << 2);
const int32_t iCurMeBlockPixY = pMe->iCurMeBlockPixY;
const int32_t iCurMeBlockQpelPixY = ((iCurMeBlockPixY) << 2);
uint16_t* pMvdCostX = pMe->pMvdCost - iCurMeBlockQpelPixX - pMe->sMvp.iMvX;//do the offset here instead of in the search
uint16_t* pMvdCostY = pMe->pMvdCost - iCurMeBlockQpelPixY - pMe->sMvp.iMvY;//do the offset here instead of in the search
//vertical search
pfVerticalFullSearchFunc (pFuncList, pMe,
pMvdCostY, pMvdCostX[ iCurMeBlockQpelPixX ],
kiEncStride, kiRefStride,
iCurMeBlockPixY + pSlice->sMvStartMin.iMvY,
iCurMeBlockPixY + pSlice->sMvStartMax.iMvY, true);
//horizontal search
if (pMe->uiSadCost >= pMe->uiSadCostThreshold) {
pfHorizontalFullSearchFunc (pFuncList, pMe,
pMvdCostX, pMvdCostY[ iCurMeBlockQpelPixY ],
kiEncStride, kiRefStride,
iCurMeBlockPixX + pSlice->sMvStartMin.iMvX,
iCurMeBlockPixX + pSlice->sMvStartMax.iMvX,
false);
}
}
/////////////////////////
// Feature Search Basics
/////////////////////////
//memory related
int32_t RequestFeatureSearchPreparation (CMemoryAlign* pMa, const int32_t kiFrameWidth, const int32_t kiFrameHeight,
const int32_t iNeedFeatureStorage,
SFeatureSearchPreparation* pFeatureSearchPreparation) {
const int32_t kiFeatureStrategyIndex = iNeedFeatureStorage >> 16;
const bool bFme8x8 = ((iNeedFeatureStorage & 0x0000FF & ME_FME) == ME_FME);
const int32_t kiMarginSize = bFme8x8 ? 8 : 16;
const int32_t kiFrameSize = (kiFrameWidth - kiMarginSize) * (kiFrameHeight - kiMarginSize);
int32_t iListOfFeatureOfBlock;
if (0 == kiFeatureStrategyIndex) {
iListOfFeatureOfBlock = sizeof (uint16_t) * kiFrameSize;
} else {
iListOfFeatureOfBlock = sizeof (uint16_t) * kiFrameSize +
(kiFrameWidth - kiMarginSize) * sizeof (uint32_t) + kiFrameWidth * 8 * sizeof (uint8_t);
}
pFeatureSearchPreparation->pFeatureOfBlock =
(uint16_t*)pMa->WelsMalloc (iListOfFeatureOfBlock, "pFeatureOfBlock");
WELS_VERIFY_RETURN_IF (ENC_RETURN_MEMALLOCERR, NULL == (pFeatureSearchPreparation->pFeatureOfBlock))
pFeatureSearchPreparation->uiFeatureStrategyIndex = kiFeatureStrategyIndex;
pFeatureSearchPreparation->bFMESwitchFlag = true;
pFeatureSearchPreparation->uiFMEGoodFrameCount = FMESWITCH_DEFAULT_GOODFRAME_NUM;
pFeatureSearchPreparation->iHighFreMbCount = 0;
return ENC_RETURN_SUCCESS;
}
int32_t ReleaseFeatureSearchPreparation (CMemoryAlign* pMa, uint16_t*& pFeatureOfBlock) {
if (pMa && pFeatureOfBlock) {
pMa->WelsFree (pFeatureOfBlock, "pFeatureOfBlock");
pFeatureOfBlock = NULL;
return ENC_RETURN_SUCCESS;
}
return ENC_RETURN_UNEXPECTED;
}
int32_t RequestScreenBlockFeatureStorage (CMemoryAlign* pMa, const int32_t kiFrameWidth, const int32_t kiFrameHeight,
const int32_t iNeedFeatureStorage,
SScreenBlockFeatureStorage* pScreenBlockFeatureStorage) {
const int32_t kiFeatureStrategyIndex = iNeedFeatureStorage >> 16;
const int32_t kiMe8x8FME = iNeedFeatureStorage & 0x0000FF & ME_FME;
const int32_t kiMe16x16FME = ((iNeedFeatureStorage & 0x00FF00) >> 8) & ME_FME;
if ((kiMe8x8FME == ME_FME) && (kiMe16x16FME == ME_FME)) {
return ENC_RETURN_UNSUPPORTED_PARA;
//the following memory allocation cannot support when FME at both size
}
const bool bIsBlock8x8 = (kiMe8x8FME == ME_FME);
const int32_t kiMarginSize = bIsBlock8x8 ? 8 : 16;
const int32_t kiFrameSize = (kiFrameWidth - kiMarginSize) * (kiFrameHeight - kiMarginSize);
const int32_t kiListSize = (0 == kiFeatureStrategyIndex) ? (bIsBlock8x8 ? LIST_SIZE_SUM_8x8 : LIST_SIZE_SUM_16x16) :
256;
pScreenBlockFeatureStorage->pTimesOfFeatureValue = (uint32_t*)pMa->WelsMalloc (kiListSize * sizeof (uint32_t),
"pScreenBlockFeatureStorage->pTimesOfFeatureValue");
WELS_VERIFY_RETURN_IF (ENC_RETURN_MEMALLOCERR, NULL == pScreenBlockFeatureStorage->pTimesOfFeatureValue)
pScreenBlockFeatureStorage->pLocationOfFeature = (uint16_t**)pMa->WelsMalloc (kiListSize * sizeof (uint16_t*),
"pScreenBlockFeatureStorage->pLocationOfFeature");
WELS_VERIFY_RETURN_IF (ENC_RETURN_MEMALLOCERR, NULL == pScreenBlockFeatureStorage->pLocationOfFeature)
pScreenBlockFeatureStorage->pLocationPointer = (uint16_t*)pMa->WelsMalloc (2 * kiFrameSize * sizeof (uint16_t),
"pScreenBlockFeatureStorage->pLocationPointer");
WELS_VERIFY_RETURN_IF (ENC_RETURN_MEMALLOCERR, NULL == pScreenBlockFeatureStorage->pLocationPointer)
pScreenBlockFeatureStorage->pFeatureOfBlockPointer = NULL;
pScreenBlockFeatureStorage->iIs16x16 = !bIsBlock8x8;
pScreenBlockFeatureStorage->uiFeatureStrategyIndex = kiFeatureStrategyIndex;
pScreenBlockFeatureStorage->iActualListSize = kiListSize;
memset (pScreenBlockFeatureStorage->uiSadCostThreshold, UINT_MAX, BLOCK_SIZE_ALL * sizeof (uint32_t));
pScreenBlockFeatureStorage->bRefBlockFeatureCalculated = false;
return ENC_RETURN_SUCCESS;
}
int32_t ReleaseScreenBlockFeatureStorage (CMemoryAlign* pMa, SScreenBlockFeatureStorage* pScreenBlockFeatureStorage) {
if (pMa && pScreenBlockFeatureStorage) {
if (pScreenBlockFeatureStorage->pTimesOfFeatureValue) {
pMa->WelsFree (pScreenBlockFeatureStorage->pTimesOfFeatureValue, "pScreenBlockFeatureStorage->pTimesOfFeatureValue");
pScreenBlockFeatureStorage->pTimesOfFeatureValue = NULL;
}
if (pScreenBlockFeatureStorage->pLocationOfFeature) {
pMa->WelsFree (pScreenBlockFeatureStorage->pLocationOfFeature, "pScreenBlockFeatureStorage->pLocationOfFeature");
pScreenBlockFeatureStorage->pLocationOfFeature = NULL;
}
if (pScreenBlockFeatureStorage->pLocationPointer) {
pMa->WelsFree (pScreenBlockFeatureStorage->pLocationPointer, "pScreenBlockFeatureStorage->pLocationPointer");
pScreenBlockFeatureStorage->pLocationPointer = NULL;
}
return ENC_RETURN_SUCCESS;
}
return ENC_RETURN_UNEXPECTED;
}
//preprocess related
int32_t SumOf8x8SingleBlock_c (uint8_t* pRef, const int32_t kiRefStride) {
int32_t iSum = 0, i;
for (i = 0; i < 8; i++) {
iSum += pRef[0] + pRef[1] + pRef[2] + pRef[3];
iSum += pRef[4] + pRef[5] + pRef[6] + pRef[7];
pRef += kiRefStride;
}
return iSum;
}
int32_t SumOf16x16SingleBlock_c (uint8_t* pRef, const int32_t kiRefStride) {
int32_t iSum = 0, i;
for (i = 0; i < 16; i++) {
iSum += pRef[0] + pRef[1] + pRef[2] + pRef[3];
iSum += pRef[4] + pRef[5] + pRef[6] + pRef[7];
iSum += pRef[8] + pRef[9] + pRef[10] + pRef[11];
iSum += pRef[12] + pRef[13] + pRef[14] + pRef[15];
pRef += kiRefStride;
}
return iSum;
}
void SumOf8x8BlockOfFrame_c (uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight,
const int32_t kiRefStride,
uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]) {
int32_t x, y;
uint8_t* pRef;
uint16_t* pBuffer;
int32_t iSum;
for (y = 0; y < kiHeight; y++) {
pRef = pRefPicture + kiRefStride * y;
pBuffer = pFeatureOfBlock + kiWidth * y;
for (x = 0; x < kiWidth; x++) {
iSum = SumOf8x8SingleBlock_c (pRef + x, kiRefStride);
pBuffer[x] = iSum;
pTimesOfFeatureValue[iSum]++;
}
}
}
void SumOf16x16BlockOfFrame_c (uint8_t* pRefPicture, const int32_t kiWidth, const int32_t kiHeight,
const int32_t kiRefStride,
uint16_t* pFeatureOfBlock, uint32_t pTimesOfFeatureValue[]) {
//TODO: this is similar to SumOf8x8BlockOfFrame_c expect the calling of single block func, refactor-able?
int32_t x, y;
uint8_t* pRef;
uint16_t* pBuffer;
int32_t iSum;
for (y = 0; y < kiHeight; y++) {
pRef = pRefPicture + kiRefStride * y;
pBuffer = pFeatureOfBlock + kiWidth * y;
for (x = 0; x < kiWidth; x++) {
iSum = SumOf16x16SingleBlock_c (pRef + x, kiRefStride);
pBuffer[x] = iSum;
pTimesOfFeatureValue[iSum]++;
}
}
}
void InitializeHashforFeature_c (uint32_t* pTimesOfFeatureValue, uint16_t* pBuf, const int32_t kiListSize,
uint16_t** pLocationOfFeature, uint16_t** pFeatureValuePointerList) {
//assign location pointer
uint16_t* pBufPos = pBuf;
for (int32_t i = 0 ; i < kiListSize; ++i) {
pLocationOfFeature[i] =
pFeatureValuePointerList[i] = pBufPos;
pBufPos += (pTimesOfFeatureValue[i] << 1);
}
}
void FillQpelLocationByFeatureValue_c (uint16_t* pFeatureOfBlock, const int32_t kiWidth, const int32_t kiHeight,
uint16_t** pFeatureValuePointerList) {
//assign each pixel's position
uint16_t* pSrcPointer = pFeatureOfBlock;
int32_t iQpelY = 0;
for (int32_t y = 0; y < kiHeight; y++) {
for (int32_t x = 0; x < kiWidth; x++) {
uint16_t uiFeature = pSrcPointer[x];
ST32 (&pFeatureValuePointerList[uiFeature][0], ((iQpelY << 16) | (x << 2)));
pFeatureValuePointerList[uiFeature] += 2;
}
iQpelY += 4;
pSrcPointer += kiWidth;
}
}
void CalculateFeatureOfBlock (SWelsFuncPtrList* pFunc, SPicture* pRef,
SScreenBlockFeatureStorage* pScreenBlockFeatureStorage) {
uint16_t* pFeatureOfBlock = pScreenBlockFeatureStorage->pFeatureOfBlockPointer;
uint32_t* pTimesOfFeatureValue = pScreenBlockFeatureStorage->pTimesOfFeatureValue;
uint16_t** pLocationOfFeature = pScreenBlockFeatureStorage->pLocationOfFeature;
uint16_t* pBuf = pScreenBlockFeatureStorage->pLocationPointer;
uint8_t* pRefData = pRef->pData[0];
const int32_t iRefStride = pRef->iLineSize[0];
int32_t iIs16x16 = pScreenBlockFeatureStorage->iIs16x16;
const int32_t iEdgeDiscard = (iIs16x16 ? 16 : 8); //this is to save complexity of padding on pRef
const int32_t iWidth = pRef->iWidthInPixel - iEdgeDiscard;
const int32_t kiHeight = pRef->iHeightInPixel - iEdgeDiscard;
const int32_t kiActualListSize = pScreenBlockFeatureStorage->iActualListSize;
uint16_t* pFeatureValuePointerList[WELS_MAX (LIST_SIZE_SUM_16x16, LIST_SIZE_MSE_16x16)] = {0};
memset (pTimesOfFeatureValue, 0, sizeof (int32_t)*kiActualListSize);
(pFunc->pfCalculateBlockFeatureOfFrame[iIs16x16]) (pRefData, iWidth, kiHeight, iRefStride, pFeatureOfBlock,
pTimesOfFeatureValue);
//assign pLocationOfFeature pointer
InitializeHashforFeature_c (pTimesOfFeatureValue, pBuf, kiActualListSize,
pLocationOfFeature, pFeatureValuePointerList);
//assign each pixel's pLocationOfFeature
FillQpelLocationByFeatureValue_c (pFeatureOfBlock, iWidth, kiHeight, pFeatureValuePointerList);
}
void PerformFMEPreprocess (SWelsFuncPtrList* pFunc, SPicture* pRef, uint16_t* pFeatureOfBlock,
SScreenBlockFeatureStorage* pScreenBlockFeatureStorage) {
pScreenBlockFeatureStorage->pFeatureOfBlockPointer = pFeatureOfBlock;
CalculateFeatureOfBlock (pFunc, pRef, pScreenBlockFeatureStorage);
pScreenBlockFeatureStorage->bRefBlockFeatureCalculated = true;
uint32_t uiRefPictureAvgQstepx16 = QStepx16ByQp[WelsMedian (0, pRef->iFrameAverageQp, 51)];
uint32_t uiSadCostThreshold16x16 = ((30 * (uiRefPictureAvgQstepx16 + 160)) >> 3);
pScreenBlockFeatureStorage->uiSadCostThreshold[BLOCK_16x16] = uiSadCostThreshold16x16;
pScreenBlockFeatureStorage->uiSadCostThreshold[BLOCK_8x8] = (uiSadCostThreshold16x16 >> 2);
pScreenBlockFeatureStorage->uiSadCostThreshold[BLOCK_16x8]
= pScreenBlockFeatureStorage->uiSadCostThreshold[BLOCK_8x16]
= pScreenBlockFeatureStorage->uiSadCostThreshold[BLOCK_4x4] = UINT_MAX;
}
//search related
void SetFeatureSearchIn (SWelsFuncPtrList* pFunc, const SWelsME& sMe,
const SSlice* pSlice, SScreenBlockFeatureStorage* pRefFeatureStorage,
const int32_t kiEncStride, const int32_t kiRefStride,
SFeatureSearchIn* pFeatureSearchIn) {
pFeatureSearchIn->pSad = pFunc->sSampleDealingFuncs.pfSampleSad[sMe.uiBlockSize];
pFeatureSearchIn->iFeatureOfCurrent = pFunc->pfCalculateSingleBlockFeature[BLOCK_16x16 == sMe.uiBlockSize] (sMe.pEncMb,
kiEncStride);
pFeatureSearchIn->pEnc = sMe.pEncMb;
pFeatureSearchIn->pColoRef = sMe.pColoRefMb;
pFeatureSearchIn->iEncStride = kiEncStride;
pFeatureSearchIn->iRefStride = kiRefStride;
pFeatureSearchIn->uiSadCostThresh = sMe.uiSadCostThreshold;
pFeatureSearchIn->iCurPixX = sMe.iCurMeBlockPixX;
pFeatureSearchIn->iCurPixXQpel = (pFeatureSearchIn->iCurPixX << 2);
pFeatureSearchIn->iCurPixY = sMe.iCurMeBlockPixY;
pFeatureSearchIn->iCurPixYQpel = (pFeatureSearchIn->iCurPixY << 2);
pFeatureSearchIn->pTimesOfFeature = pRefFeatureStorage->pTimesOfFeatureValue;
pFeatureSearchIn->pQpelLocationOfFeature = pRefFeatureStorage->pLocationOfFeature;
pFeatureSearchIn->pMvdCostX = sMe.pMvdCost - pFeatureSearchIn->iCurPixXQpel - sMe.sMvp.iMvX;
pFeatureSearchIn->pMvdCostY = sMe.pMvdCost - pFeatureSearchIn->iCurPixYQpel - sMe.sMvp.iMvY;
pFeatureSearchIn->iMinQpelX = pFeatureSearchIn->iCurPixXQpel + ((pSlice->sMvStartMin.iMvX) << 2);
pFeatureSearchIn->iMinQpelY = pFeatureSearchIn->iCurPixYQpel + ((pSlice->sMvStartMin.iMvY) << 2);
pFeatureSearchIn->iMaxQpelX = pFeatureSearchIn->iCurPixXQpel + ((pSlice->sMvStartMax.iMvX) << 2);
pFeatureSearchIn->iMaxQpelY = pFeatureSearchIn->iCurPixYQpel + ((pSlice->sMvStartMax.iMvY) << 2);
}
void SaveFeatureSearchOut (const SMVUnitXY sBestMv, const uint32_t uiBestSadCost, uint8_t* pRef,
SFeatureSearchOut* pFeatureSearchOut) {
pFeatureSearchOut->sBestMv = sBestMv;
pFeatureSearchOut->uiBestSadCost = uiBestSadCost;
pFeatureSearchOut->pBestRef = pRef;
}
bool FeatureSearchOne (SFeatureSearchIn& sFeatureSearchIn, const int32_t iFeatureDifference,
const uint32_t kuiExpectedSearchTimes,
SFeatureSearchOut* pFeatureSearchOut) {
const int32_t iFeatureOfRef = (sFeatureSearchIn.iFeatureOfCurrent + iFeatureDifference);
if (iFeatureOfRef < 0 || iFeatureOfRef >= LIST_SIZE)
return true;
PSampleSadSatdCostFunc pSad = sFeatureSearchIn.pSad;
uint8_t* pEnc = sFeatureSearchIn.pEnc;
uint8_t* pColoRef = sFeatureSearchIn.pColoRef;
const int32_t iEncStride = sFeatureSearchIn.iEncStride;
const int32_t iRefStride = sFeatureSearchIn.iRefStride;
const uint16_t uiSadCostThresh = sFeatureSearchIn.uiSadCostThresh;
const int32_t iCurPixX = sFeatureSearchIn.iCurPixX;
const int32_t iCurPixY = sFeatureSearchIn.iCurPixY;
const int32_t iCurPixXQpel = sFeatureSearchIn.iCurPixXQpel;
const int32_t iCurPixYQpel = sFeatureSearchIn.iCurPixYQpel;
const int32_t iMinQpelX = sFeatureSearchIn.iMinQpelX;
const int32_t iMinQpelY = sFeatureSearchIn.iMinQpelY;
const int32_t iMaxQpelX = sFeatureSearchIn.iMaxQpelX;
const int32_t iMaxQpelY = sFeatureSearchIn.iMaxQpelY;
const int32_t iSearchTimes = WELS_MIN (sFeatureSearchIn.pTimesOfFeature[iFeatureOfRef], kuiExpectedSearchTimes);
const int32_t iSearchTimesx2 = (iSearchTimes << 1);
const uint16_t* pQpelPosition = sFeatureSearchIn.pQpelLocationOfFeature[iFeatureOfRef];
SMVUnitXY sBestMv;
uint32_t uiBestCost, uiTmpCost;
uint8_t* pBestRef, *pCurRef;
int32_t iQpelX, iQpelY;
int32_t iIntepelX, iIntepelY;
int32_t i;
sBestMv.iMvX = pFeatureSearchOut->sBestMv.iMvX;
sBestMv.iMvY = pFeatureSearchOut->sBestMv.iMvY;
uiBestCost = pFeatureSearchOut->uiBestSadCost;
pBestRef = pFeatureSearchOut->pBestRef;
for (i = 0; i < iSearchTimesx2; i += 2) {
iQpelX = pQpelPosition[i];
iQpelY = pQpelPosition[i + 1];
if ((iQpelX > iMaxQpelX) || (iQpelX < iMinQpelX)
|| (iQpelY > iMaxQpelY) || (iQpelY < iMinQpelY)
|| (iQpelX == iCurPixXQpel) || (iQpelY == iCurPixYQpel))
continue;
uiTmpCost = sFeatureSearchIn.pMvdCostX[ iQpelX ] + sFeatureSearchIn.pMvdCostY[ iQpelY ];
if (uiTmpCost + iFeatureDifference >= uiBestCost)
continue;
iIntepelX = (iQpelX >> 2) - iCurPixX;
iIntepelY = (iQpelY >> 2) - iCurPixY;
pCurRef = &pColoRef[iIntepelX + iIntepelY * iRefStride];
uiTmpCost += pSad (pEnc, iEncStride, pCurRef, iRefStride);
if (uiTmpCost < uiBestCost) {
sBestMv.iMvX = iIntepelX;
sBestMv.iMvY = iIntepelY;
uiBestCost = uiTmpCost;
pBestRef = pCurRef;
if (uiBestCost < uiSadCostThresh)
break;
}
}
SaveFeatureSearchOut (sBestMv, uiBestCost, pBestRef, pFeatureSearchOut);
return (i < iSearchTimesx2);
}
void MotionEstimateFeatureFullSearch (SFeatureSearchIn& sFeatureSearchIn,
const uint32_t kuiMaxSearchPoint,
SWelsME* pMe) {
SFeatureSearchOut sFeatureSearchOut = { { 0 } };//TODO: this can be refactored and removed
sFeatureSearchOut.uiBestSadCost = pMe->uiSadCost;
sFeatureSearchOut.sBestMv = pMe->sMv;
sFeatureSearchOut.pBestRef = pMe->pRefMb;
int32_t iFeatureDifference = 0;//TODO: change it according to computational-complexity setting when needed
FeatureSearchOne (sFeatureSearchIn, iFeatureDifference, kuiMaxSearchPoint, &sFeatureSearchOut);
if (sFeatureSearchOut.uiBestSadCost < pMe->uiSadCost) { //TODO: this may be refactored and removed
UpdateMeResults (sFeatureSearchOut.sBestMv,
sFeatureSearchOut.uiBestSadCost, sFeatureSearchOut.pBestRef,
pMe);
}
}
//switch related
static uint32_t CountFMECostDown (const SDqLayer* pCurLayer) {
uint32_t uiCostDownSum = 0;
const int32_t kiSliceCount = GetCurrentSliceNum (pCurLayer->pSliceEncCtx);
if (kiSliceCount >= 1) {
int32_t iSliceIndex = 0;
SSlice* pSlice = &pCurLayer->sLayerInfo.pSliceInLayer[iSliceIndex];
while (iSliceIndex < kiSliceCount) {
uiCostDownSum += pSlice->uiSliceFMECostDown;
++ pSlice;
++ iSliceIndex;
}
}
return uiCostDownSum;
}
#define FMESWITCH_MBAVERCOSTSAVING_THRESHOLD (2) //empirically set.
#define FMESWITCH_GOODFRAMECOUNT_MAX (5) //empirically set.
static void UpdateFMEGoodFrameCount (const uint32_t iAvMBNormalizedRDcostDown, uint8_t& uiFMEGoodFrameCount) {
//this strategy may be changed, here the number is derived from empirical-numbers
// uiFMEGoodFrameCount lies in [0,FMESWITCH_GOODFRAMECOUNT_MAX]
if (iAvMBNormalizedRDcostDown > FMESWITCH_MBAVERCOSTSAVING_THRESHOLD) {
if (uiFMEGoodFrameCount < FMESWITCH_GOODFRAMECOUNT_MAX)
++ uiFMEGoodFrameCount;
} else {
if (uiFMEGoodFrameCount > 0)
-- uiFMEGoodFrameCount;
}
}
void UpdateFMESwitch (SDqLayer* pCurLayer) {
const uint32_t iFMECost = CountFMECostDown (pCurLayer);
const uint32_t iAvMBNormalizedRDcostDown = iFMECost / (pCurLayer->iMbWidth * pCurLayer->iMbHeight);
UpdateFMEGoodFrameCount (iAvMBNormalizedRDcostDown, pCurLayer->pFeatureSearchPreparation->uiFMEGoodFrameCount);
}
void UpdateFMESwitchNull (SDqLayer* pCurLayer) {
}
/////////////////////////
// Search function options
/////////////////////////
void WelsDiamondCrossSearch (SWelsFuncPtrList* pFunc, void* vpMe, void* vpSlice, const int32_t kiEncStride,
const int32_t kiRefStride) {
SWelsME* pMe = static_cast<SWelsME*> (vpMe);
SSlice* pSlice = static_cast<SSlice*> (vpSlice);
// Step 1: diamond search
WelsDiamondSearch (pFunc, vpMe, vpSlice, kiEncStride, kiRefStride);
// Step 2: CROSS search
SScreenBlockFeatureStorage pRefBlockFeature; //TODO: use this structure from Ref
pMe->uiSadCostThreshold = pRefBlockFeature.uiSadCostThreshold[pMe->uiBlockSize];
if (pMe->uiSadCost >= pMe->uiSadCostThreshold) {
WelsMotionCrossSearch (pFunc, pMe, pSlice, kiEncStride, kiRefStride);
}
}
void WelsDiamondCrossFeatureSearch (SWelsFuncPtrList* pFunc, void* vpMe, void* vpSlice, const int32_t kiEncStride,
const int32_t kiRefStride) {
SWelsME* pMe = static_cast<SWelsME*> (vpMe);
SSlice* pSlice = static_cast<SSlice*> (vpSlice);
// Step 1: diamond search + cross
WelsDiamondCrossSearch (pFunc, pMe, pSlice, kiEncStride, kiRefStride);
// Step 2: FeatureSearch
if (pMe->uiSadCost >= pMe->uiSadCostThreshold) {
pSlice->uiSliceFMECostDown += pMe->uiSadCost;
SScreenBlockFeatureStorage tmpScreenBlockFeatureStorage; //TODO: use this structure from Ref
uint32_t uiMaxSearchPoint = INT_MAX;//TODO: change it according to computational-complexity setting
SFeatureSearchIn sFeatureSearchIn = {0};
SetFeatureSearchIn (pFunc, *pMe, pSlice, &tmpScreenBlockFeatureStorage,
kiEncStride, kiRefStride,
&sFeatureSearchIn);
MotionEstimateFeatureFullSearch (sFeatureSearchIn, uiMaxSearchPoint, pMe);
pSlice->uiSliceFMECostDown -= pMe->uiSadCost;
}
}
} // namespace WelsSVCEnc
| [
"root@ubuntu.(none)"
] | root@ubuntu.(none) |
176f74f221ac251d9405da36c4a196e887742bb0 | d959ca8272c330ca9905093eb6d4463511c76e32 | /vepro/disk/vschddedit.cpp | c90121a2e5d07efbf53702c8cf56bdfc56f663a3 | [] | no_license | sbppy/vdc | f094f9095345a9ab7c265d6fbb8c1518469c3e51 | e37cf487258ba93fb1e382100223dac62b0afb92 | refs/heads/master | 2020-04-02T01:41:45.720017 | 2014-10-12T14:27:12 | 2014-10-12T14:27:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,322 | cpp | #include "vschddedit.h"
#include "hdddevice.hpp"
#include "debug.hpp"
#include "vschddone.h"
#include "factory.hpp"
extern Factory *gFactory;
VSCHddEdit::VSCHddEdit(QWidget *parent)
: QWidget(parent)
{
m_SelectedDisk = 0;
m_TotalDisks = 0;
int i = 0;
s8 DiskTitle[1024];
ui.setupUi(this);
QStringList hdd = m_Device.GetDeviceList();
QString text;
foreach( text, hdd)
{
if (i >= VSC_SUPPORTED_DISKS)
{
break;
}
astring strHdd = text.toStdString();
VDC_DEBUG( "%s strHdd %s \n",__FUNCTION__, strHdd.c_str());
s64 totalSize = m_Device.GetTotalDiskSpace(strHdd);
s64 leftSize = m_Device.GetavailableDiskSpace(strHdd);
VDC_DEBUG( "%s Total %lld G Left %lld G \n",__FUNCTION__, totalSize, leftSize);
VDC_DEBUG( "%s Type %d \n",__FUNCTION__, m_Device.GetHddType(strHdd));
if (m_Device.GetHddType(strHdd) == HddInternalDrive)
{
/* Add to UI */
m_Disks[i] = new VSCHddOne(true, i, strHdd, totalSize,
leftSize, this);
ui.verticalLayout->addWidget(m_Disks[i] );
if (i == 0)
{
m_Disks[i]->diskSetChecked(true);
}
m_TotalDisks ++;
connect(m_Disks[i], SIGNAL(diskSelectedUpdated(int)), this, SLOT(masterDiskSelected(int)));
i ++;
#if 0
sprintf(DiskTitle, "%s Disk 01 Total %lldG Left %lldG", strHdd.c_str(),
totalSize, leftSize);
ui.label->setText(DiskTitle);
QLabel* w1 = new QLabel("a");
//w1->setStyleSheet("QLabel { background-color : green; color : blue; }");
QSizePolicy policy1 = w1->sizePolicy();
policy1.setHorizontalStretch(1);
w1->setSizePolicy(policy1);
QLabel* w2 = new QLabel("b");
//w2->setStyleSheet("QLabel { background-color : white; color : black; }");
QSizePolicy policy2 = w2->sizePolicy();
policy2.setHorizontalStretch(1);
w2->setSizePolicy(policy2);
//layout->setSpacing(0);
//ui.horizontalLayout_6->addWidget(w1);
//ui.horizontalLayout_6->addWidget(w2);
#endif
}
}
connect( this->ui.applyButton, SIGNAL( clicked() ), this, SLOT(applyConfig()));
}
void VSCHddEdit::masterDiskSelected(int id)
{
for (int i = 0; i <m_TotalDisks; i ++ )
{
m_Disks[i]->diskSetChecked(false);
}
m_Disks[id]->diskSetChecked(true);
m_SelectedDisk = id;
}
BOOL VSCHddEdit::GetDiskPath(astring &strPath)
{
m_Disks[m_SelectedDisk]->getStrHdd(strPath);
return TRUE;
}
s32 VSCHddEdit::GetDiskSize()
{
s64 diskSize = 0;
m_Disks[m_SelectedDisk]->getNewUsed(diskSize);
s32 size = diskSize / 1024;
return size;
}
void VSCHddEdit::applyConfig()
{
bool bUpdate = false;
for (int i = 0; i < m_TotalDisks; i ++)
{
if (m_Disks[i]->isChecked() == false)
{
continue;
}
#ifdef WIN32
astring strPath = "C:\\";
#else
astring strPath = "ve/";//TODO get the hdd from hdd
#endif
s64 size = 1;
m_Disks[i]->getNewUsed(size);
size = size / 1024;
m_Disks[i]->getStrHdd(strPath);
gFactory->AddHDD(strPath, size);
bUpdate = true;
}
if (bUpdate == true)
{
emit DiskTreeUpdated();
}
return;
}
| [
"[email protected]"
] | |
5c9ce7e01e4567e5d84ec63631bd9d6876c20e9f | 0f7a4119185aff6f48907e8a5b2666d91a47c56b | /sstd_utility/windows_boost/boost/test/tools/fpc_op.hpp | bc9685840d2ce256e06f8a7247d301b58570a5b5 | [] | no_license | jixhua/QQmlQuickBook | 6636c77e9553a86f09cd59a2e89a83eaa9f153b6 | 782799ec3426291be0b0a2e37dc3e209006f0415 | refs/heads/master | 2021-09-28T13:02:48.880908 | 2018-11-17T10:43:47 | 2018-11-17T10:43:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,694 | hpp | // (C) Copyright Gennadiy Rozental 2001.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org/libs/test for the library home page.
//
//!@file
//!@brief Floating point comparison with enhanced reporting
// ***************************************************************************
#ifndef BOOST_TEST_TOOLS_FPC_OP_HPP_050915GER
#define BOOST_TEST_TOOLS_FPC_OP_HPP_050915GER
// Boost.Test
#include <boost/test/tools/assertion.hpp>
#include <boost/test/tools/floating_point_comparison.hpp>
#include <boost/test/tools/fpc_tolerance.hpp>
// Boost
#include <boost/type_traits/common_type.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/test/detail/suppress_warnings.hpp>
//____________________________________________________________________________//
namespace boost {
namespace test_tools {
namespace assertion {
namespace op {
// ************************************************************************** //
// ************** fpctraits ************** //
// ************************************************************************** //
// set of floating point comparison traits per comparison OP
template<typename OP>
struct fpctraits {
// indicate if we should perform the operation with a "logical OR"
// with the "equality under tolerance".
static const bool equality_logical_disjunction = true;
};
template <typename Lhs, typename Rhs>
struct fpctraits<op::LT<Lhs,Rhs> > {
static const bool equality_logical_disjunction = false;
};
template <typename Lhs, typename Rhs>
struct fpctraits<op::GT<Lhs,Rhs> > {
static const bool equality_logical_disjunction = false;
};
//____________________________________________________________________________//
// ************************************************************************** //
// ************** set of overloads to select correct fpc algo ************** //
// ************************************************************************** //
// we really only care about EQ vs NE. All other comparisons use direct first
// and then need EQ. For example a <= b (tolerance t) IFF a <= b OR a == b (tolerance t)
template <typename FPT, typename Lhs, typename Rhs, typename OP>
inline assertion_result
compare_fpv( Lhs const& lhs, Rhs const& rhs, OP* cmp_operator)
{
bool result = cmp_operator->eval_direct(lhs, rhs);
if(fpctraits<OP>::equality_logical_disjunction) {
return result || compare_fpv<FPT>(lhs, rhs, (op::EQ<Lhs, Rhs>*)0);
}
return result && compare_fpv<FPT>(lhs, rhs, (op::NE<Lhs, Rhs>*)0);
}
//____________________________________________________________________________//
template <typename FPT, typename Lhs, typename Rhs>
inline assertion_result
compare_fpv_near_zero( FPT const& fpv, op::EQ<Lhs,Rhs>* )
{
fpc::small_with_tolerance<FPT> P( fpc_tolerance<FPT>() );
assertion_result ar( P( fpv ) );
if( !ar )
ar.message() << "Absolute value exceeds tolerance [|" << fpv << "| > "<< fpc_tolerance<FPT>() << ']';
return ar;
}
//____________________________________________________________________________//
template <typename FPT, typename Lhs, typename Rhs>
inline assertion_result
compare_fpv_near_zero( FPT const& fpv, op::NE<Lhs,Rhs>* )
{
fpc::small_with_tolerance<FPT> P( fpc_tolerance<FPT>() );
assertion_result ar( !P( fpv ) );
if( !ar )
ar.message() << "Absolute value is within tolerance [|" << fpv << "| < "<< fpc_tolerance<FPT>() << ']';
return ar;
}
//____________________________________________________________________________//
template <typename FPT, typename Lhs, typename Rhs>
inline assertion_result
compare_fpv( Lhs const& lhs, Rhs const& rhs, op::EQ<Lhs,Rhs>* )
{
if( lhs == 0 ) {
return compare_fpv_near_zero( rhs, (op::EQ<Lhs,Rhs>*)0 );
}
else if( rhs == 0) {
return compare_fpv_near_zero( lhs, (op::EQ<Lhs,Rhs>*)0 );
}
else {
fpc::close_at_tolerance<FPT> P( fpc_tolerance<FPT>(), fpc::FPC_STRONG );
assertion_result ar( P( lhs, rhs ) );
if( !ar )
ar.message() << "Relative difference exceeds tolerance ["
<< P.tested_rel_diff() << " > " << P.fraction_tolerance() << ']';
return ar;
}
}
//____________________________________________________________________________//
template <typename FPT, typename Lhs, typename Rhs>
inline assertion_result
compare_fpv( Lhs const& lhs, Rhs const& rhs, op::NE<Lhs,Rhs>* )
{
if( lhs == 0 ) {
return compare_fpv_near_zero( rhs, (op::NE<Lhs,Rhs>*)0 );
}
else if( rhs == 0 ) {
return compare_fpv_near_zero( lhs, (op::NE<Lhs,Rhs>*)0 );
}
else {
fpc::close_at_tolerance<FPT> P( fpc_tolerance<FPT>(), fpc::FPC_WEAK );
assertion_result ar( !P( lhs, rhs ) );
if( !ar )
ar.message() << "Relative difference is within tolerance ["
<< P.tested_rel_diff() << " < " << fpc_tolerance<FPT>() << ']';
return ar;
}
}
//____________________________________________________________________________//
#define DEFINE_FPV_COMPARISON( oper, name, rev ) \
template<typename Lhs,typename Rhs> \
struct name<Lhs,Rhs,typename boost::enable_if_c< \
(fpc::tolerance_based<Lhs>::value && \
fpc::tolerance_based<Rhs>::value)>::type> { \
public: \
typedef typename common_type<Lhs,Rhs>::type FPT; \
typedef name<Lhs,Rhs> OP; \
\
typedef assertion_result result_type; \
\
static bool \
eval_direct( Lhs const& lhs, Rhs const& rhs ) \
{ \
return lhs oper rhs; \
} \
\
static assertion_result \
eval( Lhs const& lhs, Rhs const& rhs ) \
{ \
if( fpc_tolerance<FPT>() == FPT(0) ) \
{ \
return eval_direct( lhs, rhs ); \
} \
\
return compare_fpv<FPT>( lhs, rhs, (OP*)0 ); \
} \
\
template<typename PrevExprType> \
static void \
report( std::ostream& ostr, \
PrevExprType const& lhs, \
Rhs const& rhs ) \
{ \
lhs.report( ostr ); \
ostr << revert() \
<< tt_detail::print_helper( rhs ); \
} \
\
static char const* revert() \
{ return " " #rev " "; } \
}; \
/**/
BOOST_TEST_FOR_EACH_COMP_OP( DEFINE_FPV_COMPARISON )
#undef DEFINE_FPV_COMPARISON
//____________________________________________________________________________//
} // namespace op
} // namespace assertion
} // namespace test_tools
} // namespace boost
#include <boost/test/detail/enable_warnings.hpp>
#endif // BOOST_TEST_TOOLS_FPC_OP_HPP_050915GER
| [
"[email protected]"
] | |
e33af93a8e3e3eb36800332935972c45050609f0 | fab77712e8dfd19aea9716b74314f998093093e2 | /Utility/TypeDefine.h | 6515522dff2c648af5c4f2f097f91ffd53b4fc20 | [] | no_license | alandigi/tsfriend | 95f98b123ae52f1f515ab4a909de9af3724b138d | b8f246a51f01afde40a352248065a6a42f0bcbf8 | refs/heads/master | 2016-08-12T07:09:23.928793 | 2011-11-13T15:12:54 | 2011-11-13T15:12:54 | 45,849,814 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,483 | h | #pragma once
#define DATAVIEWBUFFERLENTH 8192 /* (1024*8)*/
#define INVALID_VERSION 0xFF /* */
#define VALUE_MAX_LENGTH_IN_BYTE 8
#define UI_CLIENT_ID 0xFFFFFFFF
//#define SYSTEM_WITH_ES_OPERATORION
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned long u32;
typedef int s32;
typedef unsigned __int64 u64;
typedef __int64 s64;
/* Utility */
class CDVBSpace;
class CMessage;
class CMessageSpace;
class CThreadObject;
//class CShareResource;
/* TS File */
class CTSFile;
/* ES server */
class CPacket;
class CPacketPool;
class CDemux;
class CESData;
class CESDBServer;
class CESDataBase;
/* Table server */
class CBuilder;
class CSection;
class CTable;
class CTableDBServer;
class CTableDatabase;
/* Format */
class CFormatServer;
class CFormatDatabase;
class CFormatParser;
class CTokenNode;
class CTableHeadNode;
class CDescriptorHeadNode;
class CDataNode;
class CKeyLoopNode;
class CKeyIfNode;
class CKeyElseNode;
class CKeyDescriptorNode;
/* trees */
class CTreeNode;
class CCommonTree;
class CContentTree;
class CFormatTree;
/* formula */
class CFormula;
class CFormulaOperatorNode;
class CFormulaParameterNode;
class CFormulaNumeralNode;
/* UI classes */
class CTSDoc;
| [
"[email protected]"
] | |
cc58bafd8d94cd492ee1faf3f6b7a1d5884642c6 | 011e0ecdc38a41c5f0066f1adb91b430aab2a256 | /jni/GUObjects.h | 8bea7293ee2d48a17d10aac4173e57687c61b881 | [
"MIT"
] | permissive | AkChen/UE4Dumper | 6e56be7085da974020b6b67c50f438f32cbcb066 | bb087078d91b76fb13e312e0386ba9135ac340dc | refs/heads/master | 2022-11-10T04:35:51.757374 | 2020-06-22T11:55:37 | 2020-06-22T11:55:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,321 | h | #ifndef GUOBJECTS_H
#define GUOBJECTS_H
#include "FNames.h"
#include "StructsSDK.h"
using namespace std;
int32 GetObjectCount(){
if(isUE423) {
return Read<int32>(getRealOffset(Offsets::GUObjectArray) +
Offsets::FUObjectArrayToTUObjectArray + Offsets::TUObjectArrayToNumElementsNew);
} else {
if(isEqual(pkg, "com.tencent.tmgp.pubgmhd")){
return Read<int32>(getRealOffset(Offsets::GUObjectArray) + 0x58 + Offsets::TUObjectArrayToNumElements);
} else {
return Read<int32>(getPtr(getRealOffset(Offsets::GUObjectArray)) +
Offsets::FUObjectArrayToTUObjectArray + Offsets::TUObjectArrayToNumElements);
}
}
//return 300000;
}
kaddr GetUObjectFromID(uint32 index) {
if(isUE423) {
kaddr TUObjectArray = getPtr(getRealOffset(Offsets::GUObjectArray) + Offsets::FUObjectArrayToTUObjectArray);
kaddr Chunk = getPtr(TUObjectArray + ((index / 0x10000) * Offsets::PointerSize));
return getPtr(Chunk + ((index % 0x10000) * Offsets::FUObjectItemSizeNew));
} else {
if(isEqual(pkg, "com.tencent.tmgp.pubgmhd")){
kaddr FUObjectArray = getRealOffset(Offsets::GUObjectArray);
kaddr TUObjectArray = getPtr(FUObjectArray + 0x58);
return getPtr(TUObjectArray + (index * Offsets::FUObjectItemSize));
} else {
kaddr FUObjectArray = getPtr(getRealOffset(Offsets::GUObjectArray));
kaddr TUObjectArray = getPtr(FUObjectArray + Offsets::FUObjectArrayToTUObjectArray);
return getPtr(TUObjectArray + (index * Offsets::FUObjectItemSize));
}
}
}
void DumpObjects(string out) {
uint32 count = 0;
ofstream gobj(out + "/UObjects.txt", ofstream::out);
if (gobj.is_open()) {
cout << "Dumping UObjects List" << endl;
for (int32 i = 0; i < GetObjectCount(); i++) {
kaddr uobj = GetUObjectFromID(i);
if (UObject::isValid(uobj)) {
gobj << setbase(10) << "[" << i << "]:" << endl;
gobj << "Name: " << UObject::getName(uobj) << endl;
gobj << "Class: " << UStruct::getClassName(uobj) << endl;
gobj << "ObjectPtr: " << setbase(16) << uobj << endl;
gobj << "ClassPtr: " << setbase(16) << UObject::getClass(uobj) << endl;
gobj << endl;
count++;
}
}
gobj.close();
cout << count << " UObjects Dumped" << endl;
}
}
#endif | [
"[email protected]"
] | |
053bbeb076c782272376f29afc0cbb74e44943ec | 560090526e32e009e2e9331e8a2b4f1e7861a5e8 | /Compiled/blaze-3.2/blazetest/src/mathtest/dmatdmatmin/M16x8bMDa.cpp | 7581940ed06b624a1d70c2fb371125d13e1fc997 | [
"BSD-3-Clause"
] | permissive | jcd1994/MatlabTools | 9a4c1f8190b5ceda102201799cc6c483c0a7b6f7 | 2cc7eac920b8c066338b1a0ac495f0dbdb4c75c1 | refs/heads/master | 2021-01-18T03:05:19.351404 | 2018-02-14T02:17:07 | 2018-02-14T02:17:07 | 84,264,330 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,737 | cpp | //=================================================================================================
/*!
// \file src/mathtest/dmatdmatmin/M16x8bMDa.cpp
// \brief Source file for the M16x8bMDa dense matrix/dense matrix minimum math test
//
// Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/StaticMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatmin/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'M16x8bMDa'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::StaticMatrix<TypeB,16UL,8UL> M16x8b;
typedef blaze::DynamicMatrix<TypeA> MDa;
// Creator type definitions
typedef blazetest::Creator<M16x8b> CM16x8b;
typedef blazetest::Creator<MDa> CMDa;
// Running the tests
RUN_DMATDMATMIN_OPERATION_TEST( CM16x8b(), CMDa( 16UL, 8UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix minimum:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"[email protected]"
] | |
d9c0479019f99c2811d009e178bc81724ced6465 | f8c89c4b3985966e2678d57ce0608edc411acbde | /Action.h | 0780aa5f23abc04f5bfaf0d6f01b3f52683a2680 | [] | no_license | IaMartynas/Zork | 9e038ab8a4171152b8b052abec07851e35e03a1d | 4e6131d390e1ca6d25f639cb4585579f9e7b7b32 | refs/heads/master | 2021-05-03T16:42:59.383907 | 2018-02-06T11:46:04 | 2018-02-06T11:46:04 | 120,441,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | h | /*
* Action.h
*
* Created on: Nov 4, 2017
* Author: Martynas
*/
#ifndef ACTION_H_
#define ACTION_H_
#include <string>
class Action {
public:
Action(std::string, std::string);
virtual ~Action();
virtual std::string getType();
virtual std::string getAction();
private:
std::string mType;
std::string mAction;
};
#endif /* ACTION_H_ */
| [
"[email protected]"
] | |
8eb907a3f7fb5c02bf26d1676e3953d7544f9275 | f8c59c335b0c1dc2e8ab2824de234850e0a4c045 | /modules/ide_old/src/CentralGui.h | 3d04b7ddc1ec984d8fca873b5bcc0f6af13cc152 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | DeepBlue14/rqt_ide | 469d7ffb9a2fa244c68ceafe526baa24e89b1a7b | 853964dc429d61c9afb6f1fe827f2e3e83f92713 | refs/heads/master | 2020-12-31T06:57:33.789919 | 2016-09-07T05:04:54 | 2016-09-07T05:04:54 | 34,908,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,302 | h | /*
* File: CentralGui.h
* Module: MasterFEnd
* Author: James Kuczynski
* Email: [email protected]
* File Description: This file will contain the qcentralwidget of the
* qmainwindow. Currently, it is divided into four sections
* (although this could be changed), north, south, east,
* and west.
*
* Created on May 6, 2015, 4:33 PM
*/
#ifndef CENTRAL_GUI_H
#define CENTRAL_GUI_H
#include <QWidget>
#include <QGridLayout>
#include <QTabWidget>
#include <QProgressBar>
#include <iostream>
#include "TabGui.h"
#include "FileTreeGui.h"
#include "RunPanelGui.h"
#include "NavigatorGui.h"
#include "OutputGui.h"
#include "WindowsConsoleText.h"
#include "UnixConsoleText.h"
#ifdef _WIN32
namespace cct = WindowsConsoleText;
#elif __APPLE
namespace cct = UnixConsoleText;
#elif __linux
namespace cct = UnixConsoleText;
#endif
using namespace std;
class CentralGui : public QWidget
{
Q_OBJECT
private:
TabGui* northGuiPtr;
FileTreeGui* fileTreeGuiPtr;
RunPanelGui* runPanelGuiPtr;
NavigatorGui* navigatorGuiPtr;
OutputGui* southGuiPtr;
QGridLayout* outerLayout;
private slots:
;
public:
/**
* Constructor.
*
* @param parent reference to parent type.
*/
CentralGui(QWidget* parent = 0);
/**
*
*
* @param northGuiPtr
*/
void setNorthGuiPtr(TabGui* northGuiPtr);
/**
*
*
* @return
*/
TabGui* getNorthGuiPtr();
/**
*
*
* @param fileTreeGuiPtr
*/
void setFileTreeGuiPtr(FileTreeGui* fileTreeGuiPtr);
/**
*
*
* @return
*/
FileTreeGui* getFileTreeGuiPtr();
void setRunPanelGuiPtr(RunPanelGui* runPanelGuiPtr);
RunPanelGui* getRunPanelGuiPtr();
/**
*
*
* @param navigatorGuiPtr
*/
void setNavigatorGuiPtr(NavigatorGui* navigatorGuiPtr);
/**
*
*
* @return
*/
NavigatorGui* getNavigatorGuiPtr();
/**
*
*
* @param southGuiPtr
*/
void setSouthGuiPtr(OutputGui* southGuiPtr);
/**
*
*
* @return
*/
OutputGui* getSouthGuiPtr();
/**
*
*
* @return
*/
static QProgressBar getProgressBarPtr();
/**
*
*
* @param northTabWidgetPtr
*/
void passNorthTabWidgetPtr(QTabWidget* northTabWidgetPtr);
/**
*
*
* @param southTabWidgetPtr
*/
void passSouthTabWidgetPtr(QTabWidget* southTabWidgetPtr);
/**
* Classic toString method.
*
* @return class data.
*/
QString* toString();
/**
* Destructor.
*/
~CentralGui();
};
#endif /* CENTRAL_GUI_H */ | [
"[email protected]"
] | |
d667edbf8b0f9227cb20add64aea7f5a132ad44b | 19fde8ce837204bc8ab1a2d34445a7326d95b153 | /hiho/h_172.cpp | bb38c9df6177e5b5d6c55babb4de58a566b0fe38 | [] | no_license | JS00000/acmCode | aad59f1fdd66bb3b4b2208c8c5be0f26b7169405 | eda5dbcef4a66618fc27e79184a2ae93618ee6b1 | refs/heads/master | 2021-05-24T04:27:11.966469 | 2021-03-01T08:55:35 | 2021-03-01T08:55:35 | 55,392,212 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,205 | cpp | // 二维树状数组 Fenwick_tree
#include <stdio.h>
#define maxn 1007
const int mod = 1000000007;
inline int lowbit(int x)
{
return x&(-x);
}
int N, M;
int BIT2[maxn][maxn];
void add(int x, int y, int val) {
for(int i = x; i <= N; i += lowbit(i)) {
for(int j = y; j <= N; j += lowbit(j)) {
BIT2[i][j] = ((BIT2[i][j] + val) % mod + mod) % mod;
}
}
}
int sum(int x, int y) {
int ret = 0;
for(int i = x; i > 0; i -= lowbit(i)) {
for(int j = y; j > 0; j -= lowbit(j)) {
ret = ((ret + BIT2[i][j]) % mod + mod) % mod;
}
}
return ret;
}
int main()
{
scanf("%d%d", &N, &M);
for (int i = 0; i <= N; i++)
for (int j = 0; j <= N; j++)
BIT2[i][j] = 0;
char command[10];
int a, b, x, y;
int v;
for (int i = 0; i < M; i++) {
scanf("%s", command);
if (command[0] == 'A') {
scanf("%d%d%d", &x, &y, &v);
add(x+1, y+1, v);
} else if (command[0] == 'S') {
scanf("%d%d%d%d", &a, &b, &x, &y);
printf("%d\n", ((sum(x+1, y+1) - sum(x+1, b) - sum(a, y+1) + sum(a, b)) % mod + mod) % mod);
}
}
return 0;
}
| [
"[email protected]"
] | |
5009ee293389c84750da258b0f2c66f1a78f42d1 | 8b1cedbca5f5a967e5c37c280f53dfdbff00ff19 | /cocos/170720/170720_Transition/Classes/TestScene2.cpp | 0b464c9e5087acb770b2fe716b9c3327637a5063 | [] | no_license | kcwzzz/KCW | ef552641c77d1971ad4536d37a70eb9a59f4d4e6 | 34973e5fae0a4095418ac0bd99637ffa24f525be | refs/heads/master | 2020-12-03T05:11:38.828978 | 2017-09-29T08:10:59 | 2017-09-29T08:10:59 | 95,736,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 618 | cpp | #include "TestScene2.h"
using namespace cocos2d;
Scene* TestScene2::createScene()
{
return TestScene2::create();
}
bool TestScene2::init()
{
if (!Scene::init())
{
return false;
}
auto item1 = MenuItemFont::create(
"Close Scene 2",
CC_CALLBACK_1(TestScene2::doClose, this));
auto pMenu = Menu::create(item1, nullptr);
pMenu->setPosition(Vec2(400, 50));
this->addChild(pMenu, 10);
auto tpSprite = Sprite::create("slime.png");
tpSprite->setPosition(Vec2(400, 240));
this->addChild(tpSprite, 0);
return true;
}
void TestScene2::doClose(Ref* pSender)
{
Director::getInstance()->popScene();
} | [
"[email protected]"
] | |
344826cfd4c38a768bacacbe9080b8308c23c11c | 7c8f7ca4974a20097e5aafff47b9d30b950e98fb | /source/scenes/level/Entity.cpp | 83be0baa8d12890aca5facb254acc0fb5395b88e | [] | no_license | liam-mitchell/mech | 1ba49942bec7efbf2a17883678269c9ac486de89 | f944675ca4a236d78df6e89d270f0fef3dc5b15c | refs/heads/master | 2020-03-27T23:27:58.328677 | 2015-03-20T00:49:27 | 2015-03-20T00:49:27 | 31,706,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 231 | cpp | #include "Entity.h"
void Entity::updateBehaviours(Level &level, unsigned int dt)
{
for (auto b = behaviours.rbegin(); b != behaviours.rend(); ++b) {
if ((*b)->execute(level, dt)) {
break;
}
}
}
| [
"[email protected]"
] | |
00f050c06bb088e756a0eb245aef0f2c0bade7dd | be3c7d375f992ffcee3d1d16e00b8540e92e878b | /filesystem.h | 5e462f37fb874ba7d8ba478383c04ac8a389207b | [] | no_license | faceteam/detectBody | 95a91583e89d11f0155fd034856e743253da54bb | 89ecf946fe414880b8bac669ba77e6d28808988e | refs/heads/master | 2016-09-12T23:07:45.456752 | 2016-06-02T03:19:21 | 2016-06-02T03:19:21 | 57,004,274 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,226 | h | #ifndef FILESYSTEM_H
#define FILESYSTEM_H
#include <string>
#include <vector>
class FileSystem {
public:
/**
* check a file or a directory exists
* @param[in] path a file path or a directory path
* @return true if path exists else false
*/
static bool isExists(const std::string& path);
/**
* create a directory if not exists, **the parent directory must exist**
* @param[in] dp directory path
* @reutrn true if create success else false
*/
static bool makeDir(const std::string& dp);
/**
* delete a file if exists
* if the file doesn't exists, nothing will be done and return true
* @param[in] fp full file path in filesystem
* @return true if deleted else false
*/
static bool deleteFile(const std::string& fp);
/**
* move file from src to dst, both parent directory of src and dst must exists
* @param[in] src file source
* @param[in] dst file destination
* @return true if moved else false
*/
static bool moveFile(const std::string& src, const std::string& dst);
/**
* get file name from file path
* /path/to/xxx.yyy -> xxx or xxx.yyy -> xxx
* @param[in] fp file path
* return file name without extension name
*/
static std::string getFileName(const std::string& fp);
/**
* get file extension name from file path
* /path/to/xxx.yyy -> yyy or xxx.yyy -> yyy
* @param[in] fp file path
* @return file extension name
*/
static std::string getFileExt(const std::string& fp);
/**
* get file list in a directory with specific extension name
* @param[in] dp directory path
* @param[in] ext extension name
* @param[out] fn files
* @paran[in] limit numbers of files to load
* @return true if success else false
*/
static bool readDir(const std::string& dp, const std::string& ext, \
std::vector<std::string>& fn, int limit=0);
static bool FileSystem::readDirwithpath(const std::string& dp, const std::string& ext,
std::vector<std::string>& fn, int limit=0);
/**
* join path for part1 and part2
* @param[in] part1, part2 filesystem path
* @return filesystem path for part1/part2
*/
static std::string join(const std::string &part1, const std::string &part2);
};
#endif // FILESYSTEM_H | [
"[email protected]"
] | |
9fb83c0ac982fa4fecf65f8941ad9c977f10bb23 | 55405bda5a9063b53f643d46bf520433e1d647d8 | /ch/ModificationsChecker.hpp | 52ca7e31ee9b2604366c4b9ca2ec719523709acc | [] | no_license | InvictusInnovations/keyhotee | c6f41e8c7856e54feeb3ba6b3b950174813a8d0e | cb4d1402559e645fb843affd221079f979c807d6 | refs/heads/master | 2021-01-23T03:44:20.215606 | 2014-09-05T08:44:12 | 2014-09-05T08:44:12 | 13,315,798 | 8 | 6 | null | 2014-03-13T16:33:17 | 2013-10-04T03:41:43 | C | UTF-8 | C++ | false | false | 494 | hpp | #ifndef __MODIFICATIONSCHECKER_H
#define __MODIFICATIONSCHECKER_H
/** Dedicated interface checking modifications.
if there are same changes blocking all mouse, keybord events.
*/
class IModificationsChecker
{
public:
/** Check modification
returns true if there is no modifications, application can
go to the next step
*/
virtual bool canContinue() const = 0;
protected:
virtual ~IModificationsChecker() {}
};
#endif ///__MODIFICATIONSCHECKER_H
| [
"[email protected]"
] | |
d777a648d4374da9200ba804f1e3adbeff0e677f | c300ddd08b145c074a541bae6864915b174dcf24 | /src/nstd/utility/forward.t.cpp | 4644b6a0b52d81093fc8dc80ea12571cb3be2fe5 | [] | no_license | zeta1999/kuhllib | d5f09b80d6472669722cdd94181f87757b3a863b | 72fce48a1f50f6487018d9f65097845ac5e0e558 | refs/heads/master | 2023-03-13T22:05:22.725697 | 2020-05-22T15:30:54 | 2020-05-22T15:30:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,866 | cpp | // nstd/utility/forward.t.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// Copyright (C) 2014 Dietmar Kuehl http://www.dietmar-kuehl.de
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify,
// merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// ----------------------------------------------------------------------------
#include "nstd/utility/forward.hpp"
#include "nstd/type_traits/declval.hpp"
#include "kuhl/test.hpp"
namespace NU = nstd::utility;
namespace NT = nstd::type_traits;
namespace KT = kuhl::test;
// ----------------------------------------------------------------------------
namespace
{
struct foo {};
}
// ----------------------------------------------------------------------------
static KT::testcase const tests[] = {
KT::expect_success("forward(rvalue)", [](KT::context& c)->bool{
foo&& reference(NU::forward<foo&&>(foo()));
KT::use(reference);
return KT::assert_type<foo&&, decltype(NU::forward<foo&&>(foo()))>(c, "foo()");
;
}),
KT::expect_success("forward(lvalue)", [](KT::context& c)->bool{
foo lvalue{};
foo& reference(NU::forward<foo&>(lvalue));
return assert_equal(c, "forward lvalue", &lvalue, &reference)
&& KT::assert_type<foo&, decltype(NU::forward<foo&>(lvalue))>(c, "foo&");
;
}),
KT::expect_success("forward(lvalue const)", [](KT::context& c)->bool{
foo const lvalue{};
foo const& reference(NU::forward<foo const&>(lvalue));
return assert_equal(c, "forward lvalue const", &lvalue, &reference)
&& KT::assert_type<foo const&, decltype(NU::forward<foo const&>(lvalue))>(c, "foo const&");
;
}),
KT::expect_success("forward(lvalue volatile)", [](KT::context& c)->bool{
foo volatile lvalue{};
foo volatile& reference(NU::forward<foo volatile&>(lvalue));
return assert_equal(c, "forward lvalue volatile", &lvalue, &reference)
&& KT::assert_type<foo volatile&, decltype(NU::forward<foo volatile&>(lvalue))>(c, "foo volatile&");
;
}),
KT::expect_success("forward(lvalue const volatile)", [](KT::context& c)->bool{
foo const volatile lvalue{};
foo const volatile& reference(NU::forward<foo const volatile&>(lvalue));
return assert_equal(c, "forward lvalue const volatile", &lvalue, &reference)
&& KT::assert_type<foo const volatile&, decltype(NU::forward<foo const volatile&>(lvalue))>(c, "foo const volatile&");
;
}),
KT::expect_success("forward() doesn't throw", [](KT::context& c)->bool{
return KT::assert_true(c, "rvlaue", noexcept(NU::forward<foo&&>(NT::declval<foo>())))
&& KT::assert_true(c, "lvlaue", noexcept(NU::forward<foo&>(NT::declval<foo&>())))
&& KT::assert_true(c, "lvlaue const", noexcept(NU::forward<foo const&>(NT::declval<foo const&>())))
&& KT::assert_true(c, "lvlaue volatile", noexcept(NU::forward<foo volatile&>(NT::declval<foo volatile&>())))
&& KT::assert_true(c, "lvlaue const volatile", noexcept(NU::forward<foo const volatile&>(NT::declval<foo const volatile&>())))
;
}),
};
int main(int ac, char* av[])
{
return KT::run_tests("utility::forward", ac, av, ::tests);
}
| [
"[email protected]"
] | |
772d6e0736c16d14fa1a3c49d7ca251b172ce486 | aa13e1d93b7a8017e1e610a900bd05f6df91604f | /spoj/classicals/archive/GERGOVIA.cpp | ce843194d49a34a99cf8bac302c30ef3ab6842ac | [] | no_license | laveesingh/Competitive-Programming | 3ce3272eab525635f9ce400f7467ee09de8b51df | 41047f47c23bc8572a1891e891a03cc3f751e588 | refs/heads/master | 2021-01-24T09:51:00.332543 | 2017-10-30T17:11:48 | 2017-10-30T17:11:48 | 52,956,650 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 599 | cpp | #include <iostream>
using namespace std;
#define ull long long
// ull abs(ull a){
// if (a >= 0) return a;
// return -a;
// }
void Print(ull a[], ull n){
for (ull i = 0; i < n; i += 1){
cout << a[i] << " ";
}
cout << endl;
}
int main(void){
ull n;
while(1){
cin >> n;
if (n == 0) break;
ull a[n];
for (ull i = 0; i < n; i += 1){
cin >> a[i];
}
// cout << "Here is the pre-array: ";Print(a,n);
ull ans = 0;
for (ull i = 0; i < n-1; i += 1){
ans += abs(a[i]);
a[i+1] += a[i];
}
// cout << "Here is the post-arrya: ";Print(a, n);
cout << ans << endl;
}
} | [
"[email protected]"
] | |
2332e8b15a22c2c4a614cdbe0f1cba2ad369bd72 | 822b4950ab90a02ba9471695e8b3a37ca35155b2 | /terminal_app/mainwindow.cpp | 79187de1140873456c3c061b9f910cea44a18c6f | [] | no_license | whicun/PFController | ef1c9cd007f3e89a87c60125103c281a2bb401e8 | 95537de2c27490f1659d189ed36b02d8eaa8f300 | refs/heads/master | 2023-03-30T13:26:30.193105 | 2021-04-03T16:11:47 | 2021-04-03T16:11:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 31,353 | cpp | /**
* @file mainwindow.c
* @author Stanislav Karpikov
* @brief Main application window management
*/
/** @addtogroup app_main
* @{
*/
/*--------------------------------------------------------------
INCLUDES
--------------------------------------------------------------*/
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "settingsdialog.h"
#include <QMessageBox>
#include <QMessageBox>
#include <QDateTime>
#include <QGraphicsDropShadowEffect>
#include <QListWidgetItem>
#include "htmldelegate.h"
#include "device_definition.h"
#include "interface_definitions.h"
#include "interface_messaging.h"
#include <sstream> /* std::stringstream */
#include <iomanip> /* std::setfill, std::setw */
/*--------------------------------------------------------------
NAMESPACES
--------------------------------------------------------------*/
using namespace PFCconfig;
using namespace PFCconfig::ADC;
using namespace PFCconfig::Interface;
using namespace PFCconfig::Events;
using namespace InterfaceDefinitions;
using namespace InterfaceMessaging;
/*--------------------------------------------------------------
PRIVATE DATA
--------------------------------------------------------------*/
/*--------------------------------------------------------------
CLASS FUNCTIONS
--------------------------------------------------------------*/
MainWindow::TableCalibrationRows& operator++(MainWindow::TableCalibrationRows& row, int)
{
row = static_cast<MainWindow::TableCalibrationRows>( enum_uint(row) + 1 );
return row;
}
/*--------------------------------------------------------------
CLASS FUNCTIONS
--------------------------------------------------------------*/
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent),
_ui(new Ui::MainWindow),
_pfc(new PFC),
_pfc_settings(new PFCsettings),
_page_filters(_ui, _pfc_settings, _pfc),
_page_oscillog(_ui, _pfc_settings, _pfc),
_page_main(_ui, _pfc_settings, _pfc),
_last_index_events(0),
_port_settings(new SettingsDialog),
_connected(false),
_btns_edit()
{
/* Init the UI */
_ui->setupUi(this);
_ui->actionConnect->setEnabled(true);
_ui->actionDisconnect->setEnabled(false);
_ui->actionQuit->setEnabled(true);
_ui->actionConfigure->setEnabled(true);
initInterfaceConnections();
qRegisterMetaType<QSerialPort::DataBits>("QSerialPort::DataBits");
qRegisterMetaType<QSerialPort::Parity>("QSerialPort::Parity");
qRegisterMetaType<QSerialPort::StopBits>("QSerialPort::StopBits");
qRegisterMetaType<QSerialPort::FlowControl>("QSerialPort::FlowControl");
qRegisterMetaType<std::vector<uint8_t>>("std::vector<uint8_t>");
qRegisterMetaType<InterfacePackage*>("PackageCommand*");
qRegisterMetaType<uint8_t>("uint8_t");
qRegisterMetaType<std::string>("std::string");
_ui->groupState->installEventFilter(this);
_ui->groupNetworkParameters->installEventFilter(this);
_ui->OscillogPlot->installEventFilter(this);
_ui->pageCalibrations->installEventFilter(this);
_ui->pageCapacitors->installEventFilter(this);
_ui->pageProtection->installEventFilter(this);
_ui->pageFilters->installEventFilter(this);
/* Init settings window and show it */
QMetaObject::invokeMethod(_port_settings, "show", Qt::QueuedConnection);
/* Init PFC device subsystem */
connect(_pfc, &PFC::interfaceConnected, this, &MainWindow::deviceConnected);
connect(_pfc, &PFC::interfaceDisconnected, this, &MainWindow::deviceDisconnected);
connect(_pfc, &PFC::setConnection, this, &MainWindow::setConnection);
connect(_pfc, &PFC::setNetVoltage, this, &MainWindow::setNetVoltage);
connect(_pfc, &PFC::setSwitchOnOff, this, &MainWindow::setSwitchOnOff);
connect(_pfc, &PFC::setNetVoltageRAW, this, &MainWindow::setNetVoltageRAW);
connect(_pfc, &PFC::setNetParams, this, &MainWindow::setNetParams);
connect(_pfc, &PFC::setEvents, this, &MainWindow::setEvents);
connect(_pfc, &PFC::message, this, &MainWindow::message);
connect(_pfc, &PFC::setSettingsCalibrations,
this, &MainWindow::setSettingsCalibrations);
connect(_pfc, &PFC::setSettingsProtection,
this, &MainWindow::setSettingsProtection);
connect(_pfc, &PFC::setSettingsCapacitors,
this, &MainWindow::setSettingsCapacitors);
connect(_pfc, &PFC::ansSettingsCalibrations,
this, &MainWindow::ansSettingsCalibrations);
connect(_pfc, &PFC::ansSettingsProtection,
this, &MainWindow::ansSettingsProtection);
connect(_pfc, &PFC::ansSettingsCapacitors,
this, &MainWindow::ansSettingsCapacitors);
connect(this, &MainWindow::updateNetVoltage,
_pfc, &PFC::updateNetVoltage);
connect(this, &MainWindow::updateNetVoltageRAW,
_pfc, &PFC::updateNetVoltageRAW);
connect(this, &MainWindow::updateNetParams,
_pfc, &PFC::updateNetParams);
connect(this, &MainWindow::updateEvents,
_pfc, &PFC::updateEvents);
connect(this, &MainWindow::updateSettingsCalibrations,
_pfc, &PFC::updateSettingsCalibrations);
connect(this, &MainWindow::updateSettingsProtection,
_pfc, &PFC::updateSettingsProtection);
connect(this, &MainWindow::updateSettingsCapacitors,
_pfc, &PFC::updateSettingsCapacitors);
connect(this, &MainWindow::writeSettingsCalibrations,
_pfc, &PFC::writeSettingsCalibrations);
connect(this, &MainWindow::writeSettingsProtection,
_pfc, &PFC::writeSettingsProtection);
connect(this, &MainWindow::writeSettingsCapacitors,
_pfc, &PFC::writeSettingsCapacitors);
connect(this, &MainWindow::writeSwitchOnOff,
_pfc, &PFC::writeSwitchOnOff);
connect(&_timer_voltage, &QTimer::timeout,
this, &MainWindow::timerupdateNetVoltage);
connect(&_timer_raw, &QTimer::timeout,
this, &MainWindow::timerupdateNetVoltageRaw);
connect(&_timer_oscillog, &QTimer::timeout,
this, &MainWindow::timerOscillog);
connect(&_timer_settings_calibrations, &QTimer::timeout,
this, &MainWindow::timerSettingsCalibrations);
connect(&_timer_settings_capacitors, &QTimer::timeout,
this, &MainWindow::timerSettingsCapacitors);
connect(&_timer_settings_protection, &QTimer::timeout,
this, &MainWindow::timerSettingsProtection);
connect(&_timer_settings_filters, &QTimer::timeout,
this, &MainWindow::timerSettingsFilters);
connect(&_timer_main_params, &QTimer::timeout,
this, &MainWindow::timerNetParams);
connect(&_timer_state, &QTimer::timeout,
this, &MainWindow::timerWorkState);
connect(&_timer_version, &QTimer::timeout,
this, &MainWindow::timerVersion);
connect(&_timer_events, &QTimer::timeout,
this, &MainWindow::timerEvents);
/* Init window pages */
_page_main.pageMainInit();
_page_oscillog.pageOscillogInit();
pageSettingsCalibrationsInit();
pageSettingsCapacitorsInit();
pageSettingsProtectionInit();
_page_filters.pageSettingsFiltersInit();
_timer_events.start(EVENTS_TIMER_TIMEOUT);
_ui->listLog->setItemDelegate(new HtmlDelegate);
}
void MainWindow::setFilter(QEvent* event, QObject* object, QWidget* ui_obj, QTimer* obj, std::chrono::milliseconds timeout)
{
if (object == ui_obj)
{
if (event->type() == QEvent::Show)
{
std::chrono::milliseconds timeout_apply = timeout +
((static_cast<std::chrono::milliseconds>(qrand()) % (timeout / 4)) - (timeout / 4));
obj->start(timeout_apply);
}
if (event->type() == QEvent::Hide)
{
obj->stop();
}
}
}
std::string MainWindow::stringWithColor(std::string str, std::string color)
{
std::string ret_str;
ret_str = "<font color=" + color + ">" + str + "</font>";
return ret_str;
}
void MainWindow::setConnection(bool connected)
{
_connected = connected;
if (!_connected)
{
_last_index_events = 0;
}
}
void MainWindow::filterApply(float &A, float B)
{
A = A * FCOEFF + B * (1 - FCOEFF);
}
void MainWindow::timerupdateNetVoltage(void)
{
if (_connected) emit updateNetVoltage();
}
void MainWindow::timerupdateNetVoltageRaw(void)
{
if (_connected) emit updateNetVoltageRAW();
}
void MainWindow::timerSettingsCapacitors(void)
{
if (_connected) emit updateSettingsCapacitors();
}
void MainWindow::timerSettingsProtection(void)
{
if (_connected) emit updateSettingsProtection();
}
void MainWindow::timerSettingsFilters(void)
{
if (_connected) emit _page_filters.update();
}
void MainWindow::timerSettingsCalibrations(void)
{
if (_connected) emit updateSettingsCalibrations();
}
void MainWindow::timerEvents(void)
{
if (_connected) emit updateEvents(_last_index_events);
}
void MainWindow::timerWorkState(void)
{
/* Frequent update */
if (_connected) _page_main.update();
}
void MainWindow::timerVersion(void)
{
/* Low frequency update update */
_page_main.update();
}
void MainWindow::timerNetParams(void)
{
if (_connected) emit updateNetParams();
}
void MainWindow::timerOscillog(void)
{
if (_connected) _page_oscillog.update();
}
bool MainWindow::eventFilter(QObject* object, QEvent* event)
{
setFilter(event, object, _ui->groupNetworkParameters, &_timer_main_params, TIMEOUT_UPDATE_MAIN_PARAMS);
setFilter(event, object, _ui->groupNetworkParameters, &_timer_voltage, TIMEOUT_UPDATE_VOLTAGES);
setFilter(event, object, _ui->groupNetworkParameters, &_timer_raw, TIMEOUT_UPDATE_ADC_RAW);
setFilter(event, object, _ui->groupNetworkParameters, &_timer_state, TIMEOUT_UPDATE_STATE);
setFilter(event, object, _ui->groupState, &_timer_version, TIMEOUT_UPDATE_VERSION);
setFilter(event, object, _ui->OscillogPlot, &_timer_oscillog, TIMEOUT_UPDATE_OSCILLOG);
setFilter(event, object, _ui->pageCalibrations, &_timer_settings_calibrations, TIMEOUT_UPDATE_SETTINGS_CALIBRATIONS);
setFilter(event, object, _ui->pageCapacitors, &_timer_settings_capacitors, TIMEOUT_UPDATE_SETTINGS_CAPACITORS);
setFilter(event, object, _ui->pageProtection, &_timer_settings_protection, TIMEOUT_UPDATE_SETTINGS_PROTECTION);
setFilter(event, object, _ui->pageFilters, &_timer_settings_filters, TIMEOUT_UPDATE_SETTINGS_FILTERS);
return QMainWindow::eventFilter(object, event);
}
void MainWindow::deviceConnected(void)
{
_ui->actionConnect->setEnabled(false);
_ui->actionDisconnect->setEnabled(true);
_ui->actionConfigure->setEnabled(false);
}
void MainWindow::deviceDisconnected(void)
{
_ui->actionConnect->setEnabled(true);
_ui->actionDisconnect->setEnabled(false);
_ui->actionConfigure->setEnabled(true);
}
void MainWindow::setEvents(std::list<EventRecord> ev)
{
foreach (EventRecord event, ev)
{
if (event.unix_time_s_ms >= _last_index_events)
{
_last_index_events = event.unix_time_s_ms + 1;
}
if (_last_index_events > TIME_MAX_VALUE)
{
_last_index_events = 0;
}
char Phases[3] = {'A', 'B', 'C'};
std::string ADCchannels[] = {
"ADC_UD",
"ADC_U_A",
"ADC_U_B",
"ADC_U_C",
"ADC_I_A",
"ADC_I_B",
"ADC_I_C",
"ADC_I_ET",
"ADC_I_TEMP1",
"ADC_I_TEMP2",
"ADC_EMS_A",
"ADC_EMS_B",
"ADC_EMS_C",
"ADC_EMS_I",
};
std::stringstream message_stream;
message_stream << std::fixed << std::setprecision(2);
SubEventPower subtype = static_cast<SubEventPower>((event.type >> 16) & 0xFFFF);
QDateTime timestamp;
timestamp.setTime_t(static_cast<uint>(event.unix_time_s_ms / 1000));
std::stringstream date_stream;
date_stream << timestamp.toString("dd.MM.yyyy hh:mm:ss").toStdString();
date_stream << ".";
date_stream << std::setfill('0') << std::setw(4);
date_stream << event.unix_time_s_ms % 1000;
message_stream << stringWithColor(date_stream.str(), LIGHT_GREY);
switch (static_cast<EventType>(event.type & 0xFFFF))
{
case EventType::EVENT_TYPE_POWER:
message_stream << stringWithColor(" - Power - ", DARK_GREEN);
switch (subtype)
{
case SubEventPower::SUB_EVENT_TYPE_POWER_ON:
message_stream << "Power ON";
break;
default:
message_stream << stringWithColor(" - Unknown event! ", DARK_RED);
break;
}
break;
case EventType::EVENT_TYPE_CHANGESTATE:
message_stream << stringWithColor(" - State - ", DARK_GREEN);
switch (static_cast<PFCstate>(subtype))
{
case PFCstate::PFC_STATE_INIT:
message_stream << STRING_PFC_STATE_INIT;
break;
case PFCstate::PFC_STATE_STOP:
message_stream << STRING_PFC_STATE_STOP;
break;
case PFCstate::PFC_STATE_SYNC:
message_stream << STRING_PFC_STATE_SYNC;
break;
case PFCstate::PFC_STATE_PRECHARGE_PREPARE:
message_stream << STRING_PFC_STATE_PRECHARGE_PREPARE;
break;
case PFCstate::PFC_STATE_PRECHARGE:
message_stream << STRING_PFC_STATE_PRECHARGE;
break;
case PFCstate::PFC_STATE_MAIN:
message_stream << STRING_PFC_STATE_MAIN;
break;
case PFCstate::PFC_STATE_PRECHARGE_DISABLE:
message_stream << STRING_PFC_STATE_PRECHARGE_DISABLE;
break;
case PFCstate::PFC_STATE_WORK:
message_stream << STRING_PFC_STATE_WORK;
break;
case PFCstate::PFC_STATE_CHARGE:
message_stream << STRING_PFC_STATE_CHARGE;
break;
case PFCstate::PFC_STATE_TEST:
message_stream << STRING_PFC_STATE_TEST;
break;
case PFCstate::PFC_STATE_STOPPING:
message_stream << STRING_PFC_STATE_STOPPING;
break;
case PFCstate::PFC_STATE_FAULTBLOCK:
message_stream << stringWithColor(STRING_PFC_STATE_FAULTBLOCK, DARK_RED);
break;
default:
message_stream << STRING_PFC_STATE_UNKNOWN;
break;
}
break;
case EventType::EVENT_TYPE_PROTECTION:
message_stream << stringWithColor(" - Protection ", DARK_RED);
switch (static_cast<SubEventProtection>(subtype))
{
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_UCAP_MIN:
message_stream << " - The voltage of the capacitor is too low during operation ";
message_stream << "(" << event.info + 1 << ") : " << event.value << " V";
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_UCAP_MAX:
message_stream << " - The voltage of the capacitor is too high ";
message_stream << "(" << event.info + 1 << ") : " << event.value << " V";
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_TEMPERATURE:
message_stream << " - The temperature is too high: ";
message_stream << event.value << " °С";
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_U_MIN:
message_stream << " - The voltage is too low at the phase ";
message_stream << Phases[event.info] << ": " << event.value << " V";
break;
case SubEventProtection:: SUB_EVENT_TYPE_PROTECTION_U_MAX:
message_stream << " - The voltage is too high at the phase ";
message_stream << Phases[event.info] << ": " << event.value << " V";
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_F_MIN:
message_stream << " - The grid frequency is too low: ";
message_stream << event.value << "Гц";
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_F_MAX:
message_stream << " - The grid frequency is too high: ";
message_stream << event.value << "Гц";
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_IPFC_MAX_RMS:
message_stream << " - The RMS current exceeded the threshold on the phase ";
message_stream << Phases[event.info] << ": " << event.value << " A";
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_IAFG_MAX_PEAK:
message_stream << " - The peak current exceeded the threshold on the phase ";
message_stream << Phases[event.info] << ": " << event.value << " A";
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_PHASES:
message_stream << " - Wrong phase rotation ";
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_ADC_OVERLOAD:
message_stream << " - ADC overload on channel ";
message_stream << ADCchannels[event.info] << ": " << event.value;
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_BAD_SYNC:
message_stream << " - Synchronisation failed (The grid frequency is unstable?) ";
break;
case SubEventProtection::SUB_EVENT_TYPE_PROTECTION_IGBT:
message_stream << " - IGBT fault ";
message_stream << event.info;
break;
default:
message_stream << stringWithColor(" - Unknown event! ", DARK_RED);
break;
}
break;
case EventType::EVENT_TYPE_EVENT:
message_stream << " - Event ";
break;
}
message(MESSAGE_TYPE_STATE, MESSAGE_NORMAL, MESSAGE_TARGET_ALL,
message_stream.str());
}
}
void MainWindow::message(uint8_t type, uint8_t level, uint8_t target, std::string message)
{
std::string prefix;
QColor color = Qt::black;
switch (type)
{
case MESSAGE_TYPE_GENERAL:
prefix = stringWithColor("[GENERAL] ", DARK_GREY);
break;
case MESSAGE_TYPE_CONNECTION:
prefix = stringWithColor("[CONNECTION] ", EXTRA_LIGHT_GREY);
break;
case MESSAGE_TYPE_GLOBALFAULT:
prefix = stringWithColor("[FAULT] ", DARK_RED);
break;
case MESSAGE_TYPE_GLOBALWARNING:
prefix = stringWithColor("[WARNING] ", DARK_RED);
break;
case MESSAGE_TYPE_STATE:
prefix = stringWithColor("[STATE] ", DARK_GREEN);
break;
case MESSAGE_TYPE_CAPACITORS:
prefix = stringWithColor("[CAPACITORS] ", DARK_GREEN);
break;
case MESSAGE_TYPE_NETWORK:
prefix = stringWithColor("[NETWORK] ", DARK_GREEN);
break;
default:
break;
}
switch (level)
{
case MESSAGE_NORMAL:
break;
case MESSAGE_WARNING:
color = Qt::darkYellow;
break;
case MESSAGE_ERROR:
color = Qt::darkRed;
break;
}
prefix.append(message);
QTextDocument doc;
doc.setHtml(QString::fromStdString(prefix));
QString ss(doc.toPlainText());
if (target & MESSAGE_TARGET_DEBUG)
{
qDebug() << ss;
}
if (target & MESSAGE_TARGET_STATUS)
{
_ui->statusBar->showMessage(ss, 5000);
}
if (target & MESSAGE_TARGET_HISTORY)
{
std::string s("<font color=" + LIGHT_GREY + ">");
s.append(QDateTime::currentDateTime().toString("dd.MM.yyyy hh:mm:ss:").toStdString());
s.append("</font>");
s += prefix;
QListWidgetItem *i=new QListWidgetItem(QString::fromStdString(s), _ui->listLog);
(void)i;
}
}
MainWindow::~MainWindow(void)
{
delete _port_settings;
delete _ui;
}
void MainWindow::openSerialPort(void)
{
SettingsDialog::Settings p = _port_settings->settings();
/* Connect to the default port */
_pfc->interfaceConnectTo(p.name, p.baudRate, p.dataBits, p.parity,
p.stopBits, p.flowControl, p.localEchoEnabled);
}
void MainWindow::closeSerialPort(void)
{
_pfc->interfaceDisconnect();
}
void MainWindow::about(void)
{
QMessageBox::about(this, tr("Program info"),
tr("The <b>GUI Terminal</b> is used to control the power factor corrector (PFC). Can be connected via a serial port (RS-485 interface) to the PFC. \n"
"Author: Stanislav Karpikov [[email protected]]"));
}
void MainWindow::initInterfaceConnections(void)
{
connect(_ui->actionConnect, &QAction::triggered, this, &MainWindow::openSerialPort);
connect(_ui->actionDisconnect, &QAction::triggered, this, &MainWindow::closeSerialPort);
connect(_ui->actionQuit, &QAction::triggered, this, &MainWindow::close);
connect(_ui->actionConfigure, &QAction::triggered, _port_settings, &SettingsDialog::show);
connect(_ui->actionAbout, &QAction::triggered, this, &MainWindow::about);
connect(_ui->actionAboutQt, &QAction::triggered, qApp, &QApplication::aboutQt);
connect(_port_settings, &SettingsDialog::Appl, this, &MainWindow::openSerialPort);
connect(_ui->valueCapacitorsKp, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &MainWindow::capacitorsKpValueChanged);
connect(_ui->valueCapacitorsKi, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &MainWindow::capacitorsKiValueChanged);
connect(_ui->valueCapacitorsKd, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &MainWindow::capacitorsKdValueChanged);
connect(_ui->spinCapNominal, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &MainWindow::capacitorsNominalValueChanged);
connect(_ui->spinCapPrecharge, static_cast<void(QDoubleSpinBox::*)(double)>(&QDoubleSpinBox::valueChanged), this, &MainWindow::capacitorsPrechargeValueChanged);
connect(_ui->buttonStop, &QPushButton::clicked, this, &MainWindow::stopClicked);
connect(_ui->buttonStart, &QPushButton::clicked, this, &MainWindow::startClicked);
connect(_ui->buttonSave, &QPushButton::clicked, this, &MainWindow::saveClicked);
connect(_ui->buttonClearLog, &QPushButton::clicked, this, &MainWindow::actionClearTriggered);
connect(_ui->checkBoxChannelA, &QCheckBox::toggled, this, &MainWindow::channelACheckToggled);
connect(_ui->checkBoxChannelB, &QCheckBox::toggled, this, &MainWindow::channelBCheckToggled);
connect(_ui->checkBoxChannelC, &QCheckBox::toggled, this, &MainWindow::channelCCheckToggled);
connect(_ui->buttonChargeOn, &QPushButton::clicked, this, &MainWindow::chargeOnClicked);
connect(_ui->buttonChargeOff, &QPushButton::clicked, this, &MainWindow::chargeOffClicked);
}
void MainWindow::setNetVoltage(float ADC_UD,
float ADC_U_A,
float ADC_U_B,
float ADC_U_C,
float ADC_I_A,
float ADC_I_B,
float ADC_I_C,
float ADC_I_ET,
float ADC_I_TEMP1,
float ADC_I_TEMP2,
float ADC_EMS_A,
float ADC_EMS_B,
float ADC_EMS_C,
float ADC_EMS_I,
float ADC_MATH_A,
float ADC_MATH_B,
float ADC_MATH_C)
{
Q_UNUSED(ADC_I_ET)
Q_UNUSED(ADC_EMS_A)
Q_UNUSED(ADC_EMS_B)
Q_UNUSED(ADC_EMS_C)
Q_UNUSED(ADC_EMS_I)
filterApply(_pfc_settings->adc.ADC_U_A, ADC_U_A);
filterApply(_pfc_settings->adc.ADC_U_B, ADC_U_B);
filterApply(_pfc_settings->adc.ADC_U_C, ADC_U_C);
filterApply(_pfc_settings->adc.ADC_I_A, ADC_I_A);
filterApply(_pfc_settings->adc.ADC_I_B, ADC_I_B);
filterApply(_pfc_settings->adc.ADC_I_C, ADC_I_C);
filterApply(_pfc_settings->adc.ADC_MATH_A, ADC_MATH_A);
filterApply(_pfc_settings->adc.ADC_MATH_B, ADC_MATH_B);
filterApply(_pfc_settings->adc.ADC_MATH_C, ADC_MATH_C);
_pfc_settings->adc.ADC_UD = ADC_UD;
filterApply(_pfc_settings->adc.ADC_I_TEMP1, ADC_I_TEMP1);
filterApply(_pfc_settings->adc.ADC_I_TEMP2, ADC_I_TEMP2);
_ui->valueVoltageA->setText(QString().sprintf("% 5.0f V", static_cast<double>(_pfc_settings->adc.ADC_MATH_A)));
_ui->valueVoltageB->setText(QString().sprintf("% 5.0f V", static_cast<double>(_pfc_settings->adc.ADC_MATH_B)));
_ui->valueVoltageC->setText(QString().sprintf("% 5.0f V", static_cast<double>(_pfc_settings->adc.ADC_MATH_C)));
_ui->valueInstantCurrentA->setText(QString().sprintf("% 5.1f A", static_cast<double>(_pfc_settings->adc.ADC_I_A)));
_ui->valueInstantCurrentB->setText(QString().sprintf("% 5.1f A", static_cast<double>(_pfc_settings->adc.ADC_I_B)));
_ui->valueInstantCurrentC->setText(QString().sprintf("% 5.1f A", static_cast<double>(_pfc_settings->adc.ADC_I_C)));
_ui->valueTemperature1->setText(QString().sprintf("% 3.0f °C", static_cast<double>(_pfc_settings->adc.ADC_I_TEMP1)));
_ui->valueTemperature2->setText(QString().sprintf("% 3.0f °C", static_cast<double>(_pfc_settings->adc.ADC_I_TEMP2)));
}
void MainWindow::setNetVoltageRAW(float ADC_UD,
float ADC_U_A,
float ADC_U_B,
float ADC_U_C,
float ADC_I_A,
float ADC_I_B,
float ADC_I_C,
float ADC_I_ET,
float ADC_I_TEMP1,
float ADC_I_TEMP2,
float ADC_EMS_A,
float ADC_EMS_B,
float ADC_EMS_C,
float ADC_EMS_I)
{
Q_UNUSED(ADC_I_ET)
Q_UNUSED(ADC_EMS_A)
Q_UNUSED(ADC_EMS_B)
Q_UNUSED(ADC_EMS_C)
Q_UNUSED(ADC_EMS_I)
filterApply(_pfc_settings->adc_raw.ADC_U_A, ADC_U_A);
filterApply(_pfc_settings->adc_raw.ADC_U_B, ADC_U_B);
filterApply(_pfc_settings->adc_raw.ADC_U_C, ADC_U_C);
filterApply(_pfc_settings->adc_raw.ADC_I_A, ADC_I_A);
filterApply(_pfc_settings->adc_raw.ADC_I_B, ADC_I_B);
filterApply(_pfc_settings->adc_raw.ADC_I_C, ADC_I_C);
filterApply(_pfc_settings->adc_raw.ADC_UD, ADC_UD);
filterApply(_pfc_settings->adc_raw.ADC_I_TEMP1, ADC_I_TEMP1);
filterApply(_pfc_settings->adc_raw.ADC_I_TEMP2, ADC_I_TEMP2);
}
void MainWindow::setNetParams(
float period_fact,
float U0Hz_A,
float U0Hz_B,
float U0Hz_C,
float I0Hz_A,
float I0Hz_B,
float I0Hz_C,
float thdu_A,
float thdu_B,
float thdu_C,
float U_phase_A,
float U_phase_B,
float U_phase_C)
{
_pfc_settings->net_params.period_fact = period_fact;
_pfc_settings->net_params.U0Hz_A = U0Hz_A;
_pfc_settings->net_params.U0Hz_B = U0Hz_B;
_pfc_settings->net_params.U0Hz_C = U0Hz_C;
_pfc_settings->net_params.I0Hz_A = I0Hz_A;
_pfc_settings->net_params.I0Hz_B = I0Hz_B;
_pfc_settings->net_params.I0Hz_C = I0Hz_C;
_pfc_settings->net_params.thdu_A = thdu_A;
_pfc_settings->net_params.thdu_B = thdu_B;
_pfc_settings->net_params.thdu_C = thdu_C;
_pfc_settings->net_params.U_phase_A = U_phase_A * 360.0f / 3.1416f;
_pfc_settings->net_params.U_phase_B = U_phase_B * 360.0f / 3.1416f;
_pfc_settings->net_params.U_phase_C = U_phase_C * 360.0f / 3.1416f;
_ui->valuePhaseAB->setText(QString().sprintf("% 5.1f°", static_cast<double>(_pfc_settings->net_params.U_phase_B)));
_ui->valuePhaseBC->setText(QString().sprintf("% 5.1f°", static_cast<double>(_pfc_settings->net_params.U_phase_C)));
_ui->valueTHDUA->setText(QString().sprintf("% 5.2f°", static_cast<double>(_pfc_settings->net_params.thdu_A)));
_ui->valueTHDUB->setText(QString().sprintf("% 5.2f°", static_cast<double>(_pfc_settings->net_params.thdu_B)));
_ui->valueTHDUC->setText(QString().sprintf("% 5.2f°", static_cast<double>(_pfc_settings->net_params.thdu_C)));
_ui->valueFrequency->setText(QString().sprintf("% 6.3f Hz", static_cast<double>(1.0f / (_pfc_settings->net_params.period_fact / 1000000.0f))));
}
void MainWindow::ansSettingsCalibrations(bool writed)
{
Q_UNUSED(writed)
}
void MainWindow::ansSettingsProtection(bool writed)
{
Q_UNUSED(writed)
}
void MainWindow::ansSettingsCapacitors(bool writed)
{
Q_UNUSED(writed)
}
void MainWindow::stopClicked(void)
{
emit writeSwitchOnOff(PFCCommands::COMMAND_WORK_OFF, 0);
}
void MainWindow::startClicked(void)
{
emit writeSwitchOnOff(PFCCommands::COMMAND_WORK_ON, 0);
}
void MainWindow::setSwitchOnOff(uint32_t result)
{
Q_UNUSED(result)
}
void MainWindow::saveClicked(void)
{
writeSwitchOnOff(PFCCommands::COMMAND_SETTINGS_SAVE, 0);
}
void MainWindow::actionClearTriggered(void)
{
_ui->listLog->clear();
}
void MainWindow::channelACheckToggled(bool checked)
{
emit writeSwitchOnOff(PFCCommands::COMMAND_CHANNEL0_DATA, checked);
}
void MainWindow::channelBCheckToggled(bool checked)
{
emit writeSwitchOnOff(PFCCommands::COMMAND_CHANNEL1_DATA, checked);
}
void MainWindow::channelCCheckToggled(bool checked)
{
emit writeSwitchOnOff(PFCCommands::COMMAND_CHANNEL2_DATA, checked);
}
void MainWindow::chargeOnClicked(void)
{
emit writeSwitchOnOff(PFCCommands::COMMAND_CHARGE_ON, 0);
}
void MainWindow::chargeOffClicked(void)
{
emit writeSwitchOnOff(PFCCommands::COMMAND_CHARGE_OFF, 0);
}
| [
"[email protected]"
] | |
5590c9b5c79352f69a8a54d2082ed35cef911f40 | ce92a946f9cf572d06510de1f0a0da1f2b2a706a | /source/expression_tree_parser.cpp | f8996fde95f78d120c30ac8cf3a4f93f7f2a38fa | [] | no_license | jakisa/stork | 942bb9103ef5f3209caab65c70c6aedd8d7f178d | ef550667fa735dcf0a4b042b48075b29879a2d4e | refs/heads/master | 2023-05-01T17:34:22.364822 | 2022-06-02T08:30:15 | 2022-06-02T08:30:15 | 229,492,797 | 92 | 34 | null | 2023-04-24T01:56:10 | 2019-12-21T22:56:19 | C++ | UTF-8 | C++ | false | false | 18,117 | cpp | #include "expression_tree_parser.hpp"
#include "expression_tree.hpp"
#include "tokenizer.hpp"
#include "errors.hpp"
#include <stack>
namespace stork {
namespace {
enum struct operator_precedence {
brackets,
postfix,
prefix,
multiplication,
addition,
shift,
comparison,
equality,
bitwise_and,
bitwise_xor,
bitwise_or,
logical_and,
logical_or,
assignment,
comma
};
enum struct operator_associativity {
left_to_right,
right_to_left
};
struct operator_info {
node_operation operation;
operator_precedence precedence;
operator_associativity associativity;
int number_of_operands;
size_t line_number;
size_t char_index;
operator_info(node_operation operation, size_t line_number, size_t char_index) :
operation(operation),
line_number(line_number),
char_index(char_index)
{
switch (operation) {
case node_operation::init:
precedence = operator_precedence::brackets;
break;
case node_operation::param: // This will never happen. Used only for the node creation.
case node_operation::postinc:
case node_operation::postdec:
case node_operation::index:
case node_operation::call:
precedence = operator_precedence::postfix;
break;
case node_operation::preinc:
case node_operation::predec:
case node_operation::positive:
case node_operation::negative:
case node_operation::bnot:
case node_operation::lnot:
case node_operation::size:
case node_operation::tostring:
precedence = operator_precedence::prefix;
break;
case node_operation::mul:
case node_operation::div:
case node_operation::idiv:
case node_operation::mod:
precedence = operator_precedence::multiplication;
break;
case node_operation::add:
case node_operation::sub:
case node_operation::concat:
precedence = operator_precedence::addition;
break;
case node_operation::bsl:
case node_operation::bsr:
precedence = operator_precedence::shift;
break;
case node_operation::lt:
case node_operation::gt:
case node_operation::le:
case node_operation::ge:
precedence = operator_precedence::comparison;
break;
case node_operation::eq:
case node_operation::ne:
precedence = operator_precedence::equality;
break;
case node_operation::band:
precedence = operator_precedence::bitwise_and;
break;
case node_operation::bxor:
precedence = operator_precedence::bitwise_xor;
break;
case node_operation::bor:
precedence = operator_precedence::bitwise_or;
break;
case node_operation::land:
precedence = operator_precedence::logical_and;
break;
case node_operation::lor:
precedence = operator_precedence::logical_or;
break;
case node_operation::assign:
case node_operation::add_assign:
case node_operation::sub_assign:
case node_operation::mul_assign:
case node_operation::div_assign:
case node_operation::idiv_assign:
case node_operation::mod_assign:
case node_operation::band_assign:
case node_operation::bor_assign:
case node_operation::bxor_assign:
case node_operation::bsl_assign:
case node_operation::bsr_assign:
case node_operation::concat_assign:
case node_operation::ternary:
precedence = operator_precedence::assignment;
break;
case node_operation::comma:
precedence = operator_precedence::comma;
break;
}
switch (precedence) {
case operator_precedence::prefix:
case operator_precedence::assignment:
associativity = operator_associativity::right_to_left;
break;
default:
associativity = operator_associativity::left_to_right;
break;
}
switch (operation) {
case node_operation::init:
number_of_operands = 0; //zero or more
break;
case node_operation::postinc:
case node_operation::postdec:
case node_operation::preinc:
case node_operation::predec:
case node_operation::positive:
case node_operation::negative:
case node_operation::bnot:
case node_operation::lnot:
case node_operation::size:
case node_operation::tostring:
case node_operation::call: //at least one
number_of_operands = 1;
break;
case node_operation::ternary:
number_of_operands = 3;
break;
default:
number_of_operands = 2;
break;
}
}
};
operator_info get_operator_info(reserved_token token, bool prefix, size_t line_number, size_t char_index) {
switch(token) {
case reserved_token::inc:
return prefix ? operator_info(node_operation::preinc, line_number, char_index)
: operator_info(node_operation::postinc, line_number, char_index);
case reserved_token::dec:
return prefix ? operator_info(node_operation::predec, line_number, char_index)
: operator_info(node_operation::postdec, line_number, char_index);
case reserved_token::add:
return prefix ? operator_info(node_operation::positive, line_number, char_index)
: operator_info(node_operation::add, line_number, char_index);
case reserved_token::sub:
return prefix ? operator_info(node_operation::negative, line_number, char_index)
: operator_info(node_operation::sub, line_number, char_index);
case reserved_token::concat:
return operator_info(node_operation::concat, line_number, char_index);
case reserved_token::mul:
return operator_info(node_operation::mul, line_number, char_index);
case reserved_token::div:
return operator_info(node_operation::div, line_number, char_index);
case reserved_token::idiv:
return operator_info(node_operation::idiv, line_number, char_index);
case reserved_token::mod:
return operator_info(node_operation::mod, line_number, char_index);
case reserved_token::bitwise_not:
return operator_info(node_operation::bnot, line_number, char_index);
case reserved_token::bitwise_and:
return operator_info(node_operation::band, line_number, char_index);
case reserved_token::bitwise_or:
return operator_info(node_operation::bor, line_number, char_index);
case reserved_token::bitwise_xor:
return operator_info(node_operation::bxor, line_number, char_index);
case reserved_token::shiftl:
return operator_info(node_operation::bsl, line_number, char_index);
case reserved_token::shiftr:
return operator_info(node_operation::bsr, line_number, char_index);
case reserved_token::assign:
return operator_info(node_operation::assign, line_number, char_index);
case reserved_token::add_assign:
return operator_info(node_operation::add_assign, line_number, char_index);
case reserved_token::sub_assign:
return operator_info(node_operation::sub_assign, line_number, char_index);
case reserved_token::concat_assign:
return operator_info(node_operation::concat_assign, line_number, char_index);
case reserved_token::mul_assign:
return operator_info(node_operation::mod_assign, line_number, char_index);
case reserved_token::div_assign:
return operator_info(node_operation::div_assign, line_number, char_index);
case reserved_token::idiv_assign:
return operator_info(node_operation::idiv_assign, line_number, char_index);
case reserved_token::mod_assign:
return operator_info(node_operation::mod_assign, line_number, char_index);
case reserved_token::and_assign:
return operator_info(node_operation::band_assign, line_number, char_index);
case reserved_token::or_assign:
return operator_info(node_operation::bor_assign, line_number, char_index);
case reserved_token::xor_assign:
return operator_info(node_operation::bxor_assign, line_number, char_index);
case reserved_token::shiftl_assign:
return operator_info(node_operation::bsl_assign, line_number, char_index);
case reserved_token::shiftr_assign:
return operator_info(node_operation::bsr_assign, line_number, char_index);
case reserved_token::logical_not:
return operator_info(node_operation::lnot, line_number, char_index);
case reserved_token::logical_and:
return operator_info(node_operation::land, line_number, char_index);
case reserved_token::logical_or:
return operator_info(node_operation::lor, line_number, char_index);
case reserved_token::eq:
return operator_info(node_operation::eq, line_number, char_index);
case reserved_token::ne:
return operator_info(node_operation::ne, line_number, char_index);
case reserved_token::lt:
return operator_info(node_operation::lt, line_number, char_index);
case reserved_token::gt:
return operator_info(node_operation::gt, line_number, char_index);
case reserved_token::le:
return operator_info(node_operation::le, line_number, char_index);
case reserved_token::ge:
return operator_info(node_operation::ge, line_number, char_index);
case reserved_token::question:
return operator_info(node_operation::ternary, line_number, char_index);
case reserved_token::comma:
return operator_info(node_operation::comma, line_number, char_index);
case reserved_token::open_round:
return operator_info(node_operation::call, line_number, char_index);
case reserved_token::open_square:
return operator_info(node_operation::index, line_number, char_index);
case reserved_token::kw_sizeof:
return operator_info(node_operation::size, line_number, char_index);
case reserved_token::kw_tostring:
return operator_info(node_operation::tostring, line_number, char_index);
case reserved_token::open_curly:
return operator_info(node_operation::init, line_number, char_index);
default:
throw unexpected_syntax_error(std::to_string(token), line_number, char_index);
}
}
bool is_end_of_expression(const token& t, bool allow_comma) {
if (t.is_eof()) {
return true;
}
if (t.is_reserved_token()) {
switch (t.get_reserved_token()) {
case reserved_token::semicolon:
case reserved_token::close_round:
case reserved_token::close_square:
case reserved_token::close_curly:
case reserved_token::colon:
return true;
case reserved_token::comma:
return !allow_comma;
default:
return false;
}
}
return false;
}
bool is_evaluated_before(const operator_info& l, const operator_info& r) {
return l.associativity == operator_associativity::left_to_right ? l.precedence <= r.precedence : l.precedence < r.precedence;
}
void pop_one_operator(
std::stack<operator_info>& operator_stack, std::stack<node_ptr>& operand_stack,
compiler_context& context, size_t line_number, size_t char_index
) {
if (operand_stack.size() < operator_stack.top().number_of_operands) {
throw compiler_error("Failed to parse an expression", line_number, char_index);
}
std::vector<node_ptr> operands;
operands.resize(operator_stack.top().number_of_operands);
if (operator_stack.top().precedence != operator_precedence::prefix) {
operator_stack.top().line_number = operand_stack.top()->get_line_number();
operator_stack.top().char_index = operand_stack.top()->get_char_index();
}
for (int i = operator_stack.top().number_of_operands - 1; i >= 0; --i) {
operands[i] = std::move(operand_stack.top());
operand_stack.pop();
}
operand_stack.push(std::make_unique<node>(
context, operator_stack.top().operation, std::move(operands), operator_stack.top().line_number, operator_stack.top().char_index)
);
operator_stack.pop();
}
node_ptr parse_expression_tree_impl(compiler_context& context, tokens_iterator& it, bool allow_comma, bool allow_empty) {
std::stack<node_ptr> operand_stack;
std::stack<operator_info> operator_stack;
bool expected_operand = true;
for (; !is_end_of_expression(*it, allow_comma); ++it) {
if (it->is_reserved_token()) {
operator_info oi = get_operator_info(
it->get_reserved_token(), expected_operand, it->get_line_number(), it->get_char_index()
);
if (oi.operation == node_operation::call && expected_operand) {
//open round bracket is misinterpreted as a function call
++it;
operand_stack.push(parse_expression_tree_impl(context, it, true, false));
if (it->has_value(reserved_token::close_round)) {
expected_operand = false;
continue;
} else {
throw syntax_error("Expected closing ')'", it->get_line_number(), it->get_char_index());
}
}
if (oi.operation == node_operation::init && expected_operand) {
++it;
std::vector<node_ptr> children;
if (!it->has_value(reserved_token::close_curly)) {
while (true) {
children.push_back(parse_expression_tree_impl(context, it, false, false));
if (it->has_value(reserved_token::close_curly)) {
break;
} else if (it->has_value(reserved_token::comma)) {
++it;
} else {
throw syntax_error("Expected ',', or closing '}'", it->get_line_number(), it->get_char_index());
}
}
}
operand_stack.push(std::make_unique<node>(
context,
node_operation::init,
std::move(children),
it->get_line_number(),
it->get_char_index()
));
expected_operand = false;
continue;
}
if ((oi.precedence == operator_precedence::prefix) != expected_operand) {
throw unexpected_syntax_error(
std::to_string(it->get_value()),
it->get_line_number(),
it->get_char_index()
);
}
if (!operator_stack.empty() && is_evaluated_before(operator_stack.top(), oi)) {
pop_one_operator(operator_stack, operand_stack, context, it->get_line_number(), it->get_char_index());
}
switch (oi.operation) {
case node_operation::call:
++it;
if (!it->has_value(reserved_token::close_round)) {
while (true) {
bool remove_lvalue = !it->has_value(reserved_token::bitwise_and);
if (!remove_lvalue) {
++it;
}
node_ptr argument = parse_expression_tree_impl(context, it, false, false);
if (remove_lvalue) {
size_t line_number = argument->get_line_number();
size_t char_index = argument->get_char_index();
std::vector<node_ptr> argument_vector;
argument_vector.push_back(std::move(argument));
argument = std::make_unique<node>(
context,
node_operation::param,
std::move(argument_vector),
line_number,
char_index
);
} else if (!argument->is_lvalue()) {
throw wrong_type_error(
std::to_string(argument->get_type_id()),
std::to_string(argument->get_type_id()),
true,
argument->get_line_number(),
argument->get_char_index()
);
}
operand_stack.push(std::move(argument));
++oi.number_of_operands;
if (it->has_value(reserved_token::close_round)) {
break;
} else if (it->has_value(reserved_token::comma)) {
++it;
} else {
throw syntax_error("Expected ',', or closing ')'", it->get_line_number(), it->get_char_index());
}
}
}
break;
case node_operation::index:
++it;
operand_stack.push(parse_expression_tree_impl(context, it, true, false));
if (!it->has_value(reserved_token::close_square)) {
throw syntax_error("Expected closing ]'", it->get_line_number(), it->get_char_index());
}
break;
case node_operation::ternary:
++it;
operand_stack.push(parse_expression_tree_impl(context, it, true, false));
if (!it->has_value(reserved_token::colon)) {
throw syntax_error("Expected ':'", it->get_line_number(), it->get_char_index());
}
break;
default:
break;
}
operator_stack.push(oi);
expected_operand = (oi.precedence != operator_precedence::postfix);
} else {
if (!expected_operand) {
throw unexpected_syntax_error(
std::to_string(it->get_value()),
it->get_line_number(),
it->get_char_index()
);
}
if (it->is_number()) {
operand_stack.push(std::make_unique<node>(
context, it->get_number(), std::vector<node_ptr>(), it->get_line_number(), it->get_char_index())
);
} else if (it->is_string()) {
operand_stack.push(std::make_unique<node>(
context, it->get_string(), std::vector<node_ptr>(), it->get_line_number(), it->get_char_index())
);
} else {
operand_stack.push(std::make_unique<node>(
context, it->get_identifier(), std::vector<node_ptr>(), it->get_line_number(), it->get_char_index())
);
}
expected_operand = false;
}
}
if (expected_operand) {
if (allow_empty && operand_stack.empty() && operator_stack.empty()) {
return node_ptr();
} else {
throw syntax_error("Operand expected", it->get_line_number(), it->get_char_index());
}
}
while(!operator_stack.empty()) {
pop_one_operator(operator_stack, operand_stack, context, it->get_line_number(), it->get_char_index());
}
if (operand_stack.size() != 1 || !operator_stack.empty()) {
throw compiler_error("Failed to parse an expression", it->get_line_number(), it->get_char_index());
}
return std::move(operand_stack.top());
}
}
node_ptr parse_expression_tree(
compiler_context& context, tokens_iterator& it, type_handle type_id, bool allow_comma
) {
node_ptr ret = parse_expression_tree_impl(context, it, allow_comma, type_id == type_registry::get_void_handle());
if (ret) {
ret->check_conversion(type_id, false);
}
return ret;
}
}
| [
"[email protected]"
] | |
7ce5ee59aa48fc8796869c58885410c13851d2cd | 91b36a305a65a601f93fad94ef19b995db6e5d83 | /NativePlugin/Src/Runtime/ParticleSystem/PolynomialCurve.h | 1dd57ec4813f12e7e589dc6b923886b1055dec3c | [] | no_license | maksym-pasichnyk/NativeParticleSystem | 0d79d093ef1144f60afb941d1928546005ebca62 | 35187e5d9a43e7db5264d1f953f4383873d3decf | refs/heads/master | 2021-12-14T15:41:24.820604 | 2017-05-10T16:42:23 | 2017-05-10T16:42:23 | 437,383,171 | 1 | 1 | null | 2021-12-11T20:34:42 | 2021-12-11T20:34:41 | null | UTF-8 | C++ | false | false | 6,848 | h | #ifndef POLYONOMIAL_CURVE_H
#define POLYONOMIAL_CURVE_H
template<class T>
class AnimationCurveTpl;
typedef AnimationCurveTpl<float> AnimationCurve;
class Vector2f;
struct Polynomial
{
static float EvalSegment (float t, const float* coeff)
{
return (t * (t * (t * coeff[0] + coeff[1]) + coeff[2])) + coeff[3];
}
float coeff[4];
};
// Smaller, optimized version
struct OptimizedPolynomialCurve
{
enum { kMaxPolynomialKeyframeCount = 3, kSegmentCount = kMaxPolynomialKeyframeCount-1, };
Polynomial segments[kSegmentCount];
float timeValue;
float velocityValue;
// Evaluate double integrated Polynomial curve.
// Example: position = EvaluateDoubleIntegrated (normalizedTime) * startEnergy^2
// Use DoubleIntegrate function to for example turn a force curve into a position curve.
// Expects that t is in the 0...1 range.
float EvaluateDoubleIntegrated (float t) const
{
float res0, res1;
// All segments are added together. At t = 0, the integrated curve is always zero.
// 0 segment is sampled up to the 1 keyframe
// First key is always assumed to be at 0 time
float t1 = std::min(t, timeValue);
// 1 segment is sampled from 1 key to 2 key
// Last key is always assumed to be at 1 time
float t2 = std::max(0.0F, t - timeValue);
res0 = Polynomial::EvalSegment(t1, segments[0].coeff) * t1 * t1;
res1 = Polynomial::EvalSegment(t2, segments[1].coeff) * t2 * t2;
float finalResult = res0 + res1;
// Add velocity of previous segments
finalResult += velocityValue * std::max(t - timeValue, 0.0F);
return finalResult;
}
// Evaluate integrated Polynomial curve.
// Example: position = EvaluateIntegrated (normalizedTime) * startEnergy
// Use Integrate function to for example turn a velocity curve into a position curve.
// Expects that t is in the 0...1 range.
float EvaluateIntegrated (float t) const
{
float res0, res1;
// All segments are added together. At t = 0, the integrated curve is always zero.
// 0 segment is sampled up to the 1 keyframe
// First key is always assumed to be at 0 time
float t1 = std::min(t, timeValue);
// 1 segment is sampled from 1 key to 2 key
// Last key is always assumed to be at 1 time
float t2 = std::max(0.0F, t - timeValue);
res0 = Polynomial::EvalSegment(t1, segments[0].coeff) * t1;
res1 = Polynomial::EvalSegment(t2, segments[1].coeff) * t2;
return (res0 + res1);
}
// Evaluate the curve
// extects that t is in the 0...1 range
float Evaluate (float t) const
{
float res0 = Polynomial::EvalSegment(t, segments[0].coeff);
float res1 = Polynomial::EvalSegment(t - timeValue, segments[1].coeff);
float result;
if (t > timeValue)
result = res1;
else
result = res0;
return result;
}
// Find the maximum of a double integrated curve (x: min, y: max)
Vector2f FindMinMaxDoubleIntegrated() const;
// Find the maximum of the integrated curve (x: min, y: max)
Vector2f FindMinMaxIntegrated() const;
// Precalculates polynomials from the animation curve and a scale factor
bool BuildOptimizedCurve (const AnimationCurve& editorCurve, float scale);
// Integrates a velocity curve to be a position curve.
// You have to call EvaluateIntegrated to evaluate the curve
void Integrate ();
// Integrates a velocity curve to be a position curve.
// You have to call EvaluateDoubleIntegrated to evaluate the curve
void DoubleIntegrate ();
// Add a constant force to a velocity curve
// Assumes that you have already called Integrate on the velocity curve.
void AddConstantForceToVelocityCurve (float gravity)
{
for (int i=0;i<kSegmentCount;i++)
segments[i].coeff[1] += 0.5F * gravity;
}
};
// Bigger, not so optimized version
struct PolynomialCurve
{
enum{ kMaxNumSegments = 8 };
Polynomial segments[kMaxNumSegments]; // Cached polynomial coefficients
float integrationCache[kMaxNumSegments]; // Cache of integrated values up until start of segments
float doubleIntegrationCache[kMaxNumSegments]; // Cache of double integrated values up until start of segments
float times[kMaxNumSegments]; // Time value for end of segment
int segmentCount;
// Find the maximum of a double integrated curve (x: min, y: max)
Vector2f FindMinMaxDoubleIntegrated() const;
// Find the maximum of the integrated curve (x: min, y: max)
Vector2f FindMinMaxIntegrated() const;
// Precalculates polynomials from the animation curve and a scale factor
bool BuildCurve(const AnimationCurve& editorCurve, float scale);
// Integrates a velocity curve to be a position curve.
// You have to call EvaluateIntegrated to evaluate the curve
void Integrate ();
// Integrates a velocity curve to be a position curve.
// You have to call EvaluateDoubleIntegrated to evaluate the curve
void DoubleIntegrate ();
// Evaluates if it is possible to represent animation curve as PolynomialCurve
static bool IsValidCurve(const AnimationCurve& editorCurve);
// Evaluate double integrated Polynomial curve.
// Example: position = EvaluateDoubleIntegrated (normalizedTime) * startEnergy^2
// Use DoubleIntegrate function to for example turn a force curve into a position curve.
// Expects that t is in the 0...1 range.
float EvaluateDoubleIntegrated (float t) const
{
float prevTimeValue = 0.0f;
for(int i = 0; i < segmentCount; i++)
{
if(t <= times[i])
{
const float time = t - prevTimeValue;
return doubleIntegrationCache[i] + integrationCache[i] * time + Polynomial::EvalSegment(time, segments[i].coeff) * time * time;
}
prevTimeValue = times[i];
}
return 1.0f;
}
// Evaluate integrated Polynomial curve.
// Example: position = EvaluateIntegrated (normalizedTime) * startEnergy
// Use Integrate function to for example turn a velocity curve into a position curve.
// Expects that t is in the 0...1 range.
float EvaluateIntegrated (float t) const
{
float prevTimeValue = 0.0f;
for(int i = 0; i < segmentCount; i++)
{
if(t <= times[i])
{
const float time = t - prevTimeValue;
return integrationCache[i] + Polynomial::EvalSegment(time, segments[i].coeff) * time;
}
prevTimeValue = times[i];
}
return 1.0f;
}
// Evaluate the curve
// extects that t is in the 0...1 range
float Evaluate(float t) const
{
float prevTimeValue = 0.0f;
for(int i = 0; i < segmentCount; i++)
{
if(t <= times[i])
return Polynomial::EvalSegment(t - prevTimeValue, segments[i].coeff);
prevTimeValue = times[i];
}
return 1.0f;
}
};
void SetPolynomialCurveToValue (AnimationCurve& a, OptimizedPolynomialCurve& c, float value);
void SetPolynomialCurveToLinear (AnimationCurve& a, OptimizedPolynomialCurve& c);
void ConstrainToPolynomialCurve (AnimationCurve& curve);
bool IsValidPolynomialCurve (const AnimationCurve& curve);
void CalculateMinMax(Vector2f& minmax, float value);
#endif // POLYONOMIAL_CURVE_H
| [
"[email protected]"
] | |
0b018ff1bb231a960a93ca884685df4bcdd0038d | 1d6cb5a6342532e98fb1c7216a34a41eb080640d | /Unreal/Src/Game/UnCon.cpp | e1ff9c66e94706f9a73753f7ff4ff2e7cb82e571 | [] | no_license | hogsy/unreal83 | 85b6e196057d605918d323dbf37562956e1b58ce | 935fa60ab391955490b626d1a45849b3f642efa7 | refs/heads/master | 2021-12-22T10:16:26.408589 | 2021-12-19T21:04:26 | 2021-12-19T21:04:26 | 216,208,620 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 36,227 | cpp | /*=============================================================================
UnCon.cpp: Implementation of FCameraConsole class
Copyright 1996 Epic MegaGames, Inc. This software is a trade secret.
Compiled with Visual C++ 4.0. Best viewed with Tabs=4.
Contains routines for: Messages, menus, status bar
=============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdarg.h>
#include "UnGame.h"
#include "UnCon.h"
#include "UnRender.h"
#include "UnAction.h"
#include "UnCheat.h"
#include "UnFActor.h"
/*------------------------------------------------------------------------------
Globals
------------------------------------------------------------------------------*/
//
// These defines give the size of the displayable status bar graphics, because
// the status bar textures are forced to power-of-two sizes.
//
#define STATUSBAR_U 640.0
//obsolete: #define STATUSBAR_V 58.0
#define STATUSBAR_V 64.0
//obsolete:#define EXTRABAR_U 640.0
//obsolete:#define EXTRABAR_V 32.0 /*18.0*/
// Specification of locations of parts of the status bars:
//obsolete: static const FLOAT HealthImageX = 362.0; // Relative to left of status bar.
//obsolete: static const FLOAT HealthImageY = 0.0; // Relative to top of status bar.
static const FLOAT ArmorValueX = 90.0; // Relative to left of status bar.
static const FLOAT HealthValueX = 281.0; // Relative to left of status bar.
static const FLOAT AmmoValueX = 472.0; // Relative to left of status bar.
static const FLOAT HealthValueY = 31.0; // Relative to top of status bar.
static const FLOAT ArmorValueY = 31.0; // Relative to top of status bar.
static const FLOAT AmmoValueY = 31.0; // Relative to top of status bar.
static const FLOAT ArmorImageX = 4.0; // Relative to left of status bar.
static const FLOAT ArmorImageY = 4.0; // Relative to top of status bar.
static const FLOAT AmmoImageX = 560.0; // Relative to left of status bar.
static const FLOAT AmmoImageY = 0.0; // Relative to top of status bar.
// Location of lights:
struct TLightPosition
{
FLOAT X;
FLOAT Y;
};
static const TLightPosition StatusSmallLightPositions[] =
{
{ 43.0 , 4.0 }
, { 64.0 , 4.0 }
, { 87.0 , 4.0 }
, { 108.0 , 4.0 }
, { 130.0 , 4.0 }
, { 175.0 , 4.0 }
, { 197.0 , 4.0 }
, { 218.0 , 4.0 }
, { 241.0 , 4.0 }
, { 263.0 , 4.0 }
};
static const TLightPosition StatusLightPositions[] =
{
{ 84.0 , 6.0 }
, { 128.0 , 6.0 }
, { 173.0 , 6.0 }
, { 216.0 , 6.0 }
, { 259.0 , 6.0 }
, { 349.0 , 6.0 }
, { 392.0 , 6.0 }
, { 436.0 , 6.0 }
, { 481.0 , 6.0 }
, { 525.0 , 6.0 }
};
// Inventory icons appear in the thin status bar:
static const FLOAT InventoryIconsX = 2.0; // Relative to left of status bar.
static const FLOAT InventoryIconsY = 2.0; // Relative to top of status bar.
/*------------------------------------------------------------------------------
Initializing and exiting a console
------------------------------------------------------------------------------*/
//
// Init console for a particular camera. Should be called immediately
// when a new camera is created and recognized.
//
void FCameraConsole::Init(UCamera *ThisCamera)
{
GUARD;
//
Camera = ThisCamera;
//
KeyState = CK_None;
HistoryTop = 0;
HistoryCur = 0;
for (int i=0; i<MAX_HISTORY; i++) *History[i]=0;
//
NumLines = 0;
TopLine = MAX_LINES-1;
MsgStart = 0;
MsgDuration = 0;
for (int i=0; i<MAX_LINES; i++) *MsgText[i]=0;
//
ConsolePos = 0.0;
ConsoleDest = 0.0;
//
LastTickTime = 0;
StatusRefreshPages = 2;
//
BorderSize = 1; //obsolete:2
Redraw = 0;
LogoUp = 0;
Scrollback = 0;
//
// Find all graphics resources. These are imported
// into the engine via the Graphics.mac macro and are
// stored in the game's .gfx file in the System directory.
//
StatusBar = new("StatusBar", FIND_Existing)UTexture;
StatusSmallBar = new("StatusBarS", FIND_Existing)UTexture;
StatusWeaponLight = new("StatusLight", FIND_Existing)UTexture;
StatusSmallWeaponLight = new("StatusLightS", FIND_Existing)UTexture;
//obsolete: ExtraBar = new("ExtraBar", FIND_Existing)UTexture;;
ConBackground = new("ConBackground", FIND_Existing)UTexture;
Border = new("Border", FIND_Existing)UTexture;
ArmorImages[DMT_Basic] = new("Armor1" , FIND_Existing)UTexture;
//obsolete: HealthImage = new("Health" , FIND_Existing)UTexture;
StatusDigits[0] = new("Status0" , FIND_Existing)UTexture;
StatusDigits[1] = new("Status1" , FIND_Existing)UTexture;
StatusDigits[2] = new("Status2" , FIND_Existing)UTexture;
StatusDigits[3] = new("Status3" , FIND_Existing)UTexture;
StatusDigits[4] = new("Status4" , FIND_Existing)UTexture;
StatusDigits[5] = new("Status5" , FIND_Existing)UTexture;
StatusDigits[6] = new("Status6" , FIND_Existing)UTexture;
StatusDigits[7] = new("Status7" , FIND_Existing)UTexture;
StatusDigits[8] = new("Status8" , FIND_Existing)UTexture;
StatusDigits[9] = new("Status9" , FIND_Existing)UTexture;
StatusSmallDigits[0] = new("Status0S" , FIND_Existing)UTexture;
StatusSmallDigits[1] = new("Status1S" , FIND_Existing)UTexture;
StatusSmallDigits[2] = new("Status2S" , FIND_Existing)UTexture;
StatusSmallDigits[3] = new("Status3S" , FIND_Existing)UTexture;
StatusSmallDigits[4] = new("Status4S" , FIND_Existing)UTexture;
StatusSmallDigits[5] = new("Status5S" , FIND_Existing)UTexture;
StatusSmallDigits[6] = new("Status6S" , FIND_Existing)UTexture;
StatusSmallDigits[7] = new("Status7S" , FIND_Existing)UTexture;
StatusSmallDigits[8] = new("Status8S" , FIND_Existing)UTexture;
StatusSmallDigits[9] = new("Status9S" , FIND_Existing)UTexture;
//
// Start console log:
//
SpawnConsoleMessage();
Logf("Console ready for %s",Camera->Level->ActorList->Element(Camera->iActor).Name.Name());
Logf(" ");
//
UNGUARD("FCameraConsole::Init");
};
//
// Shut down a particular camera's console. Should be called before
// closing a camera.
//
void FCameraConsole::Exit(void)
{
GUARD;
UNGUARD("FCameraConsole::Exit");
};
/*------------------------------------------------------------------------------
Utility functions
------------------------------------------------------------------------------*/
void FCameraConsole::NoteResize(void)
{
GUARD;
Redraw++;
UNGUARD("FCameraConsole::NoteResize");
};
void FCameraConsole::ClearInput(void)
{
GUARD;
//
HistoryCur = HistoryTop;
memset(TypedStr,0,sizeof(TypedStr));
//
UNGUARD("FCameraConsole::ClearInput");
};
/*------------------------------------------------------------------------------
Console command-line
------------------------------------------------------------------------------*/
int FCameraConsole::Exec(const char *Cmd,FOutputDevice *Out)
{
GUARD;
const char *Str = Cmd;
//
if (GetCMD(&Str,"STATUS") && (GetCMD(&Str,"CONSOLE") || !Str[0]))
{
Out->Logf(" CONSOLE - Owned by %s",Camera->Level->ActorList->Element(Camera->iActor).Name.Name());
return Str[0]!=0;
}
else if (GetCMD(&Str,"HIDE"))
{
Out->Log("Console hidden");
ConsoleDest = 0.0;
return 1;
}
else if (GetCMD(&Str,"SHOW"))
{
Out->Log("Console shown");
ConsoleDest = CON_SHOW;
return 1;
}
else if (GetCMD(&Str,"FULL"))
{
Out->Log("Full console view");
ConsoleDest = 1.0;
return 1;
}
else if (GetCMD(&Str,"FPS"))
{
GRend->QuickStats ^= 1; Out->Logf("Stats are %s",GRend->QuickStats?"on":"off"); return 1;
}
else if (GetCMD(&Str,"QUICKSTATS"))
{
GRend->QuickStats ^= 1;
StatusRefreshPages = 2;
return 1;
}
else if (PeekCMD(Str,"PN") || PeekCMD(Str,"PP"))
{
ICamera CameraInfo;
AActor *Actor = &Camera->GetActor();
//
int d=+1;
if (GetCMD(&Str,"PP")) d=-1;
else if (GetCMD(&Str,"PN")) d=+1;
//
UClass *DestClass;
//
if (Actor->CameraStatus.ShowFlags & SHOW_StandardView)
{
Out->Log("Must open a free camera to possess");
return 1;
};
if (!Camera->Lock(&CameraInfo)) return 1;
//
// Try to possess an available actor
//
if (GetCMD(&Str,"ALIKE")) DestClass = Actor->Class;
else DestClass = NULL;
//
int n = CameraInfo.iActor;
int Failed = 1;
//
while (1)
{
n += d;
if (n >= CameraInfo.Level.Actors->Max) n=0;
else if (n < 0) n=CameraInfo.Level.Actors->Max-1;
//
if (n == CameraInfo.iActor) break;
//
AActor *TestActor = &CameraInfo.Level.Actors->Element(n);
if (TestActor->Class && (!TestActor->Camera) && TestActor->bCanPossess && !TestActor->bHiddenEd)
{
if ((TestActor->Class == DestClass) || (DestClass == NULL))
{
CameraInfo.Level.UnpossessActor(CameraInfo.iActor);
CameraInfo.Level.PossessActor(n,Camera);
//
CameraInfo.Camera->iActor = n;
CameraInfo.iActor = n;
CameraInfo.Actor = TestActor;
//
Failed=0;
break;
};
};
};
Camera->Unlock(&CameraInfo,0);
GCameraManager->UpdateCameraWindow(Camera);
//
// Update player console window:
//
if (Failed)
{
Out->Log(LOG_Info,"Couldn't possess");
}
else
{
char Who[256];
strcpy (Who,"Possessed a ");
strcat (Who,Actor->Class->Name);
if (!Actor->Name.IsNone())
{
strcat (Who," ");
strcat (Who,Actor->Name.Name());
};
Out->Log(Who);
};
return 1;
}
else if (GetCMD(&Str,"DUMPCACHE"))
{
char Status[100];
GCache.Status(Status);
Out->Log(Status);
GCache.Dump();
GCache.AssertValid();
return 1;
}
else if (GetCMD(&Str,"CHECK"))
{
// Add any checks here...
debugf( LOG_Info, "Checking cache..." );
GCache.AssertValid();
debugf( LOG_Info, "Checking actor lists..." );
Camera->Level->ActorList->CheckLists();
return 1;
}
else if (GetCMD(&Str,"ACTORSIZES"))
{
Out->Logf( "sizeof(AI)=%i", sizeof(AActorAI) );
Out->Logf( "sizeof(ARoot)=%i", sizeof(ARoot) );
Out->Logf( "sizeof(APawn)=%i+Root", sizeof(APawn)-sizeof(ARoot) );
Out->Logf( "sizeof(ASkaarj)=%i+Root", sizeof(ASkaarj)-sizeof(ARoot) );
Out->Logf( "sizeof(ABigMan)=%i+Root", sizeof(ABigMan)-sizeof(ARoot) );
Out->Logf( "sizeof(AInventory)=%i+Root", sizeof(AInventory)-sizeof(ARoot) );
return 1;
}
else if (GetCMD(&Str,"ACTORINFO"))
{
for( int WhichActor = 0; WhichActor < Camera->Level->ActorList->Num; ++WhichActor )
{
AActor & Actor = Camera->Level->ActorList->Element(WhichActor);
if( Actor.Class != 0 )
{
char Info[100];
char * Text = Info;
const char * Name = Actor.Name.Name();
Text += sprintf( Text, "[%2i] %s %s", WhichActor, (Name!=0?Name:""), Actor.Class->Name );
Text += sprintf( Text, " %s", Actor.bStaticActor ? "s" : "!s" );
Text += sprintf( Text, ",%s", Actor.bCollideActors ? "c" : "!c" );
Text += sprintf( Text, " L:[%5.0f %5.0f %5.0f]", Actor.Location.X, Actor.Location.Y, Actor.Location.Z );
Text += sprintf( Text, " V:[%5.0f %5.0f %5.0f]", Actor.Velocity.X, Actor.Velocity.Y, Actor.Velocity.Z );
debug( LOG_Info, Info );
}
}
return 1;
}
else if
(
// Check individual characters so complete strings won't appear in the executable code.
// This makes it harder for hackers to figure out cheats by scanning for strings.
// Allow password "CHEETAH" and some abbreviations thereof...
toupper(Str[0])=='C'
&& toupper(Str[1])=='H'
&& toupper(Str[2])=='E'
&& toupper(Str[3])=='E'
&&
(
strnicmp( &Str[4], "T " ,2) == 0
|| strnicmp( &Str[4], "TA " ,3) == 0
|| strnicmp( &Str[4], "TAH " ,4) == 0
)
)
{
while( !isspace(*Str) ) { Str++; }
AActor & Actor = Camera->GetActor();
GCheat->DoCheatCommands( Str, &Actor, Camera->Level, Out );
return 1;
}
else return 0;
//
UNGUARD("FCameraConsole::Exec");
};
/*------------------------------------------------------------------------------
Camera console output
------------------------------------------------------------------------------*/
//
// Print a message on the playing screen.
// Time = time to keep message going, or 0=until next message arrives, in 60ths sec
//
void FCameraConsole::Log(ELogType ThisType, const char *Text)
{
GUARD;
//
TopLine = (TopLine+1) % MAX_LINES;
NumLines = OurMin(NumLines+1,(int)(MAX_LINES-1));
//
strncpy (MsgText[TopLine],Text,TEXTMSG_LENGTH);
MsgText[TopLine][TEXTMSG_LENGTH-1] = 0;
//
MsgType = ThisType;
MsgStart = GServer.Ticks;
MsgDuration = MESSAGE_TIME;
//
UNGUARD("FCameraConsole::Message");
};
/*------------------------------------------------------------------------------
Rendering
------------------------------------------------------------------------------*/
//
// Called before rendering the world view. Here, the
// camera console code can affect the screen's camera,
// for example by shrinking the view according to the
// size of the status bar.
//
ICamera *GSavedCamera;
void FCameraConsole::PreRender(ICamera *Camera)
{
GUARD;
// Process any console-related actions:
const BOOL FullConsole = GAction.Do(FAction::ConsoleFull);
const BOOL HalfConsole = GAction.Do(FAction::ConsoleHalf);
if( FullConsole || HalfConsole )
{
if( ConsoleDest==0 )
{
ConsoleDest = FullConsole ? 1.0 : CON_SHOW;
if (KeyState!=CK_Type) ClearInput();
KeyState = CK_Type;
}
else
{
ClearInput();
ConsoleDest = 0;
KeyState = CK_None;
}
}
if( GAction.Do(FAction::ConsoleType) )
{
ClearInput();
KeyState = CK_Type;
}
else if( GAction.Do(FAction::Chat) )
{
ClearInput();
strcpy (TypedStr,"Say ");
KeyState = CK_Type;
}
if( GAction.Do(FAction::ScreenEnlarge) )
{
if (--BorderSize<0) BorderSize=0;
}
else if( GAction.Do(FAction::ScreenShrink) )
{
if (++BorderSize>=MAX_BORDER) BorderSize=MAX_BORDER-1;
}
if( GAction.Do(FAction::ScreenShot) )
{
static int ScreenNum=0;
char Fname[256];
do {
sprintf (Fname,"Unreal%02i.PCX",ScreenNum++);
} while ((fsize(Fname)>=0) && (ScreenNum<100));
if (ScreenNum<100)
{
debugf(LOG_Info,"Saving snapshot %s",Fname);
Camera->Texture->ExportToFile(Fname);
};
}
if( GAction.Do(FAction::Pause) )
{
GServer.IsPaused = !GServer.IsPaused;
if( GServer.IsPaused )
{
// Game was just paused...
GAudio.Pause();
Log( LOG_Play, "Paused" );
//todo? Should we save any existing message and display it when unpaused?
}
else
{
// Game was just unpaused...
GAudio.UnPause();
MsgType = LOG_None; // Clear the "paused" message
}
}
//
// Update the camera console:
//
if (LastTickTime) while (LastTickTime++ < GServer.Ticks) Tick(Camera,1);
else Tick(Camera,1);
LastTickTime = GServer.Ticks;
Old->LastTickTime = GServer.Ticks; // Prevent status redraw due to LastTickTime changing
//
// Save the camera
//
GSavedCamera=(ICamera *)GMem.Get(sizeof(ICamera));
memcpy(GSavedCamera,Camera,sizeof(ICamera));
//
// Compute new status info:
//
SXR = Camera->SXR;
SYR = Camera->SYR;
BorderLines = 0;
BorderPixels = 0;
StatusBarLines = 0;
//obsolete: ExtraBarLines = 0;
ConsoleLines = 0;
//
//obsolete: Status bar is now supported in all colordepths
//if (Camera->ColorBytes!=1)
// {
// BorderSize=0;
// ConsolePos=0.0;
// };
//
// Compute sizing of all visible status bar components:
//
if (Camera->Camera->IsGame())
{
if (BorderSize>=1) // Status bar
{
StatusBarLines = OurMin((FLOAT)(Camera->FSXR * STATUSBAR_V/STATUSBAR_U),(FLOAT)SYR);
SYR -= StatusBarLines;
};
//obsolete: if (BorderSize>=2) // Extra status bar
//obsolete: {
//obsolete: ExtraBarLines = OurMin((FLOAT)(Camera->FSXR * EXTRABAR_V/EXTRABAR_U),(FLOAT)SYR);
//obsolete: SYR -= ExtraBarLines;
//obsolete: };
if (ConsolePos > 0.0) // Show console
{
ConsoleLines = OurMin(ConsolePos * (FLOAT)SYR,(FLOAT)SYR);
SYR -= ConsoleLines;
};
if (BorderSize>=2) // Encroach on screen area
{
FLOAT Fraction = (FLOAT)(BorderSize-1) / (FLOAT)(MAX_BORDER-1);
//
BorderLines = (int)OurMin((FLOAT)SYR * 0.25f * Fraction,(FLOAT)SYR);
BorderLines = OurMax(0,BorderLines - ConsoleLines);
SYR -= 2 * BorderLines;
//
BorderPixels = (int)OurMin((FLOAT)SXR * 0.25f * Fraction,(FLOAT)SXR) & ~3;
SXR -= 2 * BorderPixels;
};
Camera->Screen = &Camera->Screen
[
Camera->ColorBytes *
(BorderPixels + (ConsoleLines + BorderLines) * Camera->SXStride)
];
Camera->PrecomputeRenderInfo(SXR,SYR);
};
//
// Whether to show logo:
//
//if ((GServer.Ticks < 35*8) && Camera->Camera->IsGame()) LogoUp=1;
//else LogoUp=0;
LogoUp=0; // Logo is annoying
//
UNGUARD("FCameraConsole::PreRender");
};
// Show a numeric string with (optional) leading blanks and digits '0'-'9'.
// Updates the X position to beyond the last character shown.
static void ShowValue
(
const char * Value
, ICamera * Camera
, int & X // Updated on output
, int Y
, FLOAT XScale
, FLOAT YScale
, BOOL UseSmallImages
, UTexture * * DigitImages // An array of 10 textures for digits 0-9
)
{
while( *Value != 0 )
{
const int Spacing = XScale * (UseSmallImages ? 13.0 : 26.0 );
if( *Value == ' ' )
{
// We can't use the image sizes for spacing, since they have
// a lot of extra empty space.
X += Spacing;
}
else if( *Value >= '0' && *Value <= '9' )
{
UTexture * Image = DigitImages[*Value - '0'];
//debugf( LOG_Info, "(%3.2f %3.2f) %i %i '%c' %i %i", XScale, YScale, X, Y, *Value, int(Image->USize), int(Image->VSize) );
GRend->DrawScaledSprite
(
Camera
, Image
, X , Y
, FLOAT(Image->USize) * XScale
, FLOAT(Image->VSize) * YScale
, BT_None,NULL,0,0
);
// We can't use the image sizes for spacing, since they have
// a lot of extra empty space.
X += Spacing;
}
Value++;
}
}
// Show a numeric value 0-999 at the given position, padded on the left
// with empty space.
static void ShowValue
(
int Value // 0-999
, ICamera * Camera
, int X
, int Y
, FLOAT XScale
, FLOAT YScale
, BOOL UseSmallImages
, UTexture * * DigitImages // An array of 10 textures for digits 0-9
)
{
if( Value < 0 )
{
Value = 0;
}
else if( Value > 999 )
{
Value = 999;
}
char Text[5];
sprintf( Text, "%3i", Value );
ShowValue( Text, Camera, X, Y, XScale, YScale, UseSmallImages, DigitImages );
}
//
// Refresh the player console on the specified camera. This is called after
// all in-game graphics are drawn in the rendering loop, and it overdraws stuff
// with the status bar, menus, and chat text.
//
void FCameraConsole::PostRender(ICamera *Camera,int XLeft)
{
GUARD;
//
// Restore the previously-saved camera:
//
memcpy(Camera,GSavedCamera,sizeof(ICamera));
GMem.Release(GSavedCamera);
//
// If the console has changed since the previous frame, draw it:
//
//todo: Right now, changes in the status of the pawn are detected
// by having the pawn set bStatusChanged. This is error-prone, and
// we need to find a better way. Its not enough just to
// save ammo, health, and weapon information, we need to note
// changes in the pawn's inventory.
APawn & Pawn = (APawn&)this->Camera->GetActor(); // Camera actor is always a pawn.
const BOOL PawnStatusChanged = Pawn.bStatusChanged;
int Changed = !mymemeq(this,Old,sizeof(*this)) || PawnStatusChanged;
int DrawStatus = Changed || (StatusRefreshPages>0);
int YStart = BorderLines;
int YEnd = Camera->SYR-BorderLines-StatusBarLines;//obsolete:-ExtraBarLines;
int DrawBorder = DrawStatus || (MsgType != LOG_None) || (KeyState==CK_Type);
//
if (DrawStatus)
{
//
// Output a debugging string if we're updating the status bar. This is useful
// when expanding the status bar logic, because you need to make sure the status
// bar is only being redrawn when necessary, or else the game will run slowly.
//
//bug("Updating status bar"); /* For debugging */
//
if (Changed) StatusRefreshPages = 2; // Handle proper refresh in triple-buffered mode
else StatusRefreshPages--;
//
// Draw status bar:
//
if (StatusBarLines>0)
{
const FLOAT XScale = FLOAT(Camera->FSXR) / STATUSBAR_U;
const FLOAT YScale = FLOAT(StatusBarLines) / STATUSBAR_V;
const FLOAT StatusBarX = 0;
const FLOAT StatusBarY = Camera->FSYR-StatusBarLines;
const BOOL UseSmallBar = XScale <= 0.5;
UTexture * Bar = UseSmallBar ? StatusSmallBar : StatusBar;
const FLOAT AdditionalScale = UseSmallBar ? 2.0 : 1.0;
GRend->DrawScaledSprite
(
Camera,Bar,
0,Camera->FSYR-StatusBarLines,
Camera->FSXR * (FLOAT)Bar->USize / STATUSBAR_U * AdditionalScale + 0.5,
(FLOAT)StatusBarLines * (FLOAT)Bar->VSize / STATUSBAR_V * AdditionalScale + 0.5,
BT_None,NULL,0,0
);
// Show the health value:
//obsolete: // Show the health (image and value):
//obsolete: {
//obsolete: GRend->DrawScaledSprite // Draw the health
//obsolete: (
//obsolete: Camera
//obsolete: , HealthImage
//obsolete: , StatusBarX + HealthImageX * XScale
//obsolete: , StatusBarY + HealthImageY * YScale
//obsolete: , FLOAT(HealthImage->USize) * XScale
//obsolete: , FLOAT(HealthImage->VSize) * YScale
//obsolete: , BT_None,NULL,0,0
//obsolete: );
ShowValue
(
Pawn.Health
, Camera
, StatusBarX + HealthValueX * XScale
, StatusBarY + HealthValueY * YScale
, XScale * AdditionalScale
, YScale * AdditionalScale
, UseSmallBar
, UseSmallBar ? StatusSmallDigits : StatusDigits
);
//obsolete: }
// Show the armor (image and value):
{
UTexture * ArmorImage = ArmorImages[DMT_Basic]; // todo: Should depend on kind of armour
GRend->DrawScaledSprite // Draw the armor
(
Camera
, ArmorImage
, StatusBarX + ArmorImageX * XScale
, StatusBarY + ArmorImageY * YScale
, FLOAT(ArmorImage->USize) * XScale
, FLOAT(ArmorImage->VSize) * YScale
, BT_None,NULL,0,0
);
ShowValue
(
Pawn.Armor[DMT_Basic]
, Camera
, StatusBarX + ArmorValueX * XScale
, StatusBarY + ArmorValueY * YScale
, XScale * AdditionalScale
, YScale * AdditionalScale
, UseSmallBar
, UseSmallBar ? StatusSmallDigits : StatusDigits
);
}
// Light up the lights for weapons in our inventory...
INDEX iInventory = Pawn.iInventory;
const TLightPosition * Positions = UseSmallBar ? StatusSmallLightPositions : StatusLightPositions;
UTexture * Light = UseSmallBar ? StatusSmallWeaponLight : StatusWeaponLight;
while( iInventory != INDEX_NONE )
{
AInventory & Inventory = (AInventory &)this->Camera->Level->ActorList->Element(iInventory);
if( Inventory.OwningSet > 0 )
{
const int Index = Inventory.OwningSet-1;
GRend->DrawScaledSprite // Draw the armor
(
Camera
, Light
, StatusBarX + Positions[Index].X * XScale * AdditionalScale
, StatusBarY + Positions[Index].Y * YScale * AdditionalScale
, FLOAT(Light->USize) * XScale * AdditionalScale
, FLOAT(Light->VSize) * YScale * AdditionalScale
, BT_None,NULL,0,0
);
iInventory = Inventory.iInventory;
}
}
// Show the ammo (image and value):
if( Pawn.iWeapon != INDEX_NONE )
{
AWeapon & Weapon = (AWeapon&)this->Camera->Level->ActorList->Element(Pawn.iWeapon);
UTexture * AmmoImage = Weapon.AmmoStatusIcon;
const int Ammo = Pawn.AmmoCount[Weapon.AmmoType];
if( AmmoImage != 0 )
{
GRend->DrawScaledSprite // Draw the ammo
(
Camera
, AmmoImage
, StatusBarX + AmmoImageX * XScale
, StatusBarY + AmmoImageY * YScale
, FLOAT(AmmoImage->USize) * XScale
, FLOAT(AmmoImage->VSize) * YScale
, BT_None,NULL,0,0
);
}
ShowValue
(
Ammo
, Camera
, StatusBarX + AmmoValueX * XScale
, StatusBarY + AmmoValueY * YScale
, XScale * AdditionalScale
, YScale * AdditionalScale
, UseSmallBar
, UseSmallBar ? StatusSmallDigits : StatusDigits
);
}
};
//
// Draw console:
//
if (ConsoleLines>0) GRend->DrawTiledTextureBlock
(
Camera,ConBackground,0,Camera->SXR,0,ConsoleLines,0,-ConsoleLines
);
}
//
// Draw border:
//
if (DrawBorder && ((BorderLines>0)||(BorderPixels>0)))
{
YStart += ConsoleLines;
int V = ConsoleLines>>1;
if (BorderLines>0)
{
GRend->DrawTiledTextureBlock(Camera,Border,0,Camera->SXR,0,BorderLines,0,-V);
GRend->DrawTiledTextureBlock(Camera,Border,0,Camera->SXR,YEnd,BorderLines,0,-V);
};
if (BorderPixels>0)
{
GRend->DrawTiledTextureBlock(Camera,Border,0,BorderPixels,YStart,YEnd-YStart,0,-V);
GRend->DrawTiledTextureBlock(Camera,Border,Camera->SXR-BorderPixels,BorderPixels,YStart,YEnd-YStart,0,-V);
};
};
//
// Draw logo:
//
if (LogoUp)
{
LogoUp=1;
int USize,VSize, MipLevel=0;
BYTE *Data = GGfx.Logo->GetData(&MipLevel,Camera->ColorBytes,&USize,&VSize);
FLOAT XSize = Camera->FSXR * 0.7;
FLOAT YSize = XSize * ((FLOAT)VSize/(FLOAT)USize);
GRend->DrawScaledSprite(Camera,GGfx.Logo,0.5*(Camera->FSXR - XSize),0,XSize,YSize,BT_None,NULL,0,0);
};
#ifdef SPLASH_CONFIDENTIAL
if ((GServer.Ticks < 35*8) && (levelGetState (Camera->Level.Level)==LEVEL_UP_PLAY))
{
gfxBurnRect (Camera->Texture,20,Camera->SXR-20,70,Camera->SYR-12,0);
//
GGfx.Printf (Camera->Texture,12,80,1, GGfx.HugeFontID,P_BROWN," " GAME_NAME " " GAME_VERSION);
GGfx.Printf (Camera->Texture,50,110,-1,GGfx.MedFontID,NormalFontColor,SPLASH_1);
GGfx.Printf (Camera->Texture,50,120,-1,GGfx.MedFontID,NormalFontColor,SPLASH_2);
GGfx.Printf (Camera->Texture,50,150,-1,GGfx.MedFontID,NormalFontColor,SPLASH_3);
GGfx.Printf (Camera->Texture,50,160,-1,GGfx.MedFontID,NormalFontColor,SPLASH_4);
GGfx.Printf (Camera->Texture,50,170,-1,GGfx.MedFontID,NormalFontColor,SPLASH_5);
};
#endif
//
if (ConsoleLines)
{
//
// Console is visible; display console view
//
int Y = ConsoleLines-1;
sprintf(MsgText[(TopLine + 1 + MAX_LINES) % MAX_LINES],"(> %s_",TypedStr);
for (int i=Scrollback; i<(NumLines+1); i++) // Display all text in the buffer
{
int Line = (TopLine + MAX_LINES*2 - (i-1)) % MAX_LINES;
//
int XL,YL;
GGfx.WrappedStrLen
(
&XL,&YL,-1,0,
GGfx.MedFont,Camera->SXR-8,MsgText[Line]
);
if (YL==0) YL=3; // Half-space blank lines
//
Y -= YL;
if ((Y+YL)<0) break;
//
GGfx.WrappedPrintf
(
Camera->Texture,4,Y,
-1,0,
GGfx.MedFont,NormalFontColor,
Camera->SXR-8,0,"%s",MsgText[Line]
);
};
}
else
{
//
// Console is hidden; display single-line view
//
if ((NumLines>0) && (MsgType!=LOG_None)) // Display a status message
{
int iLine=TopLine;
for (int i=0; i<NumLines; i++)
{
if (*MsgText[iLine]) break;
iLine = (iLine-1+MAX_LINES)%MAX_LINES;
};
GGfx.WrappedPrintf
(
Camera->Texture,4,2,-1,0,
GGfx.MedFont,NormalFontColor,
Camera->SXR-8,1,
"%s",MsgText[iLine]
);
};
if (KeyState==CK_Type) // Draw stuff being typed:
{
int XL,YL;
char S[256]; sprintf(S,"(> %s_",TypedStr);
GGfx.WrappedStrLen
(
&XL,&YL,-1,0,
GGfx.MedFont,Camera->SXR-8,S
);
GGfx.WrappedPrintf
(
Camera->Texture,2,Camera->SYR - ConsoleLines - StatusBarLines /*obsolete:- ExtraBarLines*/ - YL - 1,
-1,0,
GGfx.MedFont,NormalFontColor,
Camera->SXR-4,0,S
);
};
};
//
// Remember old status info for later comparison:
//
memcpy(Old,this,sizeof(*this));
Pawn.bStatusChanged = FALSE; // Indicates no change since last time status was drawn.
//
UNGUARD("FCameraConsole::PostRender");
};
/*------------------------------------------------------------------------------
Key
------------------------------------------------------------------------------*/
//
// Console keypress handler. Returns 1 if processed, 0 if not.
//
int FCameraConsole::Key (int Key)
{
GUARD;
AActor *Actor = &Camera->GetActor();
//
// Keys recognized regardless of state:
//
switch(toupper(Key))
{
case 27: // Escape
if (GCameraManager->FullscreenCamera && !IsTyping())
{
// Return from full-screen mode
debug(LOG_Win,"Esc pressed: Ending fullscreen mode");
GCameraManager->EndFullscreen();
return 1;
};
break;
case '`':
case '~':
return 1;
break;
};
//
// State-dependent keys:
//
switch (KeyState)
{
case CK_None:
//
// Normal input state - no typing, no menu.
//
switch(Key)
{
case 27:
if (ConsoleDest!=0.0) ConsoleDest=0.0;
break;
case K_ENTER: // Toggle fullscreen mode
if (GApp->KeyDown[K_ALT]) GCameraManager->MakeFullscreen(Camera);
break;
case K_F11+256: // Brightness level
char Temp[80];
if (++GGfx.GammaLevel >= GGfx.NumGammaLevels) GGfx.GammaLevel = 0;
GGfx.SetPalette();
GCache.Flush();
sprintf(Temp,"Brightness level %i/%i",GGfx.GammaLevel+1,GGfx.NumGammaLevels);
Log(LOG_Info,Temp);
return 1;
};
return 0;
case CK_Type:
//
// Typing a command:
//
int Len = strlen (TypedStr);
switch(Key)
{
case 27:
if (Scrollback)
{
Scrollback = 0;
}
else if (TypedStr[0])
{
ClearInput();
}
else
{
ConsoleDest=0.0;
KeyState = CK_None;
};
Scrollback=0;
break;
case 13:
if (Scrollback)
{
Scrollback = 0;
}
else
{
if (TypedStr[0])
{
Logf(LOG_Console,"(> %s",TypedStr);
//
// Update history buffer:
//
strcpy(History[HistoryTop],TypedStr);
HistoryTop = (HistoryTop+1) % MAX_HISTORY;
HistoryCur = (HistoryTop+1) % MAX_HISTORY;
//
// Make a local copy of the string, in case something
// recursively affects the contents of the console, then
// execute the typed string:
//
char Temp[256]; strcpy(Temp,TypedStr);
//
if (Exec (TypedStr,this)) {}
else if (Camera->Exec (TypedStr,this)) {}
else if (Camera->Level->Exec(TypedStr,this)) {}
else if (GUnreal.Exec (TypedStr,this)) {}
};
if (TypedStr[0]) Log(LOG_Console,"");
//
ClearInput();
if (!ConsoleDest) KeyState = CK_None;
Scrollback=0;
};
break;
case K_UP+256:
{
int HistoryTemp = (HistoryCur - 1 + MAX_HISTORY) % MAX_HISTORY;
if (HistoryTemp!=HistoryTop) HistoryCur = HistoryTemp;
//
strcpy(TypedStr,History[HistoryCur]);
};
Scrollback=0;
break;
case K_DOWN+256:
if (HistoryCur==HistoryTop)
{
ClearInput();
}
else
{
HistoryCur = (HistoryCur+1) % MAX_HISTORY;
strcpy(TypedStr,History[HistoryCur]);
};
Scrollback=0;
break;
case K_PAGEUP+256:
if (++Scrollback >= MAX_LINES) Scrollback = MAX_LINES-1;
break;
case K_PAGEDOWN+256:
if (--Scrollback < 0) Scrollback = 0;
break;
case K_RIGHT+256:
break;
case K_BACKSPACE:
case K_LEFT+256:
if (Len>0) TypedStr [Len-1] = 0;
Scrollback=0;
break;
default:
if (Len<(TEXTMSG_LENGTH-1))
{
TypedStr [Len]=Key; TypedStr [Len+1]=0;
};
Scrollback=0;
break;
};
return 1;
};
return 0; // Key was not processed
UNGUARD("FCameraConsole::Key");
};
/*------------------------------------------------------------------------------
Tick
------------------------------------------------------------------------------*/
//
// Console timer tick. Should be called every timer tick for every active
// camera whether a game is running or not.
//
void FCameraConsole::Tick (ICamera *Camera,int TicksPassed)
{
GUARD;
//
// Slide console up or down:
//
if (ConsolePos!=ConsoleDest)
{
FLOAT Delta = 0.05;
//
if (ConsolePos<ConsoleDest) ConsolePos = OurMin(ConsolePos+Delta,ConsoleDest);
else ConsolePos = OurMax(ConsolePos-Delta,ConsoleDest);
};
//
// Update status message:
//
if ((GServer.Ticks - MsgStart) > MsgDuration) MsgType = LOG_None;
//
UNGUARD("FCameraConsole::Tick");
};
/*------------------------------------------------------------------------------
Status functions
------------------------------------------------------------------------------*/
//
// See if the user is typing something on the console.
// This is used to block the actions of certain player inputs,
// such as the space bar.
//
int FCameraConsole::IsTyping (void)
{
GUARD;
return KeyState!=CK_None;
UNGUARD("FCameraConsole::IsTyping");
};
/*------------------------------------------------------------------------------
The End
------------------------------------------------------------------------------*/
| [
"[email protected]"
] | |
24c9154605c1b9a0f1417ba60d503013187b62ce | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_old_hunk_1830.cpp | 4e9040f4c6bfa72c63a7446bd464ddcc921a0d60 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | cpp | " printf(\"Available tests:\\n\");\n"
" for (i =0; i < NumTests; ++i)\n"
" {\n"
" printf(\"%d. %s\\n\", i, cmakeGeneratedFunctionMapEntries[i].name);\n"
" }\n"
" printf(\"Failed: %s is an invalid test name.\\n\", av[1]);\n"
" \n" | [
"[email protected]"
] | |
344b721437a6dfc50f8b36c957e126ac0caab65b | 3f6a4ffb1dff4e361054fde5b0f891782b4e764e | /samples/normal/dense_graph/sample_graph_printer1.cpp | 900025ce58bfd66ecccb6523a3ed7fc400619f8b | [] | no_license | hexu1985/MiniGraph.For.Cpp | ad8e05f13cd374b868319db1ceb071592256c107 | d139af318b41a3ef30195cfd070269fdca1f02b7 | refs/heads/master | 2020-06-02T09:46:17.780761 | 2020-03-05T09:20:47 | 2020-03-05T09:20:47 | 191,118,473 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 825 | cpp | /** \example normal/dense_graph/sample_graph_printer1.cpp
* This is an example of how to use the GraphPrinter class.
*/
#include <vector>
#include "mini_graph.hpp"
using namespace std;
using namespace mini_graph::normal;
int main()
{
int vertexNumber = 8;
vector<Edge> edges = {{0,2}, {0,5}, {0,7}, {1,7}, {2,6}, {3,4}, {3,5}, {4,5}, {4,6}, {4,7}}; // graph1.jpg
DenseGraph graph(vertexNumber, false); // directed false
for (auto edge: edges)
graph.insert(edge);
// show adjLists
cout << "-----------------show adjLists of Graph--------------------\n";
GraphPrinter::showAdjLists(graph);
cout << endl;
// show adjMatrix
cout << "-----------------show adjMatrix of Graph--------------------\n";
GraphPrinter::showAdjMatrix(graph);
cout << endl;
return 0;
}
| [
"[email protected]"
] | |
883d319f5ce13d90ccaf64f57847aefcf2e33f5b | 9dad058a1bf68fa4e2c7876a82386d1321c3b39f | /Uzytkownik.cpp | 425f488c2e171e3fe2d2a841eed444562dc513bf | [] | no_license | krzysztofGesickiProgramista/ks-obiekt | 5c3af4f3a4d9bf671a332666cc2a9b17ec226593 | b532e65168704cfee9958e449d97a6e454fba378 | refs/heads/master | 2020-04-02T07:34:28.157933 | 2018-10-28T13:45:28 | 2018-10-28T13:45:28 | 154,203,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 431 | cpp | #include "Uzytkownik.h"
using namespace std;
void Uzytkownik::ustawId(int noweId)
{
if (noweId >= 0)
id = noweId;
}
void Uzytkownik::ustawLogin(string nowyLogin)
{
login = nowyLogin;
}
void Uzytkownik::ustawHaslo(string noweHaslo)
{
haslo = noweHaslo;
}
int Uzytkownik::pobierzId()
{
return id;
}
string Uzytkownik::pobierzLogin()
{
return login;
}
string Uzytkownik::pobierzHaslo()
{
return haslo;
}
| [
"[email protected]"
] | |
6126dac648eef1c355ad459b3ed944169e5cb652 | f14626611951a4f11a84cd71f5a2161cd144a53a | /Client/UI/Windows/PlayerShopMessageBoardPage.cpp | 299e6c3894169fa8592d7f8635e2e13947547823 | [] | no_license | Deadmanovi4/mmo-resourse | 045616f9be76f3b9cd4a39605accd2afa8099297 | 1c310e15147ae775a59626aa5b5587c6895014de | refs/heads/master | 2021-05-29T06:14:28.650762 | 2015-06-18T01:16:43 | 2015-06-18T01:16:43 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,115 | cpp | #include "StdAfx.h"
#include "../UIDef.h"
#include "../GamePage/Package/PackagePage.h"
#include "../GamePage/ChatList/ChatListPage.h"
#include "../../GameClient/Game.h"
#include "../../GameClient/ClientApp/Player.h"
#include "../../GameClient/ClientApp/ClientRegion.h"
#include "../../GameClient/ClientApp/MainPlayerHand.h"
#include "../../GameClient/ClientApp/MsgBoxSys/MsgEventManager.h"
CEGUI::Window* InitPlayerShopMessageBoardPage(void); ///< 初始化个人商店留言板界面
void SubscribePlayerShopMessageBoardPageEvent(CEGUI::Window* mainPage); ///< 个人商店商品留言板界面事件注册
CEGUI::Window* InitPlayerShopMessageBoardPage(void)
{
#ifdef _DEBUG
CEGUI::Logger::getSingleton().setLogFilename("PlayerShopSaleNoter.log");
#endif
CEGUI::Window* wnd = LoadUI("PlayerShopMessageBoard");
#ifdef _DEBUG
CEGUI::Logger::getSingleton().setLogFilename("CEGUI.log",true);
#endif
SubscribePlayerShopMessageBoardPageEvent(wnd);
wnd->setVisible(false);
return wnd;
}
void SubscribePlayerShopMessageBoardPageEvent(CEGUI::Window* mainPage)
{
} | [
"[email protected]"
] | |
cae148c69924b5beafe0e0b263c0530cbba64b74 | 6d8ecffef0cf0b25b72762d3dc2a53c5a4673521 | /src/libANGLE/renderer/vulkan/MemoryObjectVk.cpp | 505df6a63b6e32a0c80c98677cbc97af16d1191c | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | clarkezone/angle | 42b6af2ab0c8c47bd9f39b49c703b2d5006b7f5e | 62387fc647193365e041fe4708a1492b4c787ed4 | refs/heads/master | 2021-06-02T06:23:03.962868 | 2021-01-27T18:58:01 | 2021-01-31T03:10:13 | 191,053,497 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,497 | cpp | // Copyright 2019 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// MemoryObjectVk.cpp: Defines the class interface for MemoryObjectVk, implementing
// MemoryObjectImpl.
#include "libANGLE/renderer/vulkan/MemoryObjectVk.h"
#include "common/debug.h"
#include "common/vulkan/vk_headers.h"
#include "libANGLE/Context.h"
#include "libANGLE/renderer/vulkan/ContextVk.h"
#include "libANGLE/renderer/vulkan/RendererVk.h"
#include "vulkan/vulkan_fuchsia_ext.h"
#if !defined(ANGLE_PLATFORM_WINDOWS)
# include <unistd.h>
#else
# include <io.h>
#endif
#if defined(ANGLE_PLATFORM_FUCHSIA)
# include <zircon/status.h>
# include <zircon/syscalls.h>
#endif
namespace rx
{
namespace
{
#if defined(ANGLE_PLATFORM_WINDOWS)
int close(int fd)
{
return _close(fd);
}
#endif
void CloseZirconVmo(zx_handle_t handle)
{
#if defined(ANGLE_PLATFORM_FUCHSIA)
zx_handle_close(handle);
#else
UNREACHABLE();
#endif
}
angle::Result DuplicateZirconVmo(ContextVk *contextVk, zx_handle_t handle, zx_handle_t *duplicate)
{
#if defined(ANGLE_PLATFORM_FUCHSIA)
zx_status_t status = zx_handle_duplicate(handle, ZX_RIGHT_SAME_RIGHTS, duplicate);
ANGLE_VK_CHECK(contextVk, status == ZX_OK, VK_ERROR_INVALID_EXTERNAL_HANDLE);
return angle::Result::Continue;
#else
UNREACHABLE();
return angle::Result::Stop;
#endif
}
VkExternalMemoryHandleTypeFlagBits ToVulkanHandleType(gl::HandleType handleType)
{
switch (handleType)
{
case gl::HandleType::OpaqueFd:
return VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT;
case gl::HandleType::ZirconVmo:
return VK_EXTERNAL_MEMORY_HANDLE_TYPE_TEMP_ZIRCON_VMO_BIT_FUCHSIA;
default:
// Not a memory handle type.
UNREACHABLE();
return VK_EXTERNAL_MEMORY_HANDLE_TYPE_FLAG_BITS_MAX_ENUM;
}
}
} // namespace
MemoryObjectVk::MemoryObjectVk() {}
MemoryObjectVk::~MemoryObjectVk() = default;
void MemoryObjectVk::onDestroy(const gl::Context *context)
{
if (mFd != kInvalidFd)
{
close(mFd);
mFd = kInvalidFd;
}
if (mZirconHandle != ZX_HANDLE_INVALID)
{
CloseZirconVmo(mZirconHandle);
mZirconHandle = ZX_HANDLE_INVALID;
}
}
angle::Result MemoryObjectVk::setDedicatedMemory(const gl::Context *context, bool dedicatedMemory)
{
mDedicatedMemory = dedicatedMemory;
return angle::Result::Continue;
}
angle::Result MemoryObjectVk::importFd(gl::Context *context,
GLuint64 size,
gl::HandleType handleType,
GLint fd)
{
ContextVk *contextVk = vk::GetImpl(context);
switch (handleType)
{
case gl::HandleType::OpaqueFd:
return importOpaqueFd(contextVk, size, fd);
default:
UNREACHABLE();
return angle::Result::Stop;
}
}
angle::Result MemoryObjectVk::importZirconHandle(gl::Context *context,
GLuint64 size,
gl::HandleType handleType,
GLuint handle)
{
ContextVk *contextVk = vk::GetImpl(context);
switch (handleType)
{
case gl::HandleType::ZirconVmo:
return importZirconVmo(contextVk, size, handle);
default:
UNREACHABLE();
return angle::Result::Stop;
}
}
angle::Result MemoryObjectVk::importOpaqueFd(ContextVk *contextVk, GLuint64 size, GLint fd)
{
ASSERT(mHandleType == gl::HandleType::InvalidEnum);
ASSERT(mFd == kInvalidFd);
ASSERT(fd != kInvalidFd);
mHandleType = gl::HandleType::OpaqueFd;
mFd = fd;
mSize = size;
return angle::Result::Continue;
}
angle::Result MemoryObjectVk::importZirconVmo(ContextVk *contextVk, GLuint64 size, GLuint handle)
{
ASSERT(mHandleType == gl::HandleType::InvalidEnum);
ASSERT(mZirconHandle == ZX_HANDLE_INVALID);
ASSERT(handle != ZX_HANDLE_INVALID);
mHandleType = gl::HandleType::ZirconVmo;
mZirconHandle = handle;
mSize = size;
return angle::Result::Continue;
}
angle::Result MemoryObjectVk::createImage(ContextVk *contextVk,
gl::TextureType type,
size_t levels,
GLenum internalFormat,
const gl::Extents &size,
GLuint64 offset,
vk::ImageHelper *image,
GLbitfield createFlags,
GLbitfield usageFlags)
{
RendererVk *renderer = contextVk->getRenderer();
const vk::Format &vkFormat = renderer->getFormat(internalFormat);
// EXT_external_objects issue 13 says that all supported usage flags must be specified.
// However, ANGLE_external_objects_flags allows these flags to be masked. Note that the GL enum
// values constituting the bits of |usageFlags| are identical to their corresponding Vulkan
// value.
const VkImageUsageFlags imageUsageFlags =
vk::GetMaximalImageUsageFlags(renderer, vkFormat.actualImageFormatID) & usageFlags;
VkExternalMemoryImageCreateInfo externalMemoryImageCreateInfo = {};
externalMemoryImageCreateInfo.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO;
externalMemoryImageCreateInfo.handleTypes = ToVulkanHandleType(mHandleType);
VkExtent3D vkExtents;
uint32_t layerCount;
gl_vk::GetExtentsAndLayerCount(type, size, &vkExtents, &layerCount);
// Initialize VkImage with initial layout of VK_IMAGE_LAYOUT_UNDEFINED.
//
// Binding a VkImage with an initial layout of VK_IMAGE_LAYOUT_UNDEFINED to external memory
// whose content has already been defined does not make the content undefined (see 11.7.1.
// External Resource Sharing).
//
// If the content is already defined, the ownership rules imply that the first operation on the
// texture must be a call to glWaitSemaphoreEXT that grants ownership of the image and informs
// us of the true layout.
//
// If the content is not already defined, the first operation may not be a glWaitSemaphore, but
// in this case undefined layout is appropriate.
//
// ANGLE_external_objects_flags allows create flags to be specified by the application instead
// of getting defaulted to zero. Note that the GL enum values constituting the bits of
// |createFlags| are identical to their corresponding Vulkan value.
ANGLE_TRY(image->initExternal(
contextVk, type, vkExtents, vkFormat, 1, imageUsageFlags, createFlags,
vk::ImageLayout::Undefined, &externalMemoryImageCreateInfo, gl::LevelIndex(0),
gl::LevelIndex(static_cast<uint32_t>(levels) - 1), static_cast<uint32_t>(levels),
layerCount, contextVk->isRobustResourceInitEnabled()));
VkMemoryRequirements externalMemoryRequirements;
image->getImage().getMemoryRequirements(renderer->getDevice(), &externalMemoryRequirements);
void *importMemoryInfo = nullptr;
VkMemoryDedicatedAllocateInfo memoryDedicatedAllocateInfo = {};
if (mDedicatedMemory)
{
memoryDedicatedAllocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR;
memoryDedicatedAllocateInfo.image = image->getImage().getHandle();
importMemoryInfo = &memoryDedicatedAllocateInfo;
}
VkImportMemoryFdInfoKHR importMemoryFdInfo = {};
VkImportMemoryZirconHandleInfoFUCHSIA importMemoryZirconHandleInfo = {};
switch (mHandleType)
{
case gl::HandleType::OpaqueFd:
ASSERT(mFd != kInvalidFd);
importMemoryFdInfo.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR;
importMemoryFdInfo.pNext = importMemoryInfo;
importMemoryFdInfo.handleType = ToVulkanHandleType(mHandleType);
importMemoryFdInfo.fd = dup(mFd);
importMemoryInfo = &importMemoryFdInfo;
break;
case gl::HandleType::ZirconVmo:
ASSERT(mZirconHandle != ZX_HANDLE_INVALID);
importMemoryZirconHandleInfo.sType =
VK_STRUCTURE_TYPE_TEMP_IMPORT_MEMORY_ZIRCON_HANDLE_INFO_FUCHSIA;
importMemoryZirconHandleInfo.pNext = importMemoryInfo;
importMemoryZirconHandleInfo.handleType = ToVulkanHandleType(mHandleType);
ANGLE_TRY(
DuplicateZirconVmo(contextVk, mZirconHandle, &importMemoryZirconHandleInfo.handle));
importMemoryInfo = &importMemoryZirconHandleInfo;
break;
default:
UNREACHABLE();
}
// TODO(jmadill, spang): Memory sub-allocation. http://anglebug.com/2162
ASSERT(offset == 0);
ASSERT(externalMemoryRequirements.size == mSize);
VkMemoryPropertyFlags flags = 0;
ANGLE_TRY(image->initExternalMemory(contextVk, renderer->getMemoryProperties(),
externalMemoryRequirements, nullptr, importMemoryInfo,
renderer->getQueueFamilyIndex(), flags));
return angle::Result::Continue;
}
} // namespace rx
| [
"[email protected]"
] | |
90878906865093f3933f9e6b99b443137c715891 | 4105780879d500920a149dd7c9a1b37fc290bdd8 | /MyGame-Game/Mygame/main.cpp | 0afb7eea34e9587037c8ee8576852b4813e3746a | [] | no_license | KonstantyOdwazny/MyProject | 00817900e7d91345d063b0dc9f4ef89d74a3dfef | 99e734d80066b79ce1266a51308567f19390d0a7 | refs/heads/master | 2022-11-16T21:06:07.124817 | 2020-07-13T02:27:28 | 2020-07-13T02:27:28 | 265,320,106 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,959 | cpp | #include "game.h"
using namespace std;
int main()
{
MainMenu menu;
menu.PlayMusic();
while(menu.Running() && menu.active==true)
{
menu.PollEvents();
menu.Update();
menu.Drawing();
}
if(menu.action==Activity::Exit)
{
return 0;
}
else
{
if(menu.action==Activity::Sterowanie)
{
SterowanieWindow sterowanie;
sterowanie.PlayMusic();
while(sterowanie.Running())
{
sterowanie.PollEvents();
//sterowanie.Update();
sterowanie.Drawing();
}
return main();
}
OptionsWindow select;
select.PlayMusic();
while(select.Running())
{
select.PollEvents();
select.Update();
select.Drawing();
}
if(select.exitorplay==false)
{
return 0;
}
else
{
Game game(select.heroclass);
int koniec=0;
sf::SoundBuffer begin_buffer;
sf::Sound begin_music;
begin_buffer.loadFromFile("C:/Users/konst/Desktop/MyGame-Game/MyProject/MyGame-Game/build-Mygame-Desktop_Qt_5_14_1_MinGW_64_bit-Debug/bensound-epic.ogg");
begin_music.setBuffer(begin_buffer);
begin_music.setLoop(true);
begin_music.play();
while(game.running())
{
//events
game.pollevent();
if(game.startagain==true)
{
koniec=1;
break;
}
//updating
game.update();
//drawing everything
game.render();
}
if(koniec==1)
{
begin_music.stop();
return main();
}
else
{
if(game.victory==true)
{
begin_music.stop();
WinWindow win;
while(win.Running())
{
win.PollEvents();
win.Update();
win.Drawing();
}
}
return 0;
}
}
}
}
| [
"[email protected]"
] | |
924bd94a35924084614aed29f094d4d07de0a327 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/ab/274ff2d68443c5/main.cpp | fb27913c5bc46458f5f72be338a3095cb7823488 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | cpp | #include <iostream>
struct Base0 {
int b0;
};
struct Base1 {
int b1;
};
struct Derived : Base0, Base1 {};
int main() {
Derived *p = nullptr;
Base0 *p0 = p;
Base1 *p1 = p;
std::cout
<< "Derived : " << (void*)p
<< "\nBase0 : " << (void*)p0
<< "\nBase1 : " << (void*)p1 << '\n';
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
c3090545704d86d28693fd4c4a454ee5fb91f81e | 577d87fd2b11e666b6c663f2e1eee3c99e25b6a7 | /Simulationen/2-uniform/2-uni-1/lattice.c++ | cd83fdaf663b48c17c82bda955c150c403d63dde | [] | no_license | rneher/DiplomArbeit_Percolation | e86261dc5e146f1689ad8a389151cb589588fe5e | 501f80a2a9434b17fdb10fda754dfd59395f9e8f | refs/heads/master | 2020-07-10T02:31:35.332483 | 2019-08-24T10:39:20 | 2019-08-24T10:39:20 | 204,143,253 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,252 | //lattice dependent code
//lattice 1
//set adjacencies and boundary conditions
void boundaries(void)
{
int i,row,column,shift;
for (i=0; i<N; i++) {
column=i%L; //determine row and column number
row=(i-column)/L;
shift=(9*(row%L))%13;
if ((column-shift+13)%13==1)
{
nn[i][0]=(i+1)%N;
nn[i][1]=i;
nn[i][2]=(i+L-1)%N;
nn[i][3]=(i-1+N)%N;
nn[i][4]=(i-L+N)%N;
nn[i][5]=(i-L+1+N)%N;
}
else if ((column-shift+13)%13==2)
{
nn[i][0]=(i+1)%N;
nn[i][1]=(i+L)%N;
nn[i][2]=i;
nn[i][3]=(i-1+N)%N;
nn[i][4]=(i-L+N)%N;
nn[i][5]=(i-L+1+N)%N;
}
else if ((column-shift+13)%13==4)
{
nn[i][0]=i;
nn[i][1]=(i+L)%N;
nn[i][2]=(i+L-1)%N;
nn[i][3]=(i-1+N)%N;
nn[i][4]=(i-L+N)%N;
nn[i][5]=(i-L+1)%N;
}
else if ((column-shift+13)%13==5)
{
nn[i][0]=i;
nn[i][1]=i;
nn[i][2]=i;
nn[i][3]=i;
nn[i][4]=i;
nn[i][5]=i;
}
else if ((column-shift+13)%13==6)
{
nn[i][0]=(i+1)%N;
nn[i][1]=(i+L)%N;
nn[i][2]=(i+L-1)%N;
nn[i][3]=i;
nn[i][4]=(i-L+N)%N;
nn[i][5]=(i-L+1)%N;
}
else if ((column-shift+13)%13==8)
{
nn[i][0]=(i+1)%N;
nn[i][1]=(i+L)%N;
nn[i][2]=(i+L-1)%N;
nn[i][3]=(i-1+N)%N;
nn[i][4]=(i-L+N)%N;
nn[i][5]=i;
}
else if ((column-shift+13)%13==9)
{
nn[i][0]=(i+1)%N;
nn[i][1]=(i+L)%N;
nn[i][2]=(i+L-1)%N;
nn[i][3]=(i-1+N)%N;
nn[i][4]=i;
nn[i][5]=(i-L+1)%N;
}
else
{
nn[i][0]=(i+1)%N;
nn[i][1]=(i+L)%N;
nn[i][2]=(i+L-1)%N;
nn[i][3]=(i-1+N)%N;
nn[i][4]=(i-L+N)%N;
nn[i][5]=(i-L+1)%N;
}
if (row==0) {nn[i][4]=i;nn[i][5]=i;}
if (row==L-1) {nn[i][1]=i;nn[i][2]=i;}
if (column==0) {nn[i][2]=i;nn[i][3]=i;}
if (column==L-1) {nn[i][0]=i;nn[i][5]=i;}
}
}
int spanning(int root)
{
int i,temp=0;
for(i=0;i<L;i++) if (findroot(i)==root) temp++;
if (temp) {
temp=0;
for(i=N-1;i>N-1-L;i--) if (findroot(i)==root) temp++;
if (temp) {return 1;}
}
for (i=0;i<N;i+=L)
{
if (findroot(i)==root) temp++;
}
if (temp)
{
temp=0;
for (i=0;i<N;i+=L)
{
if (findroot(i+L-1)==root) temp++;
}
if (temp) return 1;
else return 0;
}
return 0;
}
| [
"[email protected]"
] | ||
58b5695812ad3a665144be4d49112cefbe69505c | 6ddb3aa0b430f8f5726ace5acf70d9b2e58631e6 | /sources/Game/Entities/Player.hpp | e0fae17fa921beef90cd8f744ae865448eb2431b | [] | no_license | jjzhang166/Akanya | 6c717a944efd29b876757aa59f707d0fecd941f5 | bb64e5b128bf6ca8730180bc76c831340357cc42 | refs/heads/master | 2023-03-28T17:07:41.388968 | 2021-03-28T22:10:22 | 2021-03-28T22:10:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,239 | hpp | //
// Akanya
// sources/Game/Entities/Player
// Desribes a palyer
//
#ifndef ___INCLUDE_GUARD_SOURCES_GAME_ENTITIES_PLAYER_HPP___
#define ___INCLUDE_GUARD_SOURCES_GAME_ENTITIES_PLAYER_HPP___
#include "Engine/Graphic/Actors/BasicShapes/Cube.hpp"
namespace game::entity {
class Player
: public engine::graphic::actor::basicShape::Cube
, public engine::graphic::actor::AControlable
{
public:
// ---------------------------------- *structors
explicit Player(
const std::string& shaderFilepath
);
~Player();
// ---------------------------------- Copy sementic
Player(
const Player&
) noexcept = delete;
auto operator=(
const Player&
) noexcept -> Player& = delete;
// ---------------------------------- Copy sementic
Player(
Player&&
) noexcept = delete;
auto operator=(
Player&&
) noexcept -> Player& = delete;
// ---------------------------------- override
void configureShader() const override;
void update(
float deltaTime
) override;
public:
protected:
protected:
private:
private:
};
} // namespace game::entity
#endif // ___INCLUDE_GUARD_SOURCES_GAME_ENTITIES_PLAYER_HPP___
| [
"[email protected]"
] | |
5fc53fcbc606fab50b55c19126fc3a25d9fc3604 | 3eafc2afeecb0616244b17ebf1389a56226fccbd | /POJ_3009.cpp | 6687ca4c6350d8a92ebcf4ef052526622b42e20e | [] | no_license | nappleyjq/algorithm | 7ada318a3cc40e5b21d193dfbe0911a268a0754b | 117dcca5f5ab46bc1106233c580e9af10efdec2c | refs/heads/master | 2021-09-02T12:30:38.774202 | 2018-01-02T16:59:08 | 2018-01-02T16:59:08 | 108,274,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,305 | cpp | /*
http://poj.org/problem?id=3009
Description
On Planet MM-21, after their Olympic games this year, curling is getting popular. But the rules are somewhat different from ours. The game is played on an ice game board on which a square mesh is marked. They use only a single stone. The purpose of the game is to lead the stone from the start to the goal with the minimum number of moves.
Fig. 1 shows an example of a game board. Some squares may be occupied with blocks. There are two special squares namely the start and the goal, which are not occupied with blocks. (These two squares are distinct.) Once the stone begins to move, it will proceed until it hits a block. In order to bring the stone to the goal, you may have to stop the stone by hitting it against a block, and throw again.
Fig. 1: Example of board (S: start, G: goal)
The movement of the stone obeys the following rules:
At the beginning, the stone stands still at the start square.
The movements of the stone are restricted to x and y directions. Diagonal moves are prohibited.
When the stone stands still, you can make it moving by throwing it. You may throw it to any direction unless it is blocked immediately(Fig. 2(a)).
Once thrown, the stone keeps moving to the same direction until one of the following occurs:
The stone hits a block (Fig. 2(b), (c)).
The stone stops at the square next to the block it hit.
The block disappears.
The stone gets out of the board.
The game ends in failure.
The stone reaches the goal square.
The stone stops there and the game ends in success.
You cannot throw the stone more than 10 times in a game. If the stone does not reach the goal in 10 moves, the game ends in failure.
Fig. 2: Stone movements
Under the rules, we would like to know whether the stone at the start can reach the goal and, if yes, the minimum number of moves required.
With the initial configuration shown in Fig. 1, 4 moves are required to bring the stone from the start to the goal. The route is shown in Fig. 3(a). Notice when the stone reaches the goal, the board configuration has changed as in Fig. 3(b).
Fig. 3: The solution for Fig. D-1 and the final board configuration
Input
The input is a sequence of datasets. The end of the input is indicated by a line containing two zeros separated by a space. The number of datasets never exceeds 100.
Each dataset is formatted as follows.
the width(=w) and the height(=h) of the board
First row of the board
...
h-th row of the board
The width and the height of the board satisfy: 2 <= w <= 20, 1 <= h <= 20.
Each line consists of w decimal numbers delimited by a space. The number describes the status of the corresponding square.
0 vacant square
1 block
2 start position
3 goal position
The dataset for Fig. D-1 is as follows:
6 6
1 0 0 2 1 0
1 1 0 0 0 0
0 0 0 0 0 3
0 0 0 0 0 0
1 0 0 0 0 1
0 1 1 1 1 1
Output
For each dataset, print a line having a decimal integer indicating the minimum number of moves along a route from the start to the goal. If there are no such routes, print -1 instead. Each line should not have any character other than this number.
Sample Input
2 1
3 2
6 6
1 0 0 2 1 0
1 1 0 0 0 0
0 0 0 0 0 3
0 0 0 0 0 0
1 0 0 0 0 1
0 1 1 1 1 1
6 1
1 1 2 1 1 3
6 1
1 0 2 1 1 3
12 1
2 0 1 1 1 1 1 1 1 1 1 3
13 1
2 0 1 1 1 1 1 1 1 1 1 1 3
0 0
Sample Output
1
4
-1
4
10
-1
*/
/*
Solution:depth first search
*/
#ifndef ONLINE_JUDGE
#pragma warning(disable : 4996)
#endif
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int w, h;
int map[32][32];
int sx, sy;
int min_step;
const int direction[4][2] = {
{ -1, 0 },
{ 1, 0 },
{ 0, -1 },
{ 0, 1 },
};
void dfs(const int& x, const int& y, int step)
{
if (step >= 10 || step > min_step)
{
return;
}
for (int i = 0; i < 4; ++i)
{
int nx = x;
int ny = y;
// 让石头往固定的方向一直飞
while(nx >= 0 && nx < w && ny >= 0 && ny < h)
{
switch (map[nx][ny])
{
case 0:
{
// 继续飞
nx += direction[i][0];
ny += direction[i][1];
}break;
case 3:
{
// 到家了
if (step + 1 < min_step)
{
min_step = step + 1;
}
nx = -1;
}break;
case 1:
{
// 撞到了block
if (!(nx - direction[i][0] == x && ny - direction[i][1] == y))
{
// 中间有空地,不是紧挨着block
// 石头消失
map[nx][ny] = 0;
// 后退一步扔石头
dfs(nx - direction[i][0], ny - direction[i][1], step + 1);
// 复原地图,供下一个方向尝试
map[nx][ny] = 1;
}
// 开始下一个方向
nx = -1;
}break;
default:
break;
}
}
}
}
int main(int argc, char *argv[])
{
while (cin >> w >> h, w != 0)
{
for (int i = 0; i < h; ++i)
{
for (int j = 0; j < w; ++j)
{
cin >> map[j][i];
}
}
for (int i = 0; i < h; ++i)
{
for (int j = 0; j < w; ++j)
{
if (2 == map[j][i])
{
sx = j;
sy = i;
i = h;
break;
}
}
}
map[sx][sy] = 0;
min_step = 11;
dfs(sx, sy, 0);
if (min_step > 10)
{
min_step = -1;
}
cout << min_step << endl;
}
return 0;
}
| [
"[email protected]"
] | |
2e35780f4d683fffe59f1eca2822cf31d9b7d71f | 438e2b02741015225f5b54130f3a97d4005c3f58 | /BOJ/18126.cpp | 5d7829f44a04f1e57b8de23c78cf70fa42613e85 | [] | no_license | jiho5993/solving_algorithm | 20c2e3e3ee6e14116554d0fd00918447ca21784c | fbbe52bc372d418e204128e78432038dfb60b410 | refs/heads/master | 2022-10-27T13:36:27.393518 | 2022-10-16T09:32:18 | 2022-10-16T09:32:18 | 193,317,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
int N;
ll dist[5001];
vector<pair<ll, ll> > arr[5001];
void dfs(int cur, int prev) {
for(auto i : arr[cur]) {
if(dist[i.first] > dist[cur] + i.second && prev != i.first) {
dist[i.first] = dist[cur] + i.second;
dfs(i.first, cur);
}
}
}
int main() {
ios_base::sync_with_stdio(false), cin.tie(0);
cin >> N;
for(int i=2; i<=N; i++) {
ll a, b, c; cin >> a >> b >> c;
arr[a].push_back({b, c});
arr[b].push_back({a, c});
dist[i] = 5e13;
}
dfs(1, 0);
cout << *max_element(dist+2, dist+N+1);
return 0;
}
| [
"[email protected]"
] | |
669f6fac17a4b4090ac6798f9ec95fc98bc0bd9a | 1775576281b8c24b5ce36b8685bc2c6919b35770 | /tags/release_1.0/mathstuff.cpp | eb879f6e99b19edbef5f81025112eb72b4ae58e3 | [] | no_license | BackupTheBerlios/gtkslade-svn | 933a1268545eaa62087f387c057548e03497b412 | 03890e3ba1735efbcccaf7ea7609d393670699c1 | refs/heads/master | 2016-09-06T18:35:25.336234 | 2006-01-01T11:05:50 | 2006-01-01T11:05:50 | 40,615,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,690 | cpp |
#include "main.h"
#include "struct_3d.h"
#include "mathstuff.h"
// difference: Finds the difference between 2 numbers
// ----------------------------------------------- >>
int difference(int v1, int v2)
{
return max(v1, v2) - min(v1, v2);
}
// distance: Returns the distance between two points
// ---------------------------------------------- >>
double distance(double x1, double y1, double x2, double y2)
{
double dist_x = x2 - x1;
double dist_y = y2 - y1;
return sqrt(dist_x * dist_x + dist_y * dist_y);
}
// midpoint: Returns the mid point of a line between two points
// --------------------------------------------------------- >>
point2_t midpoint(point2_t p1, point2_t p2)
{
int mid_x = min(p1.x, p2.x) + (difference(p1.x, p2.x) / 2);
int mid_y = min(p1.y, p2.y) + (difference(p1.y, p2.y) / 2);
return point2_t(mid_x, mid_y);
}
// distance_to_line: Finds the shortest distance from a vertex to a line
// ------------------------------------------------------------------ >>
// (code borrowed & slightly modified from Doom Builder, by CodeImp)
double distance_to_line(int x1, int y1, int x2, int y2, double vx, double vy)
{
double u;
// Get length of linedef
double ld = distance(x1, y1, x2, y2);
// Check if not zero length
if(ld)
{
// Get the intersection offset
u = double((vx - x1) * (x2 - x1) + (vy - y1) * (y2 - y1)) / (ld * ld);
// Limit intersection offset to the line
double lbound = 1 / ld;
double ubound = 1 - lbound;
if(u < lbound) u = lbound;
if(u > ubound) u = ubound;
}
else
{
u = 0;
}
// Calculate intersection point
double ix = double(x1) + u * double(x2 - x1);
double iy = double(y1) + u * double(y2 - y1);
// Return distance between intersection and point
// which is the shortest distance to the line
return distance(double(vx), double(vy), ix, iy);
}
// point_in_rect: Determines if a point is within a rectangle
// ------------------------------------------------------- >>
bool point_in_rect(int x1, int y1, int x2, int y2, int x, int y)
{
return (x >= x1) && (x <= x2) && (y >= y1) && (y <= y2);
}
// lines_intersect: Checks if 2 lines intersect eachother
// --------------------------------------------------- >>
bool lines_intersect(rect_t line1, rect_t line2)
{
float r, s;
r = float(line1.y1()-line2.y1())*float(line2.width())-float(line1.x1()-line2.x1())*float(line2.height()) /
float(line1.width())*float(line2.height())-float(line1.height())*float(line2.width());
s = float(line1.y1()-line2.y1())*float(line1.width())-float(line1.x1()-line2.x1())*float(line1.height()) /
float(line1.width())*float(line2.height())-float(line1.height())*float(line2.width());
if (0.0f <= r <= 1.0f && 0.0f <= s <= 1.0f)
return true;
else
return false;
}
// cross: Returns the cross product of 2 vectors
// ------------------------------------------ >>
point3_t cross(point3_t p1, point3_t p2)
{
point3_t cross_product;
cross_product.x = ((p1.y * p2.z) - (p1.z * p2.y));
cross_product.y = ((p1.z * p2.x) - (p1.x * p2.z));
cross_product.z = ((p1.x * p2.y) - (p1.y * p2.x));
return cross_product;
}
// dot_product: Returns the dot product of 2 vectors
// ---------------------------------------------- >>
float dot_product(point3_t v1, point3_t v2)
{
return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
}
// angle_between_vectors: Returns the angle between 2 vectors
// ------------------------------------------------------- >>
float angle_between_vectors(float x1, float y1, float x2, float y2)
{
float dot = (x1 * x2) + (y1 * y2);
float len = sqrt(x1 * x1 + y1 * y1) * sqrt(x2 * x2 + y2 * y2);
float cosin = dot / len;
return acos(cosin) * 180.0f / 3.1415926535897932384f;
}
float angle_between_vectors_2(point3_t v1, point3_t v2)
{
float dot = (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
float len = sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z)
* sqrt(v2.x * v2.x + v2.y * v2.y + v2.z * v2.z);
float cosin = dot / len;
return acos(cosin) * 180.0f / 3.1415926535897932384f;
}
// get_2d_angle: Returns the angle between 2 2d vectors (0.0f-360.0f)
// --------------------------------------------------------------- >>
float get_2d_angle(point3_t axis, point3_t vector)
{
point3_t p1(axis.x, axis.y, 0.0f);
point3_t p2(vector.x, vector.y, 0.0f);
float a = angle_between_vectors_2(p1.normalize(), p2.normalize());
float side = p2.y * p1.x - p2.x * p1.y;
float ret;
if (side > 0.0f)
ret = 360.0f - a;
else
ret = a;
if (ret > 360.0f)
ret = 360.0f;
if (ret < 0.0f)
ret = 0.0f;
return ret;
}
| [
"veilofsorrow@0f6d0948-3201-0410-bbe6-95a89488c5be"
] | veilofsorrow@0f6d0948-3201-0410-bbe6-95a89488c5be |
e030a6a9829abd344f37c670fab95a2d19999dcf | 33f59b1ba6b12c2dd3080b24830331c37bba9fe2 | /Depend/Foundation/System/Wm4TStringHashTable.inl | 1d6e7ca3473186c2f6a08c4108cf9be5e898e8a4 | [] | no_license | daleaddink/flagship3d | 4835c223fe1b6429c12e325770c14679c42ae3c6 | 6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a | refs/heads/master | 2021-01-15T16:29:12.196094 | 2009-11-01T10:18:11 | 2009-11-01T10:18:11 | 37,734,654 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,109 | inl | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Foundation Library source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4FoundationLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
//----------------------------------------------------------------------------
template <class TVALUE>
TStringHashTable<TVALUE>::TStringHashTable (int iTableSize)
{
assert(iTableSize > 0);
m_iTableSize = iTableSize;
m_iQuantity = 0;
m_iIndex = 0;
m_pkItem = 0;
m_apkTable = WM4_NEW HashItem*[m_iTableSize];
memset(m_apkTable,0,m_iTableSize*sizeof(HashItem*));
}
//----------------------------------------------------------------------------
template <class TVALUE>
TStringHashTable<TVALUE>::~TStringHashTable ()
{
RemoveAll();
WM4_DELETE[] m_apkTable;
}
//----------------------------------------------------------------------------
template <class TVALUE>
int TStringHashTable<TVALUE>::GetQuantity () const
{
return m_iQuantity;
}
//----------------------------------------------------------------------------
template <class TVALUE>
bool TStringHashTable<TVALUE>::Insert (const std::string& rkKey,
const TVALUE& rtValue)
{
// find hash table entry for given key
int iIndex = HashFunction(rkKey);
HashItem* pkItem = m_apkTable[iIndex];
// search for item in list associated with key
while (pkItem)
{
if (rkKey == pkItem->m_kKey)
{
// item already in hash table
return false;
}
pkItem = pkItem->m_pkNext;
}
// add item to beginning of list
pkItem = WM4_NEW HashItem;
pkItem->m_kKey = rkKey;
pkItem->m_tValue = rtValue;
pkItem->m_pkNext = m_apkTable[iIndex];
m_apkTable[iIndex] = pkItem;
m_iQuantity++;
return true;
}
//----------------------------------------------------------------------------
template <class TVALUE>
TVALUE* TStringHashTable<TVALUE>::Find (const std::string& rkKey) const
{
// find hash table entry for given key
int iIndex = HashFunction(rkKey);
HashItem* pkItem = m_apkTable[iIndex];
// search for item in list associated with key
while (pkItem)
{
if (rkKey == pkItem->m_kKey)
{
// item is in hash table
return &pkItem->m_tValue;
}
pkItem = pkItem->m_pkNext;
}
return 0;
}
//----------------------------------------------------------------------------
template <class TVALUE>
bool TStringHashTable<TVALUE>::Remove (const std::string& rkKey)
{
// find hash table entry for given key
int iIndex = HashFunction(rkKey);
HashItem* pkItem = m_apkTable[iIndex];
if (!pkItem)
{
return false;
}
if (rkKey == pkItem->m_kKey)
{
// item is at front of list, strip it off
HashItem* pkSave = pkItem;
m_apkTable[iIndex] = pkItem->m_pkNext;
WM4_DELETE pkSave;
m_iQuantity--;
return true;
}
// search for item in list
HashItem* pkPrev = pkItem;
HashItem* pkCurr = pkItem->m_pkNext;
while (pkCurr && rkKey != pkCurr->m_kKey)
{
pkPrev = pkCurr;
pkCurr = pkCurr->m_pkNext;
}
if (pkCurr)
{
// found the item
pkPrev->m_pkNext = pkCurr->m_pkNext;
WM4_DELETE pkCurr;
m_iQuantity--;
return true;
}
return false;
}
//----------------------------------------------------------------------------
template <class TVALUE>
void TStringHashTable<TVALUE>::RemoveAll ()
{
if (m_iQuantity > 0)
{
for (int iIndex = 0; iIndex < m_iTableSize; iIndex++)
{
while (m_apkTable[iIndex])
{
HashItem* pkSave = m_apkTable[iIndex];
m_apkTable[iIndex] = m_apkTable[iIndex]->m_pkNext;
WM4_DELETE pkSave;
if (--m_iQuantity == 0)
{
return;
}
}
}
}
}
//----------------------------------------------------------------------------
template <class TVALUE>
TVALUE* TStringHashTable<TVALUE>::GetFirst (std::string* pkKey) const
{
if (m_iQuantity > 0)
{
for (m_iIndex = 0; m_iIndex < m_iTableSize; m_iIndex++)
{
if (m_apkTable[m_iIndex])
{
m_pkItem = m_apkTable[m_iIndex];
*pkKey = m_pkItem->m_kKey;
return &m_pkItem->m_tValue;
}
}
}
return 0;
}
//----------------------------------------------------------------------------
template <class TVALUE>
TVALUE* TStringHashTable<TVALUE>::GetNext (std::string* pkKey) const
{
if (m_iQuantity > 0)
{
m_pkItem = m_pkItem->m_pkNext;
if (m_pkItem)
{
*pkKey = m_pkItem->m_kKey;
return &m_pkItem->m_tValue;
}
for (m_iIndex++; m_iIndex < m_iTableSize; m_iIndex++)
{
if (m_apkTable[m_iIndex])
{
m_pkItem = m_apkTable[m_iIndex];
*pkKey = m_pkItem->m_kKey;
return &m_pkItem->m_tValue;
}
}
}
return 0;
}
//----------------------------------------------------------------------------
template <class TVALUE>
int TStringHashTable<TVALUE>::HashFunction (const std::string& rkKey) const
{
int iHiKey = 0, iLoKey = 0;
for (int i = 0; i < (int)rkKey.length(); i++)
{
if (i & 1)
{
iHiKey += (int)rkKey[i];
}
else
{
iLoKey += (int)rkKey[i];
}
}
return abs(iLoKey * iHiKey) % m_iTableSize;
}
//----------------------------------------------------------------------------
| [
"yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa"
] | yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa |
0cf2eae76570265a3758308891d241e95c4020e1 | 25664158302e5fb3d833e7b3f8d95ac35536ba98 | /src/TokenizerDelim.h | bde6792eeed2ea90929d85e4108e801c7d82fdb7 | [] | no_license | sjackman/readr | 613db1ab052412273dbcce1e3d4725d26fe4db27 | 08a949246dd6d5921c8cd8507e0c4035b41c4daa | refs/heads/master | 2020-12-13T20:55:15.031199 | 2015-04-01T14:18:23 | 2015-04-01T14:18:23 | 33,261,585 | 1 | 0 | null | 2015-04-01T17:19:32 | 2015-04-01T17:19:32 | null | UTF-8 | C++ | false | false | 7,934 | h | #ifndef FASTREAD_TOKENIZEDELIM_H_
#define FASTREAD_TOKENIZEDELIM_H_
#include <Rcpp.h>
#include "Token.h"
#include "Tokenizer.h"
#include "utils.h"
enum DelimState {
STATE_DELIM,
STATE_FIELD,
STATE_STRING,
STATE_QUOTE,
STATE_ESCAPE_S,
STATE_ESCAPE_F,
STATE_STRING_END
};
class TokenizerDelim : public Tokenizer {
char delim_, quote_;
std::string NA_;
bool escapeBackslash_, escapeDouble_;
SourceIterator begin_, cur_, end_;
DelimState state_;
int row_, col_;
bool moreTokens_;
public:
TokenizerDelim(char delim = ',', char quote = '"', std::string NA = "NA",
bool escapeBackslash = false, bool escapeDouble = true):
delim_(delim),
quote_(quote),
NA_(NA),
escapeBackslash_(escapeBackslash),
escapeDouble_(escapeDouble),
moreTokens_(false)
{
}
void tokenize(SourceIterator begin, SourceIterator end) {
cur_ = begin;
begin_ = begin;
end_ = end;
row_ = 0;
col_ = 0;
state_ = STATE_DELIM;
moreTokens_ = true;
}
std::pair<double,size_t> progress() {
size_t bytes = cur_ - begin_;
return std::make_pair(bytes / (double) (end_ - begin_), bytes);
}
Token nextToken() {
// Capture current position
int row = row_, col = col_;
if (!moreTokens_)
return Token(TOKEN_EOF, row, col);
SourceIterator token_begin = cur_;
bool hasEscapeD = false, hasEscapeB = false;
while (cur_ != end_) {
// Increments cur on destruct, ensuring that we always move on to the
// next character
Advance advance(&cur_);
if ((row_ + 1) % 100000 == 0 || (col_ + 1) % 100000 == 0)
Rcpp::checkUserInterrupt();
switch(state_) {
case STATE_DELIM:
if (*cur_ == '\r' || *cur_ == '\n') {
newRecord();
advanceForLF(&cur_, end_);
return Token(TOKEN_EMPTY, row, col);
} else if (*cur_ == delim_) {
newField();
return Token(TOKEN_EMPTY, row, col);
} else if (*cur_ == quote_) {
state_ = STATE_STRING;
} else if (escapeBackslash_ && *cur_ == '\\') {
state_ = STATE_ESCAPE_F;
} else {
state_ = STATE_FIELD;
}
break;
case STATE_FIELD:
if (*cur_ == '\r' || *cur_ == '\n') {
newRecord();
return fieldToken(token_begin, advanceForLF(&cur_, end_), hasEscapeB, row, col);
} else if (escapeBackslash_ && *cur_ == '\\') {
state_ = STATE_ESCAPE_F;
} else if (*cur_ == delim_) {
newField();
return fieldToken(token_begin, cur_, hasEscapeB, row, col);
}
break;
case STATE_ESCAPE_F:
hasEscapeB = true;
state_ = STATE_FIELD;
break;
case STATE_QUOTE:
if (*cur_ == quote_) {
hasEscapeD = true;
state_ = STATE_STRING;
} else if (*cur_ == '\r' || *cur_ == '\n') {
newRecord();
return stringToken(token_begin + 1, advanceForLF(&cur_, end_) - 1,
hasEscapeB, hasEscapeD, row, col);
} else if (*cur_ == delim_) {
newField();
return stringToken(token_begin + 1, cur_ - 1,
hasEscapeB, hasEscapeD, row, col);
} else {
Rcpp::stop("At [%i, %i] expecting delimiter or quote but found '%s'",
row + 1, col + 1, *cur_);
}
break;
case STATE_STRING:
if (*cur_ == quote_) {
if (escapeDouble_) {
state_ = STATE_QUOTE;
} else {
state_ = STATE_STRING_END;
}
} else if (escapeBackslash_ && *cur_ == '\\') {
state_ = STATE_ESCAPE_S;
}
break;
case STATE_STRING_END:
if (*cur_ == '\r' || *cur_ == '\n') {
newRecord();
return stringToken(token_begin + 1, advanceForLF(&cur_, end_) - 1,
hasEscapeB, hasEscapeD, row, col);
} else if (*cur_ == delim_) {
newField();
return stringToken(token_begin + 1, cur_ - 1, hasEscapeB, hasEscapeD, row, col);
} else {
state_ = STATE_FIELD;
}
break;
case STATE_ESCAPE_S:
hasEscapeB = true;
state_ = STATE_STRING;
break;
}
}
// Reached end of Source: cur_ == end_
moreTokens_ = false;
switch (state_) {
case STATE_DELIM:
if (col_ == 0) {
return Token(TOKEN_EOF, row, col);
} else {
return Token(TOKEN_EMPTY, row, col);
}
case STATE_STRING_END:
case STATE_QUOTE:
return stringToken(token_begin + 1, end_ - 1, hasEscapeB, hasEscapeD, row, col);
case STATE_STRING:
Rf_warning("Unterminated string at end of file");
return stringToken(token_begin + 1, end_, hasEscapeB, hasEscapeD, row, col);
case STATE_ESCAPE_S:
case STATE_ESCAPE_F:
Rf_warning("Unterminated escape at end of file");
return stringToken(token_begin, end_ - 1, hasEscapeB, hasEscapeD, row, col);
case STATE_FIELD:
return fieldToken(token_begin, end_, hasEscapeB, row, col);
}
return Token(TOKEN_EOF, row, col);
}
private:
void newField() {
col_++;
state_ = STATE_DELIM;
}
void newRecord() {
row_++;
col_ = 0;
state_ = STATE_DELIM;
}
Token fieldToken(SourceIterator begin, SourceIterator end, bool hasEscapeB,
int row, int col) {
return Token(begin, end, row, col, (hasEscapeB) ? this : NULL).flagNA(NA_);
}
Token stringToken(SourceIterator begin, SourceIterator end, bool hasEscapeB,
bool hasEscapeD, int row, int col) {
return Token(begin, end, row, col,
(hasEscapeD || hasEscapeB) ? this : NULL);
}
public:
void unescape(SourceIterator begin, SourceIterator end,
boost::container::string* pOut) {
if (escapeDouble_ && !escapeBackslash_) {
unescapeDouble(begin, end, pOut);
} else if (escapeBackslash_ && !escapeDouble_) {
unescapeBackslash(begin, end, pOut);
} else if (escapeBackslash_ && escapeDouble_) {
Rcpp::stop("Backslash & double escapes not supported at this time");
}
}
void unescapeDouble(SourceIterator begin, SourceIterator end,
boost::container::string* pOut) {
pOut->reserve(end - begin);
bool inEscape = false;
for (SourceIterator cur = begin; cur != end; ++cur) {
if (*cur == quote_) {
if (inEscape) {
pOut->push_back(*cur);
inEscape = false;
} else {
inEscape = true;
}
} else {
pOut->push_back(*cur);
}
}
}
void unescapeBackslash(SourceIterator begin, SourceIterator end,
boost::container::string* pOut) {
pOut->reserve(end - begin);
bool inEscape = false;
for (SourceIterator cur = begin; cur != end; ++cur) {
if (inEscape) {
switch(*cur) {
case '\'': pOut->push_back('\''); break;
case '"': pOut->push_back('"'); break;
case '\\': pOut->push_back('\\'); break;
case 'a': pOut->push_back('\a'); break;
case 'b': pOut->push_back('\b'); break;
case 'f': pOut->push_back('\f'); break;
case 'n': pOut->push_back('\n'); break;
case 'r': pOut->push_back('\r'); break;
case 't': pOut->push_back('\t'); break;
case 'v': pOut->push_back('\v'); break;
default:
if (*cur == delim_ || *cur == quote_) {
pOut->push_back(*cur);
} else {
pOut->push_back('\\');
pOut->push_back(*cur);
Rcpp::warning("Unrecgonised escape '\%s' at [%i, %i]",
*cur, row_ + 1, col_ + 1);
}
break;
}
inEscape = false;
} else {
if (*cur == '\\') {
inEscape = true;
} else {
pOut->push_back(*cur);
}
}
}
}
};
#endif
| [
"[email protected]"
] | |
03f7e4315a0ca1612be6b95c33766f1750fbb96d | a910260a9fce80f2f656bce320297aafa1ef61f9 | /STLNeural/MLP.cpp | a133766b55c1217f0e9f542acebb4efeeb30439f | [] | no_license | ashvardanian/CppNeuralSTL | 0d66b8d483412819b0d5f4ff9fa9aba82346ec47 | 546694e13e5955c5fb5b26496d19fdc1d8120d50 | refs/heads/master | 2022-01-20T08:47:30.407820 | 2019-06-13T11:33:04 | 2019-06-13T11:33:04 | 191,728,338 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,624 | cpp | //
// MLP.cpp
// AILibsComparator
//
// Created by Ashot Vardanian on 6/8/19.
// Copyright © 2019 Ashot Vardanian. All rights reserved.
//
#include "MLP.hpp"
#include "activations.hpp"
#include "losses.hpp"
#include "range.hpp"
#include <array>
#include <iostream>
using namespace av::neural;
using func_activation = Sigmoid;
using func_loss = MeanSquareError;
#pragma mark - Shared
float Perceptron::estimate_error(Matrix const & Yhat, Matrix const & Y) {
Matrix const error = func_loss::values(Yhat, Y);
auto const total = ::range::accumulate(error.flat(), 0.f, std::plus<Weight> { });
return total / Y.rows();
}
#pragma mark - Single Layer Perceptron
Matrix const & SLP::final_activations() const {
return Ao;
}
void SLP::redefine_shape(std::array<Dim, 3> sizes) {
Wh.resize({ sizes[0], sizes[1] }).randomize_uniform(0, 1);
Wo.resize({ sizes[1], sizes[2] }).randomize_uniform(0, 1);
}
void SLP::propagate_forward(Matrix const & X) {
// Hidden layer.
Zh = X * Wh;
Ah = func_activation::values(Zh);
// Output layer.
Zo = Ah * Wo;
Ao = func_activation::values(Zo);
}
void SLP::propagate_backward(Matrix const & X, Matrix const & Y) {
Matrix const & Yhat = final_activations();
error_last = estimate_error(Yhat, Y);
Matrix const error_deriv = func_loss::derivs(Yhat, Y);
// Layer Error.
Matrix const Eo = error_deriv.hadamar(func_activation::derivs(Zo));
Matrix const Eh = (Eo * Wo.transposed()).hadamar(func_activation::derivs(Zh));
// Cost derivative for weights.
Matrix const dWo = Ah.transposed() * Eo;
Matrix const dWh = X.transposed() * Eh;
// Update weights.
Wh = Wh - dWh * learning_rate;
Wo = Wo - dWo * learning_rate;
}
#pragma mark - Multi Layer Perceptron
Matrix const & MLP::final_activations() const {
return As.back();
}
void MLP::redefine_shape(std::vector<Dim> sizes) {
Ws.resize(sizes.size() - 1);
Zs.resize(sizes.size() - 1);
As.resize(sizes.size() - 1);
for (Count Idx = 1; Idx < sizes.size(); Idx ++) {
Ws[Idx-1].resize({ sizes[Idx-1], sizes[Idx] }).randomize_uniform(0, 1);
}
}
void MLP::propagate_forward(Matrix const & X) {
for (int Idx = 0; Idx < Ws.size(); Idx ++) {
auto & W = Ws[Idx];
auto & Z = Zs[Idx];
auto & A = As[Idx];
if (Idx == 0) {
Z = X * W;
A = func_activation::values(Z);
} else {
Z = As[Idx - 1] * W;
A = func_activation::values(Z);
}
}
}
void MLP::propagate_backward(Matrix const & X, Matrix const & Y) {
Matrix const & Yhat = final_activations();
error_last = estimate_error(Yhat, Y);
Matrix const error_deriv = func_loss::derivs(Yhat, Y);
Count const layers_count = Ws.size();
std::vector<Matrix> Es { layers_count };
for (int Idx = int(layers_count) - 1; Idx >= 0; Idx --) {
Matrix const & Z = Zs[Idx];
Matrix const dZ = func_activation::derivs(Z);
// Layer Errors.
Matrix & E = Es[Idx];
if (Idx + 1 == Ws.size()) {
E = error_deriv.hadamar(dZ);
} else {
E = (Es[Idx + 1] * Ws[Idx + 1].transposed()).hadamar(dZ);
}
}
::range::for_each(Idxs { layers_count }, [&](int Idx) {
Matrix const & E = Es[Idx];
// Cost derivative for weights.
Matrix dW;
if (Idx != 0) {
dW = As[Idx-1].transposed() * E;
} else {
dW = X.transposed() * E;
}
// Update weights.
Matrix & W = Ws[Idx];
W = W - dW * learning_rate;
});
}
| [
"[email protected]"
] | |
7662ad72e094d58d90b64abcbb746b0500b253fc | 257fb02e60f0293db4a435dd911f8f02bbf888ab | /Src/Foundation/Utility/Time/Timer.h | f3d3b94a97b3450280055049b70edb882e29c3a3 | [
"MIT"
] | permissive | prophecy/Wonderland | 6d7cb6f8a523672810f352eaed24aba1de0b4b3a | a60b07857e66312ee94d69678b1ca8c97b1a19eb | refs/heads/master | 2021-01-18T09:30:45.761010 | 2016-10-19T10:01:37 | 2016-10-19T10:01:37 | 42,950,457 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,586 | h | /*
* This source file is part of Wonderland, the C++ Cross-platform middleware for game
*
* For the latest information, see https://github.com/prophecy/Wonderland
*
* The MIT License (MIT)
* Copyright (c) 2015 Adawat Chanchua
*
* 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.
*
*/
#ifndef __TIMER_H__
#define __TIMER_H__
#include "Utility/Utility.h"
class Timer
{
public:
static void Update();
static f32 GetDeltaTime();
static f32 GetFps();
static f64 GetHighPrecisionDeltaTime();
static f64 GetHighPrecisionFps();
};
#endif // __TIMER_H__ | [
"[email protected]"
] | |
5ae15f3346c82a79f0d1a1c9377be8ce3d0980e4 | 1802c020489329b72043a1d492b9831b28bb5745 | /include/roboticarts_leds/leds_mux.h | c329bbfb03d3dfa088fdbfbdde3e564796430f33 | [] | no_license | RoboticArts/roboticarts_leds | 3d93f9b8be994d94968361008347205fdbc8137a | 236598cc6374e25b4b443a1c69022cca0aa268a4 | refs/heads/master | 2023-02-03T13:47:03.972674 | 2020-12-20T00:57:54 | 2020-12-20T00:57:54 | 292,396,212 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | h | #ifndef LEDS_MUX_H
#define LEDS_MUX_H
#include "ros/ros.h"
#include <xmlrpcpp/XmlRpcValue.h>
#include <roboticarts_leds/SetLeds.h>
#include <roboticarts_leds/service_handler.h>
#define MAX_SERVICIES 255
class LedsMux{
public:
LedsMux(ros::NodeHandle nodehandle);
void run();
private:
ros::NodeHandle _nh;
std::string nodeName;
XmlRpc::XmlRpcValue leds_mux;
std::string cmd_leds_output_name;
int valid_services_counter;
ServiceHandler *leds_service[MAX_SERVICIES];
struct ServiceProperties{
std::string name;
std::string service_name;
double timeout;
int priority;
bool status;
};
void readRosParams();
void createServiceMultiplexer();
ServiceProperties getServiceProperties(int service);
void runMuxTimeout();
};
#endif | [
"[email protected]"
] | |
40d5646c50d6f877fafda5a696c71a943522662a | 3846cf64aa57ccf3c9672d8ed76952d019cddcbe | /BTVN/BT04/BT04Mystery.cpp | 2abdcba6b34aec072665fbcc27946c5c5ccadc42 | [] | no_license | Adriannguyen/LTNC | c31c75ed9b2a88c3a071beaea6663b0f5f4cb464 | 10736ec710772396f5827a572e0ae4a848fdad11 | refs/heads/master | 2023-06-22T12:14:11.728421 | 2021-07-20T00:14:29 | 2021-07-20T00:14:29 | 333,381,280 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 797 | cpp | #include <bits/stdc++.h>
using namespace std;
void manSort(int* arr, int num) {
for(int i = 0; i < num-1; ++i) {
for (int j = i +1; j < num;++j) {
if(arr[i] > arr[j]) {
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
}
}
int main(){
int num;
cin >> num;
int arr1[num];
int arr2[num+1];
for(int i = 0; i < num; i++) {
cin >> arr1[i];
}
for(int i = 0; i < num+1; i++) {
cin >> arr2[i];
}
manSort(arr1, num);
manSort(arr2, num+1);
bool end = false;
for(int i = 0; i < num; ++i) {
if(arr1[i] != arr2[i]) {
end = true;
cout << arr2[i];
return 0;
}
}
if(!end) cout << arr2[num];
}
| [
"[email protected]"
] | |
c4e629974b660048955b3baebd69453dbf40aa1e | 33c4bc9ca463ce0ec61945fca5841c9d8a18ab8e | /thrift/lib/cpp2/transport/rsocket/test/util/TestServiceMock.h | a9713a5ab3909a519a9f93ec41cec55f1cb2f748 | [
"Apache-2.0"
] | permissive | gaurav1086/fbthrift | d54bb343bf1a8503dd329fbfcd0b46fe9f70754c | 68d1a8790bfd5b3974e1b966c8071f9c456b6c6a | refs/heads/master | 2020-12-27T22:41:09.452839 | 2020-02-03T23:56:20 | 2020-02-03T23:58:33 | 238,088,855 | 0 | 0 | Apache-2.0 | 2020-02-04T00:13:04 | 2020-02-04T00:13:03 | null | UTF-8 | C++ | false | false | 2,511 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/portability/GMock.h>
#include <folly/io/async/ScopedEventBaseThread.h>
#include <thrift/lib/cpp2/transport/rsocket/test/util/gen-cpp2/StreamService.h>
namespace testutil {
namespace testservice {
class TestServiceMock : public StreamServiceSvIf {
public:
TestServiceMock() {}
int32_t echo(int32_t value) override;
apache::thrift::Stream<int32_t> range(int32_t from, int32_t to) override;
apache::thrift::Stream<int32_t>
slowRange(int32_t from, int32_t to, int32_t millis) override;
apache::thrift::Stream<int32_t> slowCancellation() override;
apache::thrift::Stream<Message> returnNullptr() override;
apache::thrift::ResponseAndStream<int, Message> throwError() override;
apache::thrift::ResponseAndStream<int32_t, int32_t> leakCheck(
int32_t from,
int32_t to) override;
apache::thrift::ResponseAndStream<int32_t, int32_t>
leakCheckWithSleep(int32_t from, int32_t to, int32_t sleepMs) override;
int32_t instanceCount() override;
apache::thrift::ResponseAndStream<int32_t, int32_t> sleepWithResponse(
int32_t timeMs) override;
apache::thrift::Stream<int32_t> sleepWithoutResponse(int32_t timeMs) override;
apache::thrift::ResponseAndStream<int32_t, int32_t> streamServerSlow()
override;
void sendMessage(int32_t messageId, bool complete, bool error) override;
apache::thrift::Stream<int32_t> registerToMessages() override;
apache::thrift::Stream<Message> streamThrows(int32_t whichEx) override;
apache::thrift::ResponseAndStream<int32_t, Message> responseAndStreamThrows(
int32_t whichEx) override;
apache::thrift::Stream<int32_t> requestWithBlob(
std::unique_ptr<folly::IOBuf> val) override;
protected:
folly::ScopedEventBaseThread executor_;
std::unique_ptr<apache::thrift::StreamPublisher<int32_t>> messages_;
};
} // namespace testservice
} // namespace testutil
| [
"[email protected]"
] | |
e96a68a69ff84497dc479e1e741dfd2914dfb7bf | 4bad7578931dd47c38dc283aec7eb961be6e1f30 | /src/cryptonote_basic/difficulty.h | d270f1ab9de97ce5933599b5191fd86361850ac0 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | cyberstormdotmu/electroneum-classic | d034453071a3c9fa37f494c212e3ffc6d0effc9b | 494bd2b5f9d9d759c10568e0326dde1737cefad6 | refs/heads/master | 2020-04-01T06:25:43.262217 | 2018-10-17T04:16:13 | 2018-10-17T04:16:13 | 152,947,188 | 0 | 0 | null | 2018-10-14T06:47:32 | 2018-10-14T06:47:32 | null | UTF-8 | C++ | false | false | 2,936 | h | // Copyrights(c) 2018, The Electroneum Classic Project
// Copyrights(c) 2017-2018, The Electroneum Project
// Copyrights(c) 2014-2017, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers
#pragma once
#include <cstdint>
#include <vector>
#include "crypto/hash.h"
namespace cryptonote
{
typedef std::uint64_t difficulty_type;
/**
* @brief checks if a hash fits the given difficulty
*
* The hash passes if (hash * difficulty) < 2^256.
* Phrased differently, if (hash * difficulty) fits without overflow into
* the least significant 256 bits of the 320 bit multiplication result.
*
* @param hash the hash to check
* @param difficulty the difficulty to check against
*
* @return true if valid, else false
*/
bool check_hash(const crypto::hash &hash, difficulty_type difficulty);
difficulty_type next_difficulty(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds, uint8_t version = 1);
difficulty_type next_difficulty_v2(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds);
difficulty_type next_difficulty_v3(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds);
}
| [
"[email protected]"
] | |
dc7d6c82702ce2b40f21c5ea5303aaaa00362165 | 45364deefe009a0df9e745a4dd4b680dcedea42b | /SDK/FSD_AudioCapture_classes.hpp | 13366c7c11b9ebc9fe5d25df13566250811eb3d1 | [] | no_license | RussellJerome/DeepRockGalacticSDK | 5ae9b59c7324f2a97035f28545f92773526ed99e | f13d9d8879a645c3de89ad7dc6756f4a7a94607e | refs/heads/master | 2022-11-26T17:55:08.185666 | 2020-07-26T21:39:30 | 2020-07-26T21:39:30 | 277,796,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 962 | hpp | #pragma once
// DeepRockGalactic SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "FSD_AudioCapture_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// Class AudioCapture.AudioCaptureComponent
// 0x00B0 (0x0720 - 0x0670)
class UAudioCaptureComponent : public USynthComponent
{
public:
int JitterLatencyFrames; // 0x0670(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
unsigned char UnknownData00[0xAC]; // 0x0674(0x00AC) MISSED OFFSET
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class AudioCapture.AudioCaptureComponent");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
b5564312d869c1375fe9a6cdaafc1e996414ffea | 7667b22de9200b5ebdb53427c1f1f64b3fde588b | /Game/Game/LoadScreen.h | 097fcde5c5bfcf74b152ed63f411b9e793272273 | [] | no_license | aguspoles/GameSFML | 6650302f6efe327b9697e06e52ebb71f0bb6204f | bf884faa894d365151a1eb42bdf8e47b4e635528 | refs/heads/master | 2020-12-30T15:08:02.924204 | 2017-06-30T14:12:27 | 2017-06-30T14:12:27 | 93,110,794 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | h | #ifndef LOADSCREEN_H
#define LOADSCREEN_H
#include "Level.h"
class LoadScreen :
public Game
{
private:
bool _loaded;
sf::Text _text;
sf::Font _font;
const std::string FONTS_PATH = "Assets/Fonts/";
public:
LoadScreen();
~LoadScreen();
void Run();
void Update();
void Draw();
void Init();
void Destroy();
void LoadAssets();
};
#endif | [
"[email protected]"
] | |
51615f6001d7b9dde93a0833b48853d3efb00cba | 86b7a918b73855acde09b910271b277255e60644 | /DataStructures/SearchEngine.h | 0d7d35dbe3aa70708c96678711acb72ce0453c67 | [
"BSD-2-Clause"
] | permissive | sbrunner/osrm.deb | aff0692e6316d7a2b0f33b204de5c009e071e5c2 | 915c5f296e50886821f8585d590c2bd91a848c06 | refs/heads/master | 2020-05-17T19:37:43.483783 | 2013-10-16T14:57:48 | 2013-10-16T14:57:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,487 | h | /*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SEARCHENGINE_H_
#define SEARCHENGINE_H_
#include "Coordinate.h"
#include "NodeInformationHelpDesk.h"
#include "PhantomNodes.h"
#include "QueryEdge.h"
#include "SearchEngineData.h"
#include "../RoutingAlgorithms/AlternativePathRouting.h"
#include "../RoutingAlgorithms/ShortestPathRouting.h"
#include "../Server/DataStructures/QueryObjectsStorage.h"
#include "../Util/StringUtil.h"
#include "../typedefs.h"
#include <climits>
#include <string>
#include <vector>
class SearchEngine {
private:
SearchEngineData _queryData;
public:
ShortestPathRouting<SearchEngineData> shortestPath;
AlternativeRouting<SearchEngineData> alternativePaths;
SearchEngine( QueryObjectsStorage * query_objects );
~SearchEngine();
void GetCoordinatesForNodeID(NodeID id, FixedPointCoordinate& result) const;
void FindPhantomNodeForCoordinate(
const FixedPointCoordinate & location,
PhantomNode & result,
unsigned zoomLevel
) const;
NodeID GetNameIDForOriginDestinationNodeID(
const NodeID s, const NodeID t) const;
std::string GetEscapedNameForNameID(const unsigned nameID) const;
};
#endif /* SEARCHENGINE_H_ */
| [
"[email protected]"
] | |
715292b5c74b6180657d8209ff2afa5eccd23f51 | 903767e9e1bd7ae4c273621f2787e8e93ed38553 | /Codeforces/Div2/prev/659/C.cpp | 53312cf6b66f6a707662b80c04789439de111323 | [] | no_license | itohdak/Competitive_Programming | 609e6a9e17a4fa21b8f3f7fc9bbc13204d7f7ac4 | e14ab7a92813755d97a85be4ead68620753a6d4b | refs/heads/master | 2023-08-04T08:57:55.546063 | 2023-08-01T21:09:28 | 2023-08-01T21:09:28 | 304,704,923 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,796 | cpp | #include <bits/stdc++.h>
#include <print.hpp>
using namespace std;
#define ll long long
#define ld long double
#define REP(i,m,n) for(int i=(int)(m); i<(int)(n); i++)
#define rep(i,n) REP(i,0,n)
#define RREP(i,m,n) for(int i=(int)(m); i>=(int)(n); i--)
#define rrep(i,n) RREP(i,(n)-1,0)
#define all(v) v.begin(), v.end()
#define endk '\n'
const int inf = 1e9+7;
const ll longinf = 1LL<<60;
const ll mod = 1e9+7;
const ld eps = 1e-10;
template<typename T1, typename T2> inline void chmin(T1 &a, T2 b){if(a>b) a=b;}
template<typename T1, typename T2> inline void chmax(T1 &a, T2 b){if(a<b) a=b;}
#define MAX_N 200005
class UnionFind
{
public:
int par[MAX_N];
int depth[MAX_N];
int nGroup[MAX_N];
UnionFind(int n) {
init(n);
}
void init(int n) {
for(int i=0; i<n; i++) {
par[i] = i;
depth[i] = 0;
nGroup[i] = 1;
}
}
int root(int x) {
if(par[x] == x) {
return x;
} else {
return par[x] = root(par[x]);
}
}
bool same(int x, int y) {
return root(x) == root(y);
}
void unite(int x, int y) {
x = root(x);
y = root(y);
if(x == y) return;
if(depth[x] < depth[y]) {
par[x] = y;
nGroup[y] += nGroup[x];
nGroup[x] = 0;
} else {
par[y] = x;
nGroup[x] += nGroup[y];
nGroup[y] = 0;
if(depth[x] == depth[y])
depth[x]++;
}
}
};
void solve() {
int n; cin >> n;
string a, b; cin >> a >> b;
UnionFind uf(20);
int ans = 0;
rep(i, n) {
if(a[i] > b[i]) {
cout << -1 << endk;
return;
}
if(!uf.same(a[i]-'a', b[i]-'a')) {
ans++;
uf.unite(a[i]-'a', b[i]-'a');
}
}
cout << ans << endk;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int T;
cin >> T;
while(T--) solve();
return 0;
}
| [
"[email protected]"
] | |
0b57c3fd39867bb8b372648bb02709e9fa7e4d93 | 7250574efb657928b76ba3df4412cf0b39666673 | /src/file/file_manage.cpp | 772332ff8c219e33ce857018ee8414f26f750c3f | [] | no_license | YIDWang/llylog | 920d9c1254439213701020dd0ce72168e5994581 | 8cc35fc55bd90d33fbea9ad73b6484c5ef92fc3a | refs/heads/master | 2021-01-18T20:27:31.303648 | 2017-04-10T10:22:01 | 2017-04-10T10:22:01 | 86,968,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,691 | cpp | #include "file_manage.h"
FileManage::FileManage(stDiv *div,std::string path,std::string name){
m_strPath = path;
m_strFileName = name;
for (int i = 0 ; i < 4 ; i++){
m_mapFilePool[i+1] = std::shared_ptr<FileOpr>(new FileOpr());
m_mapMes[i+1] = std::shared_ptr<stDiv>(new stDiv());
m_mapMes[i+1]-> type = div->type;
m_mapMes[i+1]-> divMessage = div->divMessage;
open(i+1);
}
}
FileManage::~FileManage(){
m_mapFilePool.clear();
m_mapMes.clear();
}
int FileManage::Operater(int type,std::string msg){
if(wirte(type,msg) !=0){
return -1;
}
return 0;
}
int FileManage::checkFile(int type){
std::shared_ptr<FileOprImp> file = m_mapFilePool[type];
std::cout<<"check:"<<m_mapMes[type]->type<<std::endl;
switch (m_mapMes[type]->type){
case 1:{
int size = file->Size();
std::cout<<"checkfile:"<<type<<" "<<m_mapMes[type]->divMessage.size.size<<" "<<size<<std::endl;
if(m_mapMes[type]->divMessage.size.size <= size){
return reOpen(type);
}
break;
}
case 0:{
time_t start = m_mapMes[type]->divMessage.time.divTime;
time_t end = time(NULL);
unsigned long interval = m_mapMes[type]->divMessage.time.interval;
if (difftime(end,start) >= interval){
// std::cout<<"checkfile:"<<type<<" "<<m_mapMes[type]->divMessage.time.interval<<" "<<m_mapMes[type]->divMessage.time.divTime<<std::endl;
m_mapMes[type]->divMessage.time.divTime = end;
return reOpen(type);
}
break;
}
}
return 0;
}
int FileManage::wirte(int type,std::string msg){
// std::cout<<type<<" "<<msg<<std::endl;
if(checkFile(type)){
return -1;
}
return m_mapFilePool[type]->Write(msg);
}
int FileManage::open(int type){
// std::string timeTemp = NowTime();
std::string strNewFileName = m_strFileName+ "-" + Level(type);
if(m_mapFilePool[type]->Open(m_strPath,strNewFileName) !=0){
return -1;
}
if(!m_mapMes[type]->type){
m_mapMes[type]->divMessage.time.divTime = time(NULL);
}
return 0;
}
int FileManage::reOpen(int type){
std::string time = NowTime();
std::string strNewFileName = m_strFileName +"-"+ time + "-"+Level(type);
std::shared_ptr<FileOprImp> file = m_mapFilePool[type];
if(file->ReName(strNewFileName)!= 0){
return -1;
}
return 0;
}
| [
"[email protected]"
] | |
962ccaa8ab8c86b4182593e3f558e9869cd46dc1 | 52b148a3d5b2d1c5285445df9fb1816dbf4f6248 | /bitmap_interfaces/asteroids_interface.h | 00e3613aea268e1e63e268872ea7e95b7e39e405 | [] | no_license | quebin31/spaceship-cpp | fa7bcf063b80d8926142caef6cb9bfdbfed8a866 | 41f3a36edf6f2b0707e9490e861ab1b5878019fa | refs/heads/master | 2023-04-29T18:48:04.599314 | 2023-04-21T03:37:41 | 2023-04-21T03:37:41 | 74,414,776 | 0 | 0 | null | 2023-04-21T03:37:42 | 2016-11-21T23:23:44 | C++ | UTF-8 | C++ | false | false | 2,099 | h | //
// Created by kevin on 7/12/16.
//
#ifndef SPACESHIP2_ASTEROIDS_INTERFACE_H
#define SPACESHIP2_ASTEROIDS_INTERFACE_H
#include "../bitmap_objects/asteroid.h"
class AsteroidFactory;
class AsteroidObjPool;
class AsteroidInterface;
class AsteroidFactory
{
private:
static int fps_to_gen;
private:
static int generate_random_num_of_asters();
static int generate_random_fps_count();
static Asteroid* check_store(AsteroidObjPool* setofasters);
public:
static int getFpsToGen();
static void generateRowFor(AsteroidObjPool *setofasters);
};
class AsteroidObjPool
{
private:
std::vector<Asteroid*> asters_on_use;
std::vector<Asteroid*> store;
private:
friend class AsteroidFactory;
friend class AsteroidInterface;
public:
class Iterator
{
private:
AsteroidObjPool* ap;
int index;
private:
friend class AsteroidObjPool;
public:
Iterator(AsteroidObjPool& _ap);
Iterator(AsteroidObjPool* _ap);
Iterator(const Iterator& itr);
Iterator& operator++();
Iterator operator++(int);
Iterator operator+(const int sum);
bool operator==(const Iterator& itr);
bool operator!=(const Iterator& itr);
Asteroid* operator*();
int getIndex();
};
AsteroidObjPool();
~AsteroidObjPool();
Asteroid* at(const int index);
Asteroid* operator[](const int index);
std::size_t size();
void erase(Iterator& itr);
Iterator begin();
Iterator end();
};
class AsteroidInterface
{
private:
static AsteroidObjPool *asteroidOP;
public:
static void createAsteroidObjPool();
static void deleteAsteroidObjPool();
static void updateAsteroids(int64_t actual_frames_count);
static void eraseAsteroid(AsteroidObjPool::Iterator &itr);
static AsteroidObjPool::Iterator getBegin();
static AsteroidObjPool::Iterator getEnd();
static AsteroidObjPool* getAOP();
static void reset_asteroids();
};
#endif //SPACESHIP2_ASTEROIDS_INTERFACE_H
| [
"[email protected]"
] | |
3b8bdc4819944b675637e102242f59c66791de9a | 536656cd89e4fa3a92b5dcab28657d60d1d244bd | /third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.cc | cbdcc36d04606f3e4cbfe7a71e8ddbf026510b8d | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | ECS-251-W2020/chromium | 79caebf50443f297557d9510620bf8d44a68399a | ac814e85cb870a6b569e184c7a60a70ff3cb19f9 | refs/heads/master | 2022-08-19T17:42:46.887573 | 2020-03-18T06:08:44 | 2020-03-18T06:08:44 | 248,141,336 | 7 | 8 | BSD-3-Clause | 2022-07-06T20:32:48 | 2020-03-18T04:52:18 | null | UTF-8 | C++ | false | false | 14,423 | cc | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/peerconnection/rtc_quic_stream.h"
#include "base/containers/span.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
namespace blink {
// 6 MB allows a reasonable amount to buffer on the read and write side.
// TODO(https://crbug.com/874296): Consider exposing these configurations.
const uint32_t RTCQuicStream::kWriteBufferSize = 6 * 1024 * 1024;
const uint32_t RTCQuicStream::kReadBufferSize = 6 * 1024 * 1024;
class RTCQuicStream::PendingReadBufferedAmountPromise
: public GarbageCollected<PendingReadBufferedAmountPromise> {
public:
PendingReadBufferedAmountPromise(ScriptPromiseResolver* promise_resolver,
uint32_t readable_amount)
: promise_resolver_(promise_resolver),
readable_amount_(readable_amount) {}
ScriptPromiseResolver* promise_resolver() const { return promise_resolver_; }
uint32_t readable_amount() const { return readable_amount_; }
void Trace(Visitor* visitor) { visitor->Trace(promise_resolver_); }
private:
Member<ScriptPromiseResolver> promise_resolver_;
uint32_t readable_amount_;
};
class RTCQuicStream::PendingWriteBufferedAmountPromise
: public GarbageCollected<PendingWriteBufferedAmountPromise> {
public:
PendingWriteBufferedAmountPromise(ScriptPromiseResolver* promise_resolver,
uint32_t threshold)
: promise_resolver_(promise_resolver), threshold_(threshold) {}
ScriptPromiseResolver* promise_resolver() const { return promise_resolver_; }
uint32_t threshold() const { return threshold_; }
void Trace(Visitor* visitor) { visitor->Trace(promise_resolver_); }
private:
Member<ScriptPromiseResolver> promise_resolver_;
uint32_t threshold_;
};
RTCQuicStream::RTCQuicStream(ExecutionContext* context,
RTCQuicTransport* transport,
QuicStreamProxy* stream_proxy)
: ExecutionContextClient(context),
transport_(transport),
proxy_(stream_proxy) {
DCHECK(transport_);
DCHECK(proxy_);
}
RTCQuicStream::~RTCQuicStream() = default;
RTCQuicTransport* RTCQuicStream::transport() const {
return transport_;
}
String RTCQuicStream::state() const {
switch (state_) {
case RTCQuicStreamState::kNew:
return "new";
case RTCQuicStreamState::kOpening:
return "opening";
case RTCQuicStreamState::kOpen:
return "open";
case RTCQuicStreamState::kClosing:
return "closing";
case RTCQuicStreamState::kClosed:
return "closed";
}
return String();
}
uint32_t RTCQuicStream::readBufferedAmount() const {
return receive_buffer_.size();
}
uint32_t RTCQuicStream::maxReadBufferedAmount() const {
return kReadBufferSize;
}
uint32_t RTCQuicStream::writeBufferedAmount() const {
return write_buffered_amount_;
}
uint32_t RTCQuicStream::maxWriteBufferedAmount() const {
return kWriteBufferSize;
}
RTCQuicStreamReadResult* RTCQuicStream::readInto(
NotShared<DOMUint8Array> data,
ExceptionState& exception_state) {
if (RaiseIfNotReadable(exception_state)) {
return 0;
}
uint32_t read_amount = static_cast<uint32_t>(receive_buffer_.ReadInto(
base::make_span(data.View()->Data(), data.View()->lengthAsSizeT())));
if (!received_fin_ && read_amount > 0) {
proxy_->MarkReceivedDataConsumed(read_amount);
}
if (receive_buffer_.empty() && received_fin_) {
read_fin_ = true;
if (wrote_fin_) {
DCHECK_EQ(state_, RTCQuicStreamState::kClosing);
Close(CloseReason::kReadWriteFinished);
} else {
DCHECK_EQ(state_, RTCQuicStreamState::kOpen);
state_ = RTCQuicStreamState::kClosing;
}
}
auto* result = RTCQuicStreamReadResult::Create();
result->setAmount(read_amount);
result->setFinished(read_fin_);
return result;
}
void RTCQuicStream::write(const RTCQuicStreamWriteParameters* data,
ExceptionState& exception_state) {
bool finish = data->finish();
bool has_write_data =
data->hasData() && data->data().View()->lengthAsSizeT() > 0;
if (!has_write_data && !finish) {
exception_state.ThrowDOMException(
DOMExceptionCode::kNotSupportedError,
"Cannot write empty data, unless data.finish is set to true.");
return;
}
if (RaiseIfNotWritable(exception_state)) {
return;
}
Vector<uint8_t> data_vector;
if (has_write_data) {
DOMUint8Array* write_data = data->data().View();
size_t remaining_write_buffer_size =
kWriteBufferSize - writeBufferedAmount();
if (write_data->lengthAsSizeT() > remaining_write_buffer_size) {
exception_state.ThrowDOMException(
DOMExceptionCode::kOperationError,
"The write data size of " +
String::Number(write_data->lengthAsSizeT()) +
" bytes would exceed the remaining write buffer size of " +
String::Number(remaining_write_buffer_size) + " bytes.");
return;
}
data_vector.resize(static_cast<wtf_size_t>(write_data->lengthAsSizeT()));
memcpy(data_vector.data(), write_data->Data(), write_data->lengthAsSizeT());
write_buffered_amount_ +=
static_cast<uint32_t>(write_data->lengthAsSizeT());
}
proxy_->WriteData(std::move(data_vector), finish);
if (finish) {
wrote_fin_ = true;
if (!read_fin_) {
DCHECK_EQ(state_, RTCQuicStreamState::kOpen);
state_ = RTCQuicStreamState::kClosing;
RejectPendingWaitForWriteBufferedAmountBelowPromises();
} else {
DCHECK_EQ(state_, RTCQuicStreamState::kClosing);
Close(CloseReason::kReadWriteFinished);
}
}
}
void RTCQuicStream::reset() {
if (IsClosed()) {
return;
}
Close(CloseReason::kLocalReset);
}
ScriptPromise RTCQuicStream::waitForReadable(ScriptState* script_state,
uint32_t amount,
ExceptionState& exception_state) {
if (RaiseIfNotReadable(exception_state)) {
return ScriptPromise();
}
if (amount > kReadBufferSize) {
exception_state.ThrowTypeError(
"The amount " + String::Number(amount) +
" is greater than the maximum read buffer size of " +
String::Number(kReadBufferSize) + ".");
return ScriptPromise();
}
auto* promise_resolver =
MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = promise_resolver->Promise();
if (received_fin_ || receive_buffer_.size() >= amount) {
promise_resolver->Resolve();
} else {
pending_read_buffered_amount_promises_.push_back(
MakeGarbageCollected<PendingReadBufferedAmountPromise>(promise_resolver,
amount));
}
return promise;
}
ScriptPromise RTCQuicStream::waitForWriteBufferedAmountBelow(
ScriptState* script_state,
uint32_t threshold,
ExceptionState& exception_state) {
if (RaiseIfNotWritable(exception_state)) {
return ScriptPromise();
}
auto* promise_resolver =
MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = promise_resolver->Promise();
if (write_buffered_amount_ <= threshold) {
promise_resolver->Resolve();
} else {
pending_write_buffered_amount_promises_.push_back(
MakeGarbageCollected<PendingWriteBufferedAmountPromise>(
promise_resolver, threshold));
}
return promise;
}
bool RTCQuicStream::RaiseIfNotReadable(ExceptionState& exception_state) {
if (read_fin_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"The stream is not readable: The end of the stream has been read.");
return true;
}
if (IsClosed()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"The stream is not readable: The stream is closed.");
return true;
}
return false;
}
bool RTCQuicStream::RaiseIfNotWritable(ExceptionState& exception_state) {
if (wrote_fin_) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"The stream is not writable: finish() has been called.");
return true;
}
if (IsClosed()) {
exception_state.ThrowDOMException(
DOMExceptionCode::kInvalidStateError,
"The stream is not writable: The stream is closed.");
return true;
}
return false;
}
void RTCQuicStream::RejectPendingWaitForReadablePromises() {
// TODO(https://github.com/w3c/webrtc-quic/issues/81): The promise resolve
// order is under specified.
for (PendingReadBufferedAmountPromise* pending_promise :
pending_read_buffered_amount_promises_) {
ScriptState::Scope scope(
pending_promise->promise_resolver()->GetScriptState());
ExceptionState exception_state(
pending_promise->promise_resolver()->GetScriptState()->GetIsolate(),
ExceptionState::kExecutionContext, "RTCQuicStream", "waitForReadable");
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"The RTCQuicStream is not readable.");
pending_promise->promise_resolver()->Reject(exception_state);
}
pending_read_buffered_amount_promises_.clear();
}
void RTCQuicStream::RejectPendingWaitForWriteBufferedAmountBelowPromises() {
// TODO(https://github.com/w3c/webrtc-quic/issues/81): The promise resolve
// order is under specified.
for (PendingWriteBufferedAmountPromise* pending_promise :
pending_write_buffered_amount_promises_) {
ScriptState::Scope scope(
pending_promise->promise_resolver()->GetScriptState());
ExceptionState exception_state(
pending_promise->promise_resolver()->GetScriptState()->GetIsolate(),
ExceptionState::kExecutionContext, "RTCQuicStream",
"waitForWriteBufferedAmountBelow");
exception_state.ThrowDOMException(DOMExceptionCode::kInvalidStateError,
"The stream is no longer writable.");
pending_promise->promise_resolver()->Reject(exception_state);
}
pending_write_buffered_amount_promises_.clear();
}
void RTCQuicStream::OnRemoteReset() {
Close(CloseReason::kRemoteReset);
}
void RTCQuicStream::OnDataReceived(Vector<uint8_t> data, bool fin) {
DCHECK(!received_fin_);
DCHECK_LE(data.size(), kReadBufferSize - receive_buffer_.size());
received_fin_ = fin;
receive_buffer_.Append(std::move(data));
// TODO(https://github.com/w3c/webrtc-quic/issues/81): The promise resolve
// order is under specified.
for (auto* it = pending_read_buffered_amount_promises_.begin();
it != pending_read_buffered_amount_promises_.end();
/* incremented manually */) {
PendingReadBufferedAmountPromise* pending_promise = *it;
if (received_fin_ ||
receive_buffer_.size() >= pending_promise->readable_amount()) {
pending_promise->promise_resolver()->Resolve();
it = pending_read_buffered_amount_promises_.erase(it);
} else {
++it;
}
}
}
void RTCQuicStream::OnWriteDataConsumed(uint32_t amount) {
DCHECK_GE(write_buffered_amount_, amount);
write_buffered_amount_ -= amount;
// TODO(https://github.com/w3c/webrtc-quic/issues/81): The promise resolve
// order is under specified.
for (auto* it = pending_write_buffered_amount_promises_.begin();
it != pending_write_buffered_amount_promises_.end();
/* incremented manually */) {
PendingWriteBufferedAmountPromise* pending_promise = *it;
if (write_buffered_amount_ <= pending_promise->threshold()) {
pending_promise->promise_resolver()->Resolve();
it = pending_write_buffered_amount_promises_.erase(it);
} else {
++it;
}
}
}
void RTCQuicStream::OnQuicTransportClosed(
RTCQuicTransport::CloseReason reason) {
switch (reason) {
case RTCQuicTransport::CloseReason::kContextDestroyed:
Close(CloseReason::kContextDestroyed);
break;
default:
Close(CloseReason::kQuicTransportClosed);
break;
}
}
void RTCQuicStream::Close(CloseReason reason) {
DCHECK_NE(state_, RTCQuicStreamState::kClosed);
// Tear down the QuicStreamProxy.
// If the Close is caused by a remote event or regular use of WriteData, the
// QuicStreamProxy will have already been deleted.
// If the Close is caused by the transport then the transport is responsible
// for deleting the QuicStreamProxy.
if (reason == CloseReason::kLocalReset) {
// This deletes the QuicStreamProxy.
proxy_->Reset();
}
proxy_ = nullptr;
// Remove this stream from the RTCQuicTransport unless closing from a
// transport-level event.
switch (reason) {
case CloseReason::kReadWriteFinished:
case CloseReason::kLocalReset:
case CloseReason::kRemoteReset:
transport_->RemoveStream(this);
break;
case CloseReason::kQuicTransportClosed:
case CloseReason::kContextDestroyed:
// The RTCQuicTransport will handle clearing its list of streams.
break;
}
// Clear observable state.
receive_buffer_.Clear();
write_buffered_amount_ = 0;
// It's illegal to resolve or reject promises when the ExecutionContext is
// being destroyed.
if (reason != CloseReason::kContextDestroyed) {
RejectPendingWaitForReadablePromises();
RejectPendingWaitForWriteBufferedAmountBelowPromises();
}
// Change the state. Fire the statechange event only if the close is caused by
// a remote stream event.
state_ = RTCQuicStreamState::kClosed;
if (reason == CloseReason::kRemoteReset) {
DispatchEvent(*Event::Create(event_type_names::kStatechange));
}
}
const AtomicString& RTCQuicStream::InterfaceName() const {
return event_target_names::kRTCQuicStream;
}
ExecutionContext* RTCQuicStream::GetExecutionContext() const {
return ExecutionContextClient::GetExecutionContext();
}
void RTCQuicStream::Trace(Visitor* visitor) {
visitor->Trace(transport_);
visitor->Trace(pending_read_buffered_amount_promises_);
visitor->Trace(pending_write_buffered_amount_promises_);
EventTargetWithInlineData::Trace(visitor);
ExecutionContextClient::Trace(visitor);
}
} // namespace blink
| [
"[email protected]"
] | |
dd030c99029b6367f4fb31e3c5d563e5f84896cb | 75732426f13d523ab1c7be7bee23c2152eb9a77c | /bundles/remote_services/remote_service_admin_shm_v2/rsa_shm/gtest/src/thpool_ei.cc | 7d9369a58377984ca071c6a622f1b7557b8038fd | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | apache/celix | 841da4d364432bff49c796f908d64090cec1d759 | 28118976b802f421f4789ece0c15e791f542712f | refs/heads/master | 2023-09-04T22:17:43.815664 | 2023-09-04T01:22:00 | 2023-09-04T01:22:00 | 22,781,134 | 158 | 114 | Apache-2.0 | 2023-09-12T01:22:30 | 2014-08-09T07:00:07 | C | UTF-8 | C++ | false | false | 1,479 | cc | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
//TODO: Move it to libs/error_injector and use conan to import thpool
#include "thpool_ei.h"
extern "C" {
struct thpool_* __real_thpool_init(int num_threads);
CELIX_EI_DEFINE(thpool_init, struct thpool_*)
struct thpool_* __wrap_thpool_init(int num_threads) {
CELIX_EI_IMPL(thpool_init);
return __real_thpool_init(num_threads);
}
int __real_thpool_add_work(struct thpool_* thpool_p, void (*function_p)(void*), void* arg_p);
CELIX_EI_DEFINE(thpool_add_work, int)
int __wrap_thpool_add_work(struct thpool_* thpool_p, void (*function_p)(void*), void* arg_p) {
CELIX_EI_IMPL(thpool_add_work);
return __real_thpool_add_work(thpool_p, function_p, arg_p);
}
} | [
"[email protected]"
] | |
4e045e94db73ebc09a1f439ce30b4514c2f4a572 | 22ee7658700691218e586d90837d491e2c64a89d | /src/fcst/include/layers/conventional_CL.h | 69b26d74581db5b19fcd6900675c29609bed7093 | [
"MIT",
"DOC"
] | permissive | Aslan-Kosakian/OpenFCSTv03 | 1099cf8468aa868d788dff334596448fe0449076 | 00a721a58341b287b52cec36bfaff741fd3a7ee3 | refs/heads/master | 2021-01-12T09:37:33.261888 | 2017-01-16T17:05:49 | 2017-01-16T17:05:49 | 76,203,415 | 0 | 0 | null | 2016-12-11T22:15:03 | 2016-12-11T22:15:03 | null | UTF-8 | C++ | false | false | 33,069 | h | //---------------------------------------------------------------------------
//
// FCST: Fuel Cell Simulation Toolbox
//
// Copyright (C) 2006-13 by Energy Systems Design Laboratory, University of Alberta
//
// This software is distributed under the MIT License.
// For more information, see the README file in /doc/LICENSE
//
// - Class: conventional_cl.h
// - Description: Class characterizing the conventional catalyst layer and methods for computing effective properties. It also provides interface to various material classes used in catalyst layer.
// - Developers: Peter Dobson (2011) and Madhur Bhaiya (2013)
// - Id: $Id: conventional_CL.h 2605 2014-08-15 03:36:44Z secanell $
//
//---------------------------------------------------------------------------
#ifndef _FUELCELLSHOP__CONVENTIONAL_CL__H
#define _FUELCELLSHOP__CONVENTIONAL_CL__H
// Include deal.II classes
#include <deal.II/base/types.h>
// Include FCST classes
#include <layers/catalyst_layer.h>
#include <grid/geometries.h>
#include <boost/shared_ptr.hpp>
//Include STL
#include <algorithm>
#include <math.h>
#include <memory>
using namespace dealii;
namespace FuelCellShop
{
namespace Layer
{
/**
* This class characterizes a catalyst layer and uses this information
* to compute effective transport properties and interfacial areas for phase
* change or electrochemical reactions.
*
* This class implements a macrohomogeneous homogeneous or graded catalyst layer.
*
*/
template <int dim>
class ConventionalCL :
public CatalystLayer<dim>
{
public:
/**FcstUtilities
* Concrete name used for objects of this class. This name is used when
* setting up the subsection where the data is stored in the input file.
*
* The data will be store under
* \code
* subsection name_specified_in_constructor
* set Material id = 4
* set Catalyst layer type = HomogeneousCL # <-here I select the type of object of type CatalystLayer
* subsection HomogeneousCL # <- this is the concrete_name for this class
* set all info relevant to this object
* end
* end
* \endcode
*/
static const std::string concrete_name;
///@name Constructors, destructor, and initalization
//@{
/** \warning For internal use only.
*
* Constructor used only to create a prototype. Do not use
* in general since this will not include the name of the section
* in the parameter file you need.
*/
ConventionalCL();
/**
* Destructor
*/
virtual ~ConventionalCL();
//@}
///@name Accessors and info
//@{
/**
* Re-implementation of the parent set_local_material_id class to initialize the porosity
* variable to the right value once the material ID is changed.
*/
virtual inline void set_local_material_id(const unsigned int& id)
{
FuelCellShop::Layer::BaseLayer<dim>::set_local_material_id(id);
if (!epsilon_V.empty())
this->porosity = epsilon_V.at(this->local_material_id());
}
/**
* Print out the volume fraction in the catalyst layer
*/
virtual void print_layer_properties() const;
/** Get the volume fractions in the catalyst layer */
virtual void get_volume_fractions(std::map<std::string, double>& volume_fractions)
{
//Assert( mat_id != numbers::invalid_material_id, ExcMessage("Graded Catalyst Layers needs its material id.") );
compute_volume_fraction();
volume_fractions["Solid"] = epsilon_S.at(this->local_material_id());
volume_fractions["Void"] = epsilon_V.at(this->local_material_id());
volume_fractions["Ionomer"] = epsilon_N.at(this->local_material_id());
}
/**
* Return loadings
* - \param V_Pt = Pt loading in ug/cm3
* - \param loading_N = ionomer loading %wt
* - \param IC_ratio = I/C ratio
* @note either loading_N or IC_ratio should be passed through input file, the other computed
* - \param prc_Pt = Pt/C ratio
*/
virtual inline void get_loadings(std::map<std::string, double> & info)
{
//Assert( mat_id != numbers::invalid_material_id, ExcMessage("Graded/Homogeneous Catalyst Layers needs its material id.") );
info["V_Pt"] = V_Pt.at(this->local_material_id());
info["loading_N"] = loading_N.at(this->local_material_id());
info["IC_ratio"] = IC_ratio.at(this->local_material_id());
info["prc_Pt"] = prc_Pt.at(this->local_material_id());
};
/** Return the platinum loading per cm3 catalyst layer */
inline double get_V_Pt(const unsigned int mat_id = numbers::invalid_material_id) const
{
Assert( mat_id != numbers::invalid_material_id, ExcMessage("Graded/Homogeneous Catalyst Layers needs its material id.") );
// this is blah-blah return, change later
return V_Pt.at(this->local_material_id());
}
/**
* Get the active area of platinum per unit volume of CL
*
* The active area is computed using the data in the input file according to the information in #compute_Av
*/
virtual double get_active_area_Pt() const
{
//Assert( mat_id != numbers::invalid_material_id, ExcMessage("Graded Catalyst Layers needs its material id.") );
// this is blah-blah return, change later
return Av.at(this->local_material_id());
}
//@}
///@name Effective property calculators
//@{
/**
* Compute the effective property in the pores of the CL. This is used for example to
* compute effective diffusivity of gases. The method takes in bulk diffusion coefficient [\p m^2/s] and liquid water saturation as the first and second
* argument respectively. This routine is used in the isotropic case.
*/
virtual void effective_gas_diffusivity(const double&,
const double&,
double&) const;
/**
* Return the effective diffusivity [\p m^2/s] for nonisothermal with/without two-phase case in the CL. It takes bulk diffusivity, computed using
* #compute_gas_diffusion method and transforms it into an effective property,
* taking into account the porosity, saturation and CL structure (Anisotropic case),
* at all quadrature points of the cell.
*
* \note: For two-phase case, set_saturation should be called before using this method, otherwise this method assumes saturation value to be zero.
*/
virtual void effective_gas_diffusivity(std::vector< Tensor<2,dim> >&) const;
/**
* Return the derivative of effective diffusivity w.r.t solution variables/design parameters
* for nonisothermal with/without two-phase case in the CL. It transforms bulk diffusion properties computed using
* #compute_gas_diffusion method and transforms it into an effective property,
* taking into account the porosity, saturation and CL structure (Anisotropic case),
* at all quadrature points of the cell.
*
* \note: For two-phase case, set_saturation should be called before using this method, otherwise this method assumes saturation value to be zero.
*/
virtual void derivative_effective_gas_diffusivity(std::map< VariableNames, std::vector< Tensor<2,dim> > >&) const;
/**
* Compute the effective property in the pores of the CL. This is used to compute effective diffusivity of gases.
* This routine can be used either in the isotropic or anisotropic cases.
* Bulk diffusion coefficients or their derivatives are obtained from Mixure::BinaryDiffusion classes
* inside this method.
*
* \note The routine FuelCellShop::Layer::PorousLayer< dim >::set_gases_and_compute (std::vector< FuelCellShop::Material::PureGas * > &gases, double pressure, double temperature)
* (in the parent class) should have been called prior to using this class. This method is to be used only for a single-phase, isothermal application.
*/
virtual void effective_gas_diffusivity(Table< 2, Tensor< 2, dim > >&) const;
/**
* Compute the effective electron conductivity in the CL
*/
virtual void effective_electron_conductivity(double&) const;
/**
* Compute the effective electron conductivity in the CL as an
* anisotropic tensor.
*/
virtual void effective_electron_conductivity(Tensor<2,dim>&) const;
/**
* Compute the derivative of the effective electron conductivity in the GDL
* with respect to either the solution or design parameters. The parameters with respect to
* which the derivatives are computed are setup in FuelCellShop::Layer::set_derivative_flags()
*/
virtual void derivative_effective_electron_conductivity(std::vector<double>&) const;
/**
* Compute the effective proton conductivity in the CL.
*/
virtual void effective_proton_conductivity(double&) const;
virtual void effective_proton_conductivity(std::vector<double>&) const;
/**
* Compute the derivative of the effective proton conductivity in the CL
* with respect to either the solution or design parameters. The parameters with respect to
* which the derivatives are computed are setup in FuelCellShop::Layer::set_derivative_flags()
*/
virtual void derivative_effective_proton_conductivity(std::map< VariableNames, std::vector<double> >&) const;
/**
* Compute the effective water diffusivity (lambda diffusivity) in the CL.
*/
virtual void effective_water_diffusivity(double&) const;
virtual void effective_water_diffusivity(std::vector<double>&) const;
/**
* Compute the derivative of the effective water diffusivity (lambda diffusivity) in the CL
* with respect to either the solution or design parameters. The parameters with respect to
* which the derivatives are computed are setup in FuelCellShop::Layer::set_derivative_flags()
*/
virtual void derivative_effective_water_diffusivity(std::map< VariableNames, std::vector<double> >&) const;
/**
* Compute the effective thermal conductivity of catalyst layer
*/
virtual void effective_thermal_conductivity(double&) const;
/**
* Compute the effective thermal conductivity as a Tensor at all quadrature points
*/
virtual void effective_thermal_conductivity(std::vector< Tensor<2,dim> >&) const;
/**
* Compute the derivative of the effective thermal conductivity in the CL. Currently, this function returns
* only derivatives with respect to Temperature.
*/
virtual void derivative_effective_thermal_conductivity(std::vector< Tensor<2,dim> >&) const;
/**
* Compute the effective thermo-osmotic diffusivity of lambda (sorbed water),
* at all quadrature points in the CL.
*/
virtual void effective_thermoosmotic_diffusivity(std::vector<double>&) const;
/**
* Compute the derivative of the effective thermo-osmotic diffusivity of lambda (sorbed water) in the CL
* with respect to either the solution or design parameters. The parameters with respect to
* which the derivatives are computed are setup in FuelCellShop::Layer::set_derivative_flags()
*/
virtual void derivative_effective_thermoosmotic_diffusivity(std::map< VariableNames, std::vector<double> >&) const;
/**
* Compute the anisotropic CL liquid permeability \f$ \left[ cm^2 \right] \f$, at all quadrature points in the cell.
*/
virtual void liquid_permeablity(std::vector< Tensor<2,dim> >&) const;
/**
* Compute the derivative of the anisotropic liquid permeability in the CL
* with respect to either the solution or design parameters, at all quadrature points in the cell. The parameters with respect to
* which the derivatives are computed are setup in FuelCellShop::Layer::set_derivative_flags()
*/
virtual void derivative_liquid_permeablity(std::map< VariableNames, std::vector< Tensor<2,dim> > >&) const;
/**
* Compute the anisotropic CL liquid permeability \f$ \left[ cm^2 \right] \f$, at all quadrature points in the cell.
*/
virtual void saturated_liquid_permeablity_PSD(double&) const;
virtual void relative_liquid_permeability_PSD(std::vector< Tensor<2,dim> >&) const;
virtual void derivative_relative_liquid_permeablity_PSD(std::vector< double >&) const;
virtual void derivative_relative_liquid_permeablity_PSD(std::map< VariableNames, std::vector< Tensor<2,dim> > >&) const;
/**
* Compute \f$ p_c \quad \left[ dyne \cdot cm^{-2}\right] \f$, at all quadrature points in the cell.
*/
virtual void pcapillary(std::vector<double>&) const;
virtual void saturation_from_capillary_equation(std::vector<double>&) const;
virtual void derivative_saturation_from_capillary_equation_PSD(std::vector<double>&) const;
/**
* Compute \f$ \frac{\partial p_c}{\partial s} \quad \left[ dyne \cdot cm^{-2}\right] \f$, at all quadrature points in the CL.
*/
virtual void dpcapillary_dsat(std::vector<double> &) const;
/**
* Compute the derivative of \f$ \frac{\partial p_c}{\partial s} \quad \left[ dyne \cdot cm^{-2}\right] \f$ in the CL, with
* respect to either the solution or design parameters, at all quadrature points in the cell. The parameters with respect to which
* the derivatives are computed are setup in FuelCellShop::Layer::set_derivative_flags()
*/
virtual void derivative_dpcapillary_dsat(std::map< VariableNames, std::vector<double> > &) const;
/**
* Compute the liquid-gas interfacial surface area per unit volume, \f$ a_{lv} ~\left[ \frac{cm^2}{cm^3} \right] \f$, at all
* quadrature points in the CL.
*/
virtual void interfacial_surface_area(std::vector<double>&) const;
/**
* Compute the derivative of the liquid-gas interfacial surface area per unit volume, with respect to either the
* solution variables or design parameters, at all quadrature points in the CL. The parameters with respect to which
* the derivatives are computed are setup in FuelCellShop::Layer::set_derivative_flags().
*/
virtual void derivative_interfacial_surface_area(std::map< VariableNames, std::vector<double> >&) const;
/**
* Compute the liquid-gas interfacial surface area per unit volume, \f$ a_{lv} ~\left[ \frac{cm^2}{cm^3} \right] \f$, at all
* quadrature points in the CL.
*/
virtual void interfacial_surface_area_PSD(std::vector<double>&) const;
/**
* Compute the derivative of the liquid-gas interfacial surface area per unit volume, with respect to either the
* solution variables or design parameters, at all quadrature points in the CL. The parameters with respect to which
* the derivatives are computed are setup in FuelCellShop::Layer::set_derivative_flags().
*/
virtual void derivative_interfacial_surface_area_PSD(std::vector<double>&) const;
virtual void derivative_interfacial_surface_area_PSD(std::map< VariableNames, std::vector<double> >&) const;
//@}
protected:
///@name Constructors
//@{
/**
* Constructor
*/
ConventionalCL(std::string name);
/**
* Declare parameters for a parameter file.
*
* @note In order to enable graded catalyst layers, some parameters such as Platinum loading on support (%wt) utilize a
* map with the following structure material_id1:value1, material_id2:value2 where material_id1, material_id2
* correspond to sublayers within the catalyst layer.
*
* @code
* subsection Fuel cell data
* (...)
* subsection Cathode Catalyst Layer #<- This is the name fo the subsection that you specify in cl_section_name
* (...)
* subsection ConventionalCL #<- This is the name in (this->concrete_name)
* set Platinum loading on support (%wt) = 4:0.46 # Mass percentage of platinum catalyst on the support carbon black
* set Platinum loading per unit volume (mg/cm3) = 4:400 # Catalyst platinum mass loading per unit volume of CL
* set Electrolyte loading (%wt) = 4:0.3 # Electrode loading is the weight percentage of ionomer per gram of CL
* //-- Network characteristics
* set Method effective transport properties in pores = Bruggemann # OPTIONS: Given|Bruggemann|Percolation -- Method used to compute effective transport properties in the void phase.
* set Porosity threshold = 0.12 # Threshold value of the volume fraction of void space in the CL. If the porosity is less than this value transport does not occur
* set Porosity network constant = 2.0 # Parameter used when using percolation theory
* set Porosity gamma network constant = 0.0 # Parameter used when using percolation theory to account for extra diffusion
* //--
* set Method effective transport properties in solid phase = Bruggemann # OPTIONS: Given|Bruggemann|Percolation --- Method used to compute effective transport properties in pores
* set Solid network threshold = 0.12 # Threshold value of the volume fraction of solid (electron conductive) phase in the CL. If the solid phase is less than this value transport in the fibre network does not occur
* set Solid network constant = 2.0 # Parameter used when using percolation theory
* set Method effective transport properties in electrolyte phase = Bruggemann # OPTIONS: Given|Bruggemann|Percolation|Iden11 -- Method used to compute effective transport properties in pores
* set Electrolyte network threshold = 0.12 # Threshold value of the volume fraction of electrolyte (proton conductive) phase in the CL. If the electrolyte phase is less than this value transport in the network does not occur
* set Electrolyte network constant = 2.0 # Parameter used when using percolation theory
* set Method to compute active area = given # OPTIONS: given|Marr|ETEK06|ETEK07 --
* set Active area [cm^2/cm^3] = 4:2.0e5
* set Method to compute porosity = marc #OPTIONS: marc
* //----
* set Method effective thermal conductivity = Given # OPTIONS: Given -- Method used to compute effective thermal conductivity
* set Thermal conductivity, [W/(cm K)] = 4:0.015
* end
* end
* end
* @endcode
*
* For an explanation for the different options, please see the appropriate member function. For example, for the options relating
* to active area see member function FuelCellShop::Layer::ConventionalCL::compute_Av()
*/
void declare_parameters (const std::string& cl_section_name,
ParameterHandler ¶m) const;
/**
* Member function used to read in data and initialize the necessary data
* to compute the coefficients.
*/
void initialize (ParameterHandler ¶m);
//@}
/**
* Compute porosity and volume fraction of solid and ionomer in the catalyst layer
*/
void compute_volume_fraction();
/**
* Compute the active area of catalyst in the layer by the specified method
*
* There are three methods to compute the active area, namely
* - given
* - Marr
* - ETEK06
* - ETEK07
*
* The given option will simply use the value provided by the user.
*
* The Marr, ETEK06 and ETEK07 options use a polyomial approximation to obtain the surface area of Pt per gram of catalyst, i.e. \f$ A_0 \f$ ,
* based on the Pt to carbon weight ratio, i.e. Pt|C or Platinum loading on support (%wt) in the input file.
* Then, the cm^2 Pt per cm^3 of CL is obtained using
* \f[
* A_v = A_0*(V_{Pt}*1e-3)
* \f]
* where \f$ V_{Pt} \f$ is the input parameter "Platinum loading per unit volume (mg/cm3)".
*
* The functions to obtain \f$ A_0 \f$ are
*
* 1) Marr
* \f[
* A_0 = 2.2779e6*(Pt|C)^3 - 1.5857e6*(Pt|C)^2 - 2.0153e6*(Pt|C) + 1.5950e6;
* \f]
* The equation is from the following reference:
* Marr, C., Li, X. Composition and performance modelling of catalyst layer in a proton exchange membrane fuel cell.
* Journal of Power Sources 77 (1) , pp. 17-27, 1999
*
* 2) ETEK06
* \f[
* A_0 = -4.5646e5*(Pt|C)^3 + 1.0618e6*(Pt|C)^2 - 1.8564e6*(Pt|C) + 1.5955e6;
* \f]
* and is a curve-fit to ETEK catalyst data reported previous to 2006.
*
* 3) ETEK07
* \f[
* A_0 = 0.7401e7*(Pt|C)^4 - 1.8105e7*(Pt|C)^3 + 1.5449e7*(Pt|C)^2 - 0.6453e7*(Pt|C) + 0.2054e7
* \f]
* The equation is derived in M. Secanell, Computational Modeling and Optimization of Proton
* Exchange Membrane Fuel Cells, Ph.D. thesis, University of Victoria, 2008 by curve-fitting data from ETEK from their
* 2007 catalyst. It is used in several of M. Secanell's publications.
*
*/
void compute_Av();
/**
* Compute the derivative of the effective proton conductivity w.r.t. the electrolyte
* loading.
*/
void derivative_effective_proton_conductivity_wrt_electrolyte_loading(double&) const;
/**
* Function to compute the partial derivative of the volume fraction
* the different phases in the catalyst layer with respect to
* the design variables of the optimization problem
*/
void derivative_volume_fractions(double &Depsilon_S,
double &Depsilon_V,
double &Depsilon_N) const;
/**
* Get the effective transport method in the pores
*/
void get_method_transport_property_pores(std::string& method) const
{
method = method_eff_property_pores;
};
/**
* Get the effective transport method in the electrolyte
*/
void get_method_transport_property_electrolyte(std::string& method) const
{
method = method_eff_property_electrolyte;
};
/**
* Get the effective transport method in the solid phase
*/
void get_method_transport_property_solid(std::string& method) const
{
method = method_eff_property_solid;
};
/**
* Inline function to compute
* \f[
* \frac{\partial \epsilon_S^{cat}}{\partial \%Pt}
* \f]
*/
inline double depsilon_S_cat_dprc_Pt(const double& V_Pt,
const double& prc_Pt) const
{
return -(V_Pt*1e-3)/(rho_c*pow(prc_Pt,2.0));
}
/**
* Inline function to compute
* \f[
* \frac{\partial \epsilon_S^{cat}}{\partial m_{Pt}}
* \f]
*/
inline double depsilon_S_cat_dVPt(const double& prc_Pt) const
{
return (1/rho_Pt + (1-prc_Pt)/(prc_Pt*rho_c))*(1e-3);
}
/**
* Inline function to compute
* \f[
* \frac{\partial \epsilon_V^{cat}}{\partial \epsilon_S^{cat}}
* \f]
*/
inline double depsilon_V_cat_depsilon_S_cat() const
{
return -1;
}
/**
* Inline function to compute
* \f[
* \frac{\partial \epsilon_V^{cat}}{\partial \epsilon_S^{cat}}
* \f]
*/
inline double depsilon_V_cat_depsilon_N_cat() const
{
return -1;
}
//-- Composition
/** Volume fraction of Nafion in the cathode catalyst layer. Using unsigned int specifying the material id for the specific CL*/
std::map< unsigned int, double> epsilon_N;
/** Void volume fraction (Porosity) of the catalyst layer. Using unsigned int specifying the material id for the specific CL*/
std::map< unsigned int, double> epsilon_V;
/** Solid volume fraction in the catalyst layer. Using unsigned int specifying the material id for the specific CL*/
std::map< unsigned int, double> epsilon_S;
/** Volume fraction of water in the cathode catalyst layer. Using unsigned int specifying the material id for the specific CL*/
std::map< unsigned int, double> epsilon_W;
//-- Catalyst properties
/** Density of platinum */
double rho_Pt;
/** Density of support material */
double rho_c;
/** Percentage of platinum per carbon on the catalyst layer. Using unsigned int specifying the material id for the specific CL*/
std::map< unsigned int, double> prc_Pt;
/** Platinum loading at the catalyst layer per unit volume. Using unsigned int specifying the material id for the specific CL*/
std::map< unsigned int, double> V_Pt;
/** Platinum loading at the catalyst layer per unit area. Using unsigned int specifying the material id for the specific CL*/
std::map< unsigned int, double> M_Pt;
/** Active area of catalyst per unit volume of catalyst layer. Using unsigned int specifying the material id for the specific CL*/
std::map< unsigned int, double> Av;
/** Method to compute active area */
std::string method_Av;
/** Method to compute porosity */
std::string method_porosity;
/** Layer thickness or thicknesses. Using unsigned int specifying the material id*/
std::map< unsigned int, double> L_CL;
//-- Electrolyte properties
/** Density of electrolyte */
double rho_N;
/** Electrolyte loading. Electrode loading is the weight percentage
* of ionomer per gram of CL. Which may change if multiple CLs exist. Each CL is specified using unsigned int for the material id.
* loading_N = weight electrolyte / (weight Pt + weight C + weight electrolyte)
*/
std::map< unsigned int, double> loading_N;
/**
* Ionomer to carbon ratio. Which may change if multiple CLs exist. Each CL is specified using unsigned int for the material id.
* I/C ratio = weight electrolyte / weight C
*/
std::map< unsigned int, double> IC_ratio;
/** Percentage (mass fraction) of electrolyte in the catalyst layer. Each CL is specified using unsigned int for the material id. */
std::map< unsigned int, double> prc_N;
// Network characteristics
/** Method used to compute effective properties -- Type of network */
std::string method_eff_property_pores;
/** Porous network threshold */
double porosity_th;
/** Porous network constant */
double porosity_mu;
/** */
double porosity_gamma;
/** Method used to compute effective properties -- Type of network */
std::string method_eff_property_solid;
/** Solid phase network threshold */
double solid_th;
/** Solid phase network constant */
double solid_mu;
/** Method used to compute effective properties -- Type of network */
std::string method_eff_property_electrolyte;
/** Electrolyte network threshold */
double electrolyte_th;
/** Electrolyte network constant */
double electrolyte_mu;
/** Method used to compute effective thermal conductivity in the catalyst layer */
std::string method_eff_thermal;
/** Thermal Conductivity of the layer. Using unsigned int specifying the material id for the specific CL*/
std::map< unsigned int, double> k_T;
/** Method used to compute the relative liquid permeability. */
std::string method_rel_liquid_permeability;
/** Irreducible liquid water saturation value in the MPL. */
std::map< unsigned int, double> s_irr;
/** Absolute permeability [cm^2] of the layer. Using unsigned int specifying the material id for the specific CL*/
std::map< unsigned int, double> abs_permeability;
/** Method used to compute capillary pressure as a function of saturation. */
std::string method_capillary_function;
};
}
}
#endif
| [
"[email protected]"
] | |
ab6ab160626555a82140a275c59a0c56f12001ce | 5bb7cf6f6f38e8a96ef5d522d26cf78c7c097c41 | /src/engine/server/library/serverGame/src/shared/space/ShipComponentDataReactor.cpp | d725ca6134404f8ba3f896ad3e5ac3f86290e826 | [] | no_license | hackerlank/SWG_Client_Next_Main | 1c88015af11bd42c662a7d7c4fe0807924f4077a | d737257b8fc28f7ad4d8d02113e7662682187194 | refs/heads/master | 2021-01-12T06:25:56.627527 | 2016-06-01T19:32:59 | 2016-06-01T19:32:59 | 77,359,203 | 6 | 4 | null | 2016-12-26T05:09:07 | 2016-12-26T05:09:06 | null | UTF-8 | C++ | false | false | 3,963 | cpp | //======================================================================
//
// ShipComponentDataReactor.cpp
// copyright (c) 2004 Sony Online Entertainment
//
//======================================================================
#include "serverGame/FirstServerGame.h"
#include "serverGame/ShipComponentDataReactor.h"
#include "serverGame/ShipObject.h"
#include "sharedFoundation/DynamicVariableList.h"
#include "sharedGame/SharedObjectAttributes.h"
#include "UnicodeUtils.h"
//======================================================================
namespace ShipComponentDataReactorNamespace
{
namespace Objvars
{
std::string const energyGenerationRate = "ship_comp.reactor.energy_generation_rate";
}
}
using namespace ShipComponentDataReactorNamespace;
//----------------------------------------------------------------------
ShipComponentDataReactor::ShipComponentDataReactor (ShipComponentDescriptor const & shipComponentDescriptor) :
ServerShipComponentData(shipComponentDescriptor),
m_energyGenerationRate (0.0f)
{
}
//----------------------------------------------------------------------
ShipComponentDataReactor::~ShipComponentDataReactor ()
{
}
//----------------------------------------------------------------------
bool ShipComponentDataReactor::readDataFromShip (int chassisSlot, ShipObject const & ship)
{
if (!ServerShipComponentData::readDataFromShip (chassisSlot, ship))
return false;
m_energyGenerationRate = ship.getReactorEnergyGenerationRate ();
return true;
}
//----------------------------------------------------------------------
void ShipComponentDataReactor::writeDataToShip (int chassisSlot, ShipObject & ship) const
{
ServerShipComponentData::writeDataToShip (chassisSlot, ship);
ship.setReactorEnergyGenerationRate (m_energyGenerationRate);
}
//----------------------------------------------------------------------
bool ShipComponentDataReactor::readDataFromComponent (TangibleObject const & component)
{
if (!ServerShipComponentData::readDataFromComponent (component))
return false;
DynamicVariableList const & objvars = component.getObjVars ();
if (!objvars.getItem (Objvars::energyGenerationRate, m_energyGenerationRate))
WARNING (true, ("ShipComponentDataReactor [%s] has no energyGenerationRate [%s]", component.getNetworkId ().getValueString ().c_str (), Objvars::energyGenerationRate.c_str ()));
return true;
}
//----------------------------------------------------------------------
void ShipComponentDataReactor::writeDataToComponent (TangibleObject & component) const
{
ServerShipComponentData::writeDataToComponent (component);
component.setObjVarItem (Objvars::energyGenerationRate, m_energyGenerationRate);
}
//----------------------------------------------------------------------
void ShipComponentDataReactor::printDebugString (Unicode::String & result, Unicode::String const & padding) const
{
ServerShipComponentData::printDebugString (result, padding);
char buf [1024];
const size_t buf_size = sizeof (buf);
std::string const & nPad = Unicode::wideToNarrow (padding) + " ";
snprintf (buf, buf_size,
"%sEnergyGenerationRate: %f (%f)\n",
nPad.c_str (), m_energyGenerationRate, m_energyGenerationRate * m_efficiencyGeneral);
result += Unicode::narrowToWide (buf);
}
//----------------------------------------------------------------------
void ShipComponentDataReactor::getAttributes(stdvector<std::pair<std::string, Unicode::String> >::fwd & data) const
{
ServerShipComponentData::getAttributes(data);
Unicode::String attrib;
static char buffer[128];
static const size_t buffer_size = sizeof (buffer);
snprintf(buffer, buffer_size, "%.1f", m_energyGenerationRate);
attrib = Unicode::narrowToWide(buffer);
data.push_back(std::make_pair(cm_shipComponentCategory + SharedObjectAttributes::ship_component_reactor_generation_rate, attrib));
}
//======================================================================
| [
"[email protected]"
] | |
a69b6e73516cc8c9ec0a59b8854211e82160f169 | dfc3cbda909c36d41688461e3af4b819756fd42b | /Samutichev.Evgenii/lab2/core/conn_mq.cpp | 90b9c692d150de042f30c2e94780455c9449bc5c | [] | no_license | zhenyatos/OS_Labs_SPBPU_2020 | b3864c551c617998617d1bcb070c52ce7ef1f8b5 | 971f42e6a36bed35e4e327b32e715f36793880b3 | refs/heads/main | 2023-01-22T10:43:40.150393 | 2020-11-19T14:31:11 | 2020-11-19T14:31:11 | 301,869,133 | 0 | 0 | null | 2020-11-19T14:31:12 | 2020-10-06T22:25:43 | C++ | UTF-8 | C++ | false | false | 1,796 | cpp | #include "conn.h"
#include "sys_exception.h"
#include <mqueue.h>
#include <new>
#include <string>
#include <sys/stat.h>
#include <errno.h>
#include <syslog.h>
const mode_t permissions = 0666;
const char* prefix = "/mq_";
namespace {
class ConnectionImpl : public Connection {
public:
ConnectionImpl(size_t id, bool create);
int read() const override;
void write(int msg) const override;
~ConnectionImpl() override;
private:
mqd_t _descr;
std::string _id;
};
ConnectionImpl::ConnectionImpl(size_t id, bool create) {
_id = prefix + std::to_string(id);
if (create) {
mq_attr attr = {0, 1, sizeof(int), 0 };
_descr = mq_open(_id.c_str(), O_CREAT | O_RDWR, permissions, &attr);
if (_descr == (mqd_t)-1)
throw SysException("Failed to create (MQ)", errno);
}
else {
_descr = mq_open(_id.c_str(), O_RDWR);
if (_descr == (mqd_t)-1)
throw SysException("Failed to open (MQ)", errno);
}
}
int ConnectionImpl::read() const {
int msg;
if (mq_receive(_descr, (char*)&msg, sizeof(int), 0) == -1)
throw SysException("Failed to read message (MQ)", errno);
return msg;
}
void ConnectionImpl::write(int msg) const {
if (mq_send(_descr, (char*)&msg, sizeof(int), 0) == -1)
throw SysException("Failed to write (MQ)", errno);
}
ConnectionImpl::~ConnectionImpl() {
if (mq_close(_descr) == -1)
syslog(LOG_ERR, "An unhandled exception occured while closing descriptor %d (MQ)", _descr);
}
}
Connection* Connection::create(size_t id, bool create) {
return new (std::nothrow) ConnectionImpl(id, create);
}
| [
"[email protected]"
] | |
b7142e48126d1db509a006727ad18c64200e2078 | 61854962871ec2f492d964563e9e8cd97a8bd3de | /Cluster.h | 05ff07f9ae54705a5ff2d8f02c0d272b42d706cb | [] | no_license | daviddoria/AgglomerativeClustering | 4b73f762c292a739e7fdc4be180e6a287dd3f914 | bcdf1988188d9a73d4c52ebdcd8a2f1071ac7d3a | refs/heads/master | 2021-01-10T19:50:04.569485 | 2010-09-23T12:45:25 | 2010-09-23T12:45:25 | 933,272 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 672 | h | #ifndef CLUSTER_H
#define CLUSTER_H
#include <vector>
#include <Geometry/OrientedPoint.h>
#include <vgl/vgl_point_3d.h>
class Cluster
{
std::vector<OrientedPoint> Points_;
vgl_point_3d<double> Center_;
public:
Cluster(){}
Cluster(const std::vector<OrientedPoint> &Points)
{
setPoints(Points);
}
vgl_point_3d<double> getCenter() const {return Center_;}
OrientedPoint getPoint(unsigned int i) const {return Points_[i];}
unsigned int NumPoints() const {return Points_.size();}
void setPoints(const std::vector<OrientedPoint> &Points);
void AppendCluster(const Cluster &C);
};
std::ostream& operator<<(std::ostream& output, const Cluster &C);
#endif | [
"[email protected]"
] | |
69c9fdf54439b31252fae314b1b91d6e9be3fcb4 | 538f53dad517a1b906f40e4ba1d9a8f14bc272a6 | /Point2D.h | f130c3139cea9287603ba902f2c3f6e6c6ff254a | [
"LicenseRef-scancode-public-domain"
] | permissive | ElkMonster/Point2D | 1ab41627d85763c4fe2ec424609ce467cced3829 | 80fe85fe67828ef5aa7fc5c8793d4047528b63c0 | refs/heads/master | 2021-01-01T05:49:00.273852 | 2012-08-07T16:45:16 | 2012-08-07T16:45:16 | 5,330,318 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,724 | h | #ifndef POINT2D_H_
#define POINT2D_H_
#include <ostream>
namespace geom
{
/** A simple 2D point class. */
class Point2D
{
public:
Point2D();
Point2D(float x, float y);
Point2D(const Point2D& other);
virtual ~Point2D();
Point2D& operator=(const Point2D& rhs);
Point2D& operator+=(const Point2D& rhs);
Point2D& operator-=(const Point2D& rhs);
Point2D& operator*=(const Point2D& rhs);
Point2D& operator/=(const Point2D& rhs);
Point2D& operator*=(float factor);
Point2D& operator/=(float divisor);
const Point2D operator-() const;
const Point2D operator+(const Point2D& other) const;
const Point2D operator-(const Point2D& other) const;
const Point2D operator*(const Point2D& other) const;
const Point2D operator/(const Point2D& other) const;
const Point2D operator*(float factor) const;
const Point2D operator/(float divisor) const;
bool operator==(const Point2D& rhs) const;
bool operator!=(const Point2D& rhs) const;
bool operator<(const Point2D& rhs) const;
bool operator>(const Point2D& rhs) const;
bool operator<=(const Point2D& rhs) const;
bool operator>=(const Point2D& rhs) const;
const Point2D abs() const;
bool isIn(const Point2D list[], int listSize) const;
friend const Point2D min(const Point2D& p1, const Point2D& p2);
friend const Point2D max(const Point2D& p1, const Point2D& p2);
friend std::ostream& operator<<(std::ostream& out, const Point2D& point);
public:
float x;
float y;
}; // class Point2D
float dist(const Point2D& p1, const Point2D& p2);
} // namespace geom
#endif // POINT2D_H_
| [
"[email protected]"
] | |
df2a571f61fdb926911219e3a2118dcfc871c0fa | 91d5815101bd7f4fa8041b1b624e96ca86badbfb | /utility.cpp | 8133d19311ee54ff030434ff27aec0abf9e427f8 | [] | no_license | itsmeat/LIC | f4180f6a31f53fe634c7cd5545ccc47eed1c3f8c | 898b82087723a0bfcc575f7e2154eedb5257aa64 | refs/heads/master | 2021-08-22T05:45:49.018147 | 2017-11-29T11:43:51 | 2017-11-29T11:43:51 | 112,468,611 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,832 | cpp | #include "utility.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
int sWidth = 800;
int sHeight = 800;
//constants
float PI = 3.1415;
unsigned int TextureLoader(string path, bool isAlpha){
// load and create a texture
// -------------------------
//Deal with the image vertically down rule vs opengl vertically up rule.
stbi_set_flip_vertically_on_load(true);
unsigned int texture=0;
GLenum interpret = GL_RGB;
if(isAlpha==true)
interpret = GL_RGBA;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture); // all upcoming GL_TEXTURE_2D operations now have effect on this texture object
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load image, create texture and generate mipmaps
int width, height, nrChannels;
unsigned char *data = stbi_load((TRPath+path).c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, interpret, width, height, 0, interpret, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
cout << "Failed to load texture" << endl;
}
stbi_image_free(data);
return texture;
}
/////////////////////////////////////////////////////////////////////////////////
// constructor generates the shader on the fly
// ------------------------------------------------------------------------
void Shader::init(string vertexPath, string fragmentPath)
{
// 1. retrieve the vertex/fragment source code from filePath
string vertexCode;
string fragmentCode;
ifstream vShaderFile;
ifstream fShaderFile;
// ensure ifstream objects can throw exceptions:
vShaderFile.exceptions (ifstream::failbit | ifstream::badbit);
fShaderFile.exceptions (ifstream::failbit | ifstream::badbit);
try
{
// open files
vShaderFile.open((VSPath+vertexPath).c_str());
fShaderFile.open((FSPath+fragmentPath).c_str());
stringstream vShaderStream, fShaderStream;
// read file's buffer contents into streams
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
// close file handlers
vShaderFile.close();
fShaderFile.close();
// convert stream into string
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
}
catch (ifstream::failure e)
{
cout << "ERROR::SHADER::FILE_NOT_SUCCESFULLY_READ" << endl;
}
const char* vShaderCode = vertexCode.c_str();
const char * fShaderCode = fragmentCode.c_str();
// 2. compile shaders
unsigned int vertex, fragment;
int success;
char infoLog[512];
// vertex shader
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
checkCompileErrors(vertex, "VERTEX");
// fragment Shader
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
checkCompileErrors(fragment, "FRAGMENT");
// shader Program
ID = glCreateProgram();
glAttachShader(ID, vertex);
glAttachShader(ID, fragment);
glLinkProgram(ID);
checkCompileErrors(ID, "PROGRAM");
// delete the shaders as they're linked into our program now and no longer necessary
glDeleteShader(vertex);
glDeleteShader(fragment);
}
// activate the shader
// ------------------------------------------------------------------------
void Shader::use()
{
glUseProgram(ID);
}
// utility uniform functions
// ------------------------------------------------------------------------
void Shader::set1b(const string &name, bool value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()), (int)value);
}
// ------------------------------------------------------------------------
void Shader::set1i(const string &name, int value) const
{
glUniform1i(glGetUniformLocation(ID, name.c_str()), value);
}
// ------------------------------------------------------------------------
void Shader::set1f(const string &name, float value) const
{
glUniform1f(glGetUniformLocation(ID, name.c_str()), value);
}
void Shader::set4f(const string &name, float x, float y, float z, float w) const
{
glUniform4f(glGetUniformLocation(ID, name.c_str()), x, y, z, w);
}
void Shader::set3m(const string &name, mat3 transform) const
{
glUniformMatrix3fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, value_ptr(transform));
}
void Shader::set4m(const string &name, mat4 transform) const
{
glUniformMatrix4fv(glGetUniformLocation(ID, name.c_str()), 1, GL_FALSE, value_ptr(transform));
}
void Shader::set3fv(const string &name, vec3 vPtr) const
{
glUniform3fv(glGetUniformLocation(ID, name.c_str()), 1, value_ptr(vPtr));
}
void Shader::setsu(GLenum shaderType, const string &name, const string &value) const
{
int activeS,countActiveSU;
char suname[256], surname[256];
int len, numCompS;
glGetProgramStageiv(ID, shaderType, GL_ACTIVE_SUBROUTINE_UNIFORMS, &countActiveSU);
GLuint indices[countActiveSU];
memset(indices, 0, sizeof(int)*countActiveSU);
for (int i = 0; i < countActiveSU; ++i) {
glGetActiveSubroutineUniformName(ID, shaderType, i, 256, &len, suname);
printf("Suroutine Uniform: %d name: %s\n", i, suname);
glGetActiveSubroutineUniformiv(ID, shaderType, i, GL_NUM_COMPATIBLE_SUBROUTINES, &numCompS);
int *s = (int *)malloc(sizeof(int) * numCompS);
glGetActiveSubroutineUniformiv(ID, shaderType, i, GL_COMPATIBLE_SUBROUTINES, s);
printf("Compatible Subroutines:\n");
for (int j=0; j < numCompS; ++j) {
glGetActiveSubroutineName(ID, shaderType, s[j], 256, &len, surname);
printf("\t%d - %s\n", s[j], surname);
if(suname==name and surname==value){
GLuint index = glGetSubroutineIndex(ID, shaderType, surname);
indices[i] = s[j];
glUniformSubroutinesuiv(shaderType, 1, &index);
return;
}
}
printf("\n");
free(s);
}
}
// utility function for checking shader compilation/linking errors.
// ------------------------------------------------------------------------
void Shader::checkCompileErrors(unsigned int shader, string type)
{
int success;
char infoLog[1024];
if (type != "PROGRAM")
{
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << endl;
}
}
else
{
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shader, 1024, NULL, infoLog);
cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog << "\n -- --------------------------------------------------- -- " << endl;
}
}
}
/////////////////////////////////////////////////////////////////////////////////////
GLuint shaderLoaderFile(string path, GLenum shaderType){
GLuint shaderID = 0;
//load file contents
string shaderString;
ifstream sourceFile( path.c_str() );
//Source file loaded
if( sourceFile ) {
//Get shader source
shaderString.assign( ( istreambuf_iterator< char >( sourceFile ) ), istreambuf_iterator< char >() );
return shaderLoaderString(shaderString, shaderType);
}
else {
printf( "Unable to open file %s\n", path.c_str() );
}
return shaderID;
}
GLuint shaderLoaderString(string contents, GLenum shaderType){
//Create shader ID
GLuint shaderID = glCreateShader( shaderType );
//Set shader source
const GLchar* shaderSource = contents.c_str();
glShaderSource( shaderID, 1, (const GLchar**)&shaderSource, NULL );
//Compile shader source
glCompileShader( shaderID );
int success;
char infoLog[512];
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(shaderID, 512, NULL, infoLog);
cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << endl;
}
return shaderID;
}
//Initialization and Context creation wrappers for glfw and glad
// ---------------------------------------------------------------------------------------------
void glutInitialize(int argc, char **argv){
glutInit(&argc, argv);
glutInitWindowSize(sWidth, sHeight);
glutInitWindowPosition(10, 10);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
}
int glewInitialize(){
// initialize glew and check for OpenGL 2.0 support
glewInit();
if(glewIsSupported("GL_VERSION_4_0")) {
cout << "Ready for OpenGL 4.0" << endl;
} else {
cerr << "OpenGL 2.0 not supported" << endl;
return 0;
}
return 1;
}
//----------------------------------------------------------------------------------------------------
unsigned int genNoiseTex(int width, int height){
unsigned int noise_texture;
// create the noise texture
glGenTextures(1 ,&noise_texture);
glBindTexture(GL_TEXTURE_2D, noise_texture);
float *arr = new float[width*height];
for(int i=0; i<width*height; i++) {
arr[i] = drand48();
}
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, 1, width, height, 0, GL_LUMINANCE, GL_FLOAT, arr);
delete[] arr;
return noise_texture;
}
void CalculateFrameRate(const string &start){
static float framesPerSecond = 0.0f; // This will store our fps
static float lastTime = 0.0f; // This will hold the time from the last frame
float currentTime = glutGet(GLUT_ELAPSED_TIME) * 0.001f;
++framesPerSecond;
string temp = "";
if( currentTime - lastTime > 1.0f )
{
lastTime = currentTime;
// printf("\nCurrent Frames Per Second: %d\n\n", (int)framesPerSecond);
// sprintf(temp, "LIC | %d fps ", (int)framesPerSecond);
temp += start + " | " + to_string((int)framesPerSecond) + " fps";
glutSetWindowTitle(temp.c_str());
framesPerSecond = 0;
}
}
mat4 rotationMatrix(vec3 axis, float angle)
{
axis = normalize(axis);
float s = sin(angle);
float c = cos(angle);
float oc = 1.0 - c;
return mat4(oc * axis.x * axis.x + c, oc * axis.x * axis.y - axis.z * s, oc * axis.z * axis.x + axis.y * s, 0.0,
oc * axis.x * axis.y + axis.z * s, oc * axis.y * axis.y + c, oc * axis.y * axis.z - axis.x * s, 0.0,
oc * axis.z * axis.x - axis.y * s, oc * axis.y * axis.z + axis.x * s, oc * axis.z * axis.z + c, 0.0,
0.0, 0.0, 0.0, 1.0);
}
///////////////////////////////////////////////////////////////////////////////
// Support for selecting window context screen space via viewport.
// And then use this space for orthogonal or perspective projection.
///////////////////////////////////////////////////////////////////////////////
void chooseScreenArea(float x, float y, float w, float h, float scale, int is3D){
glViewport (x, y, w, h);
//use projection scaling in the chosen viewport
glMatrixMode (GL_PROJECTION); /* Select The Projection Matrix */
glLoadIdentity (); /* Reset The Projection Matrix */
if(is3D == 1){
glClearDepth(1.0f); // Set background depth to farthest
glEnable(GL_DEPTH_TEST); // Enable depth testing for z-culling
glDepthFunc(GL_LEQUAL); // Set the type of depth-test
glShadeModel(GL_SMOOTH); // Enable smooth shading
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Nice perspective corrections
gluPerspective(45, w/h, 0.1, 100);
}
else
gluOrtho2D(x, w*scale, y, h*scale);
glMatrixMode (GL_MODELVIEW); /* Select The Modelview Matrix */
glLoadIdentity (); /* Reset The Modelview Matrix */
}
///////////////////////////////////////////////////////////////////////////////
// write 2d text using GLUT
// The projection matrix must be set to orthogonal before call this function.
///////////////////////////////////////////////////////////////////////////////
void drawString2D(vec2 pos, vec4 col, void* font, string s)
{
glColor4fv((float *)&col);
glRasterPos2fv((float *)&pos);
int len, i;
const char *str = s.c_str();
len = s.length();
for (i = 0; i < len; i++) {
glutBitmapCharacter(font, str[i]);
}
}
///////////////////////////////////////////////////////////////////////////////
// draw a string in 3D space
///////////////////////////////////////////////////////////////////////////////
void drawString3D(vec3 pos, vec4 col, void* font, string s)
{
glColor4fv((float *)&col); // set text color
glRasterPos3fv((float *)&pos); // place text position
int len, i;
const char *str = s.c_str();
len = s.length();
for (i = 0; i < len; i++) {
glutBitmapCharacter(font, str[i]);
}
}
float degrees(float radians){
return radians*180.0f/PI;
}
float radians(float degrees){
return degrees*PI/180.0f;
}
// Returns a quaternion such that q*start = dest
quat rotationBetweenVectors(vec3 start, vec3 dest){
start = normalize(start);
dest = normalize(dest);
float cosTheta = dot(start, dest);
vec3 rotationAxis;
if (cosTheta < -1 + 0.001f){
// special case when vectors in opposite directions :
// there is no "ideal" rotation axis
// So guess one; any will do as long as it's perpendicular to start
// This implementation favors a rotation around the Up axis,
// since it's often what you want to do.
rotationAxis = cross(vec3(0.0f, 0.0f, 1.0f), start);
if (length2(rotationAxis) < 0.01 ) // bad luck, they were parallel, try again!
rotationAxis = cross(vec3(1.0f, 0.0f, 0.0f), start);
rotationAxis = normalize(rotationAxis);
return angleAxis(glm::radians(180.0f), rotationAxis);
}
// Implementation from Stan Melax's Game Programming Gems 1 article
rotationAxis = cross(start, dest);
float s = sqrt( (1+cosTheta)*2 );
float invs = 1 / s;
return quat(
s * 0.5f,
rotationAxis.x * invs,
rotationAxis.y * invs,
rotationAxis.z * invs
);
}
//sets the modelview matrix to new coordinate system defined by the axes
mat4 rotateModelViewToNewCoordinateSpace(vec3 new_x, vec3 new_y, vec3 new_z){
/*************************Dont' Delete*********************/
// glRotatef(-angle_x, 1, 0, 0); // pitch
// glRotatef(-angle_y, 0, 1, 0); // heading
// glRotatef(cameraAngleZ, 0, 0, 1); // roll
// quat quaternion = rotationBetweenVectors(front, vec3(0, 0, 1));
// mat4 rotationMatrix = toMat4(quaternion);
// glMultMatrixf((float*)&rotationMatrix);
/***********************************************************/
mat4 rotationMatrix = mat4(vec4(new_x, 0), vec4(new_y, 0), vec4(new_z, 0), vec4(0, 0, 0, 1));
rotationMatrix = transpose(rotationMatrix);
return rotationMatrix;
}
| [
"[email protected]"
] | |
636bf004cd9c232cb430831c707b53a00b0a1d2c | 0b37c5d5dc696cf3f0a89295afb117f955f0ab2c | /src/fred/camera/yuv2rgb.cpp | 62d051eff4daa78f4670dd3473316fe77211149a | [] | no_license | nickdiego/blue-barcode-reader | 14f623e8e5a8946f5606d4a63c813364957ff67e | 132a8506305938f6639c416591e073aa8adde4bc | refs/heads/master | 2020-05-16T02:57:41.539201 | 2013-01-25T02:51:20 | 2013-04-01T16:20:43 | 9,150,586 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,855 | cpp | #include "yuv2rgb.h"
#include <QtCore/qmath.h>
Yuv2Rgb::Yuv2Rgb()
: m_bits(0)
, m_width(0)
, m_height(0)
{
preCalculateValues();
}
Yuv2Rgb::~Yuv2Rgb()
{
if (m_v1)
delete m_v1;
if (m_v2)
delete m_v2;
if (m_v3)
delete m_v3;
if (m_v4)
delete m_v4;
}
uchar *Yuv2Rgb::bits()
{
return m_bits;
}
int Yuv2Rgb::width()
{
return m_width;
}
int Yuv2Rgb::height()
{
return m_height;
}
void Yuv2Rgb::convert(const uchar *bits, const int &width, const int &height)
{
#if defined(Q_OS_HARMATTAN)
if ((m_bits == 0) || (width != m_width) || (height != m_height)) {
if (m_bits != 0)
delete[] m_bits;
m_width = width;
m_height = height;
m_bits = new uchar[m_width * m_height * 4];
}
int iterations = (m_width / 2) * m_height;
uchar *destination = m_bits;
const uchar *source = bits;
int r;
int g;
int b;
int u;
int y1;
int v;
int y2;
for (int i = 0; i < iterations; ++i) {
// Get UYVY chrominance and luminance values
u = *source;
y1 = *(source + 1);
v = *(source + 2);
y2 = *(source + 3);
// Apply formula from the 1st two bytes
applyFormula(r, g, b, y1, u, v);
*destination = b;
*(destination + 1) = g;
*(destination + 2) = r;
*(destination + 3) = 0;
destination += 4;
// Apply formula from the next two bytes
applyFormula(r, g, b, y2, u, v);
*destination = b;
*(destination + 1) = g;
*(destination + 2) = r;
*(destination + 3) = 0;
destination += 4;
source += 4;
}
#endif
}
void Yuv2Rgb::preCalculateValues()
{
#if defined(Q_OS_HARMATTAN)
int i;
qreal x;
m_v1 = new int[256];
m_v2 = new int[256];
m_v3 = new int[256];
m_v4 = new int[256];
for (i = 0; i < 256; i++) {
// m_v1 = 1.370705 * (V - 128.0)
x = 1.370705 * (i - 128.0);
m_v1[i] = x;
// m_v2 = 0.698001 * (V - 128.0)
x = 0.698001 * (i - 128.0);
m_v2[i] = x;
// m_v3 = 0.337633 * (U - 128.0)
x = 0.337633 * (i - 128.0);
m_v3[i] = x;
// m_v4 = 1.732446 * (U - 128.0)
x = 1.732446 * (i - 128.0);
m_v4[i] = x;
}
#endif
}
void Yuv2Rgb::applyFormula(int &r, int &g, int &b,
const int &y, const int &u, const int &v)
{
// Formula:
// R = Y + 1.370705 * (V - 128.0)
// G = Y - 0.698001 * (V - 128.0) - 0.337633 * (U - 128.0)
// B = Y + 1.732446 * (U - 128.0)
r = y + m_v1[v];
g = y - m_v2[v] - m_v3[u];
b = y + m_v4[u];
// Clamping
r = (r < 0) ? 0 : ((r > 255) ? 255 : r);
g = (g < 0) ? 0 : ((g > 255) ? 255 : g);
b = (b < 0) ? 0 : ((b > 255) ? 255 : b);
}
| [
"[email protected]"
] | |
01bd5cd673a3f9d61f0f189bf514237d0c42aae9 | 41f2f6c4efa14a418a2360d8d761fd8a412ca52e | /cscommon_commbat/RpcCoder/Out - 副本/CPP/Config/RewardCfg.h | 48de78bb92f65eec5a1eea4a004052a02dd05616 | [] | no_license | wanggan768q/csommon | 57ec57a489a699ea2dc209b281faf011f9e35d94 | 8b1e4bd62e02fd20c4cd65d409989a37dbff8091 | refs/heads/master | 2023-01-11T08:13:08.266805 | 2022-02-28T09:31:57 | 2022-02-28T09:31:57 | 107,096,090 | 1 | 1 | null | 2022-12-26T19:45:41 | 2017-10-16T07:57:02 | C# | UTF-8 | C++ | false | false | 7,282 | h | #ifndef __REWARD_CONFIG_H
#define __REWARD_CONFIG_H
#ifdef CONFIG_JSON
#else
#include "ConfigUtil.h"
#enif
#define printf_message(_argg) printf(_argg)
//奖励表脜盲脰脙脢媒戮脻陆谩鹿鹿
struct RewardElement
{
friend class RewardTable;
int RewardID; //奖励ID 奖励ID
int Item1; //道具1 道具1
int ItemNum1; //道具1数量 道具1数量
int Item2; //道具2 道具2
int ItemNum2; //道具2数量 道具2数量
int Item3; //道具3 道具3
int ItemNum3; //道具3数量 道具3数量
int Item4; //道具4 道具4
int ItemNum4; //道具4数量 道具4数量
int Item5; //道具5 道具5
int ItemNum5; //道具5数量 道具5数量
private:
bool m_bIsValidate;
void SetIsValidate(bool isValid)
{
m_bIsValidate=isValid;
}
public:
bool IsValidate()
{
return m_bIsValidate;
}
RewardElement()
{
RewardID = -1;
m_bIsValidate=false;
}
};
//奖励表脜盲脰脙路芒脳掳脌脿
class RewardTable
{
friend class TableData;
private:
RewardTable(){}
~RewardTable(){}
map<int, RewardElement> m_mapElements;
vector<RewardElement> m_vecAllElements;
RewardElement m_emptyItem;
public:
static RewardTable& Instance()
{
static RewardTable sInstance;
return sInstance;
}
RewardElement GetElement(int key)
{
if( m_mapElements.count(key)>0 )
return m_mapElements[key];
return m_emptyItem;
}
bool HasElement(int key)
{
return m_mapElements.find(key) != m_mapElements.end();
}
vector<RewardElement>& GetAllElement()
{
if(!m_vecAllElements.empty())
return m_vecAllElements;
m_vecAllElements.reserve(m_mapElements.size());
for(auto iter=m_mapElements.begin(); iter != m_mapElements.end(); ++iter)
{
if(iter->second.IsValidate())
m_vecAllElements.push_back(iter->second);
}
return m_vecAllElements;
}
bool Load()
{
#ifdef CONFIG_JSON
return LoadJson("Reward.json");
#else
string strTableContent;
if( LoadConfigContent("Reward.csv", strTableContent ) )
return LoadCsv( strTableContent );
if( !LoadConfigContent("Reward.bin", strTableContent ) )
{
printf_message("脜盲脰脙脦脛录镁[Reward.bin]脦麓脮脪碌陆");
assert(false);
return false;
}
return LoadBin(strTableContent);
#endif
}
bool LoadJson(const std::string& jsonFile)
{
boost::property_tree::ptree parse;
boost::property_tree::json_parser::read_json(std::string(CONFIG_PATH) + jsonFile, parse);
boost::property_tree::ptree sms_array = parse.get_child("data");
vector<string> vecLine;
if(vecLine[0]!="RewardID"){printf_message("Reward.csv中字段[RewardID]位置不对应");assert(false); return false; }
if(vecLine[1]!="Item1"){printf_message("Reward.csv中字段[Item1]位置不对应");assert(false); return false; }
if(vecLine[2]!="ItemNum1"){printf_message("Reward.csv中字段[ItemNum1]位置不对应");assert(false); return false; }
if(vecLine[3]!="Item2"){printf_message("Reward.csv中字段[Item2]位置不对应");assert(false); return false; }
if(vecLine[4]!="ItemNum2"){printf_message("Reward.csv中字段[ItemNum2]位置不对应");assert(false); return false; }
if(vecLine[5]!="Item3"){printf_message("Reward.csv中字段[Item3]位置不对应");assert(false); return false; }
if(vecLine[6]!="ItemNum3"){printf_message("Reward.csv中字段[ItemNum3]位置不对应");assert(false); return false; }
if(vecLine[7]!="Item4"){printf_message("Reward.csv中字段[Item4]位置不对应");assert(false); return false; }
if(vecLine[8]!="ItemNum4"){printf_message("Reward.csv中字段[ItemNum4]位置不对应");assert(false); return false; }
if(vecLine[9]!="Item5"){printf_message("Reward.csv中字段[Item5]位置不对应");assert(false); return false; }
if(vecLine[10]!="ItemNum5"){printf_message("Reward.csv中字段[ItemNum5]位置不对应");assert(false); return false; }
BOOST_FOREACH(boost::property_tree::ptree::value_type& v, sms_array)
{
boost::property_tree::ptree p = v.second;
RewardElement member;
member.RewardID=atoi(vecLine[0].c_str());
member.Item1=atoi(vecLine[1].c_str());
member.ItemNum1=atoi(vecLine[2].c_str());
member.Item2=atoi(vecLine[3].c_str());
member.ItemNum2=atoi(vecLine[4].c_str());
member.Item3=atoi(vecLine[5].c_str());
member.ItemNum3=atoi(vecLine[6].c_str());
member.Item4=atoi(vecLine[7].c_str());
member.ItemNum4=atoi(vecLine[8].c_str());
member.Item5=atoi(vecLine[9].c_str());
member.ItemNum5=atoi(vecLine[10].c_str());
$ReadJsonValue$
member.SetIsValidate(true);
m_mapElements[member.RewardID] = member;
}
return true;
}
bool LoadCsv(string strContent)
{
m_vecAllElements.clear();
m_mapElements.clear();
int contentOffset = 0;
vector<string> vecLine;
vecLine = ReadCsvLine( strContent, contentOffset );
if(vecLine.size() != 11)
{
printf_message("Reward.csv脰脨脕脨脢媒脕驴脫毛脡煤鲁脡碌脛麓煤脗毛虏禄脝楼脜盲!");
assert(false);
return false;
}
if(vecLine[0]!="RewardID"){printf_message("Reward.csv中字段[RewardID]位置不对应");assert(false); return false; }
if(vecLine[1]!="Item1"){printf_message("Reward.csv中字段[Item1]位置不对应");assert(false); return false; }
if(vecLine[2]!="ItemNum1"){printf_message("Reward.csv中字段[ItemNum1]位置不对应");assert(false); return false; }
if(vecLine[3]!="Item2"){printf_message("Reward.csv中字段[Item2]位置不对应");assert(false); return false; }
if(vecLine[4]!="ItemNum2"){printf_message("Reward.csv中字段[ItemNum2]位置不对应");assert(false); return false; }
if(vecLine[5]!="Item3"){printf_message("Reward.csv中字段[Item3]位置不对应");assert(false); return false; }
if(vecLine[6]!="ItemNum3"){printf_message("Reward.csv中字段[ItemNum3]位置不对应");assert(false); return false; }
if(vecLine[7]!="Item4"){printf_message("Reward.csv中字段[Item4]位置不对应");assert(false); return false; }
if(vecLine[8]!="ItemNum4"){printf_message("Reward.csv中字段[ItemNum4]位置不对应");assert(false); return false; }
if(vecLine[9]!="Item5"){printf_message("Reward.csv中字段[Item5]位置不对应");assert(false); return false; }
if(vecLine[10]!="ItemNum5"){printf_message("Reward.csv中字段[ItemNum5]位置不对应");assert(false); return false; }
while(true)
{
vecLine = ReadCsvLine( strContent, contentOffset );
if((int)vecLine.size() == 0 )
break;
if((int)vecLine.size() != (int)11)
{
assert(false);
return false;
}
RewardElement member;
member.RewardID=atoi(vecLine[0].c_str());
member.Item1=atoi(vecLine[1].c_str());
member.ItemNum1=atoi(vecLine[2].c_str());
member.Item2=atoi(vecLine[3].c_str());
member.ItemNum2=atoi(vecLine[4].c_str());
member.Item3=atoi(vecLine[5].c_str());
member.ItemNum3=atoi(vecLine[6].c_str());
member.Item4=atoi(vecLine[7].c_str());
member.ItemNum4=atoi(vecLine[8].c_str());
member.Item5=atoi(vecLine[9].c_str());
member.ItemNum5=atoi(vecLine[10].c_str());
member.SetIsValidate(true);
m_mapElements[member.RewardID] = member;
}
return true;
}
};
#endif
| [
"[email protected]"
] | |
da75ab18a4f7013702155430cba644ca5adf543c | a7e34664ec2ad91dcc969c00462592095045ad58 | /gpu/vulkan/vulkan_image.h | d3865638a3a263ef6b268ff995a073d4fa4954ca | [
"BSD-3-Clause"
] | permissive | BrutalD/chromium | 1dae06ae416e4badd459106129c70b69061f61ff | 6fc0f20612e16ea07cfb06910fb71a58817b20cc | refs/heads/master | 2023-01-13T01:15:01.065084 | 2020-03-26T04:06:48 | 2020-03-26T04:06:48 | 250,165,321 | 1 | 0 | BSD-3-Clause | 2020-03-26T04:59:20 | 2020-03-26T04:59:19 | null | UTF-8 | C++ | false | false | 4,703 | h | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GPU_VULKAN_VULKAN_IMAGE_H_
#define GPU_VULKAN_VULKAN_IMAGE_H_
#include <vulkan/vulkan.h>
#include "base/files/scoped_file.h"
#include "base/optional.h"
#include "base/util/type_safety/pass_key.h"
#include "build/build_config.h"
#include "gpu/ipc/common/vulkan_ycbcr_info.h"
#include "gpu/vulkan/vulkan_export.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/gpu_memory_buffer.h"
#if defined(OS_FUCHSIA)
#include <lib/zx/vmo.h>
#endif
namespace gpu {
class VulkanDeviceQueue;
class VULKAN_EXPORT VulkanImage {
public:
explicit VulkanImage(util::PassKey<VulkanImage> pass_key);
~VulkanImage();
VulkanImage(VulkanImage&) = delete;
VulkanImage& operator=(VulkanImage&) = delete;
static std::unique_ptr<VulkanImage> Create(
VulkanDeviceQueue* device_queue,
const gfx::Size& size,
VkFormat format,
VkImageUsageFlags usage,
VkImageCreateFlags flags = 0,
VkImageTiling image_tiling = VK_IMAGE_TILING_OPTIMAL,
void* vk_image_create_info_next = nullptr,
void* vk_memory_allocation_info_next = nullptr);
// Create VulkanImage with external memory, it can be exported and used by
// foreign API
static std::unique_ptr<VulkanImage> CreateWithExternalMemory(
VulkanDeviceQueue* device_queue,
const gfx::Size& size,
VkFormat format,
VkImageUsageFlags usage,
VkImageCreateFlags flags = 0,
VkImageTiling image_tiling = VK_IMAGE_TILING_OPTIMAL);
static std::unique_ptr<VulkanImage> CreateFromGpuMemoryBufferHandle(
VulkanDeviceQueue* device_queue,
gfx::GpuMemoryBufferHandle gmb_handle,
const gfx::Size& size,
VkFormat format,
VkImageUsageFlags usage,
VkImageCreateFlags flags = 0,
VkImageTiling image_tiling = VK_IMAGE_TILING_OPTIMAL);
static std::unique_ptr<VulkanImage> Create(
VulkanDeviceQueue* device_queue,
VkImage image,
VkDeviceMemory device_memory,
const gfx::Size& size,
VkFormat format,
VkImageTiling image_tiling,
VkDeviceSize device_size,
uint32_t memory_type_index,
base::Optional<VulkanYCbCrInfo>& ycbcr_info);
void Destroy();
#if defined(OS_POSIX)
base::ScopedFD GetMemoryFd(VkExternalMemoryHandleTypeFlagBits handle_type =
VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT);
#endif
#if defined(OS_FUCHSIA)
zx::vmo GetMemoryZirconHandle();
#endif
const gfx::Size& size() const { return size_; }
VkFormat format() const { return format_; }
VkDeviceSize device_size() const { return device_size_; }
uint32_t memory_type_index() const { return memory_type_index_; }
VkImageTiling image_tiling() const { return image_tiling_; }
const base::Optional<VulkanYCbCrInfo>& ycbcr_info() const {
return ycbcr_info_;
}
VkImage image() const { return image_; }
VkDeviceMemory device_memory() const { return device_memory_; }
VkExternalMemoryHandleTypeFlags handle_types() const { return handle_types_; }
private:
bool Initialize(VulkanDeviceQueue* device_queue,
const gfx::Size& size,
VkFormat format,
VkImageUsageFlags usage,
VkImageCreateFlags flags,
VkImageTiling image_tiling,
void* image_create_info_next,
void* memory_allocation_info_next,
const VkMemoryRequirements* requirements);
bool InitializeWithExternalMemory(VulkanDeviceQueue* device_queue,
const gfx::Size& size,
VkFormat format,
VkImageUsageFlags usage,
VkImageCreateFlags flags,
VkImageTiling image_tiling);
bool InitializeFromGpuMemoryBufferHandle(
VulkanDeviceQueue* device_queue,
gfx::GpuMemoryBufferHandle gmb_handle,
const gfx::Size& size,
VkFormat format,
VkImageUsageFlags usage,
VkImageCreateFlags flags,
VkImageTiling image_tiling);
VulkanDeviceQueue* device_queue_ = nullptr;
gfx::Size size_;
VkFormat format_ = VK_FORMAT_UNDEFINED;
VkDeviceSize device_size_ = 0;
uint32_t memory_type_index_ = 0;
VkImageTiling image_tiling_ = VK_IMAGE_TILING_OPTIMAL;
base::Optional<VulkanYCbCrInfo> ycbcr_info_;
VkImage image_ = VK_NULL_HANDLE;
VkDeviceMemory device_memory_ = VK_NULL_HANDLE;
VkExternalMemoryHandleTypeFlags handle_types_ = 0;
};
} // namespace gpu
#endif // GPU_VULKAN_VULKAN_IMAGE_H_
| [
"[email protected]"
] | |
86f87fae03adf4cb8b788d2dba4d4158ee8f6d11 | 6ffd23679939f59f0a09c9507a126ba056b239d7 | /dnn/test/cuda/deformable_ps_roi_pooling.cpp | 38f1ff462faebca71dc284ecf2c6c696ca91b63a | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | MegEngine/MegEngine | 74c1c9b6022c858962caf7f27e6f65220739999f | 66b79160d35b2710c00befede0c3fd729109e474 | refs/heads/master | 2023-08-23T20:01:32.476848 | 2023-08-01T07:12:01 | 2023-08-11T06:04:12 | 248,175,118 | 5,697 | 585 | Apache-2.0 | 2023-07-19T05:11:07 | 2020-03-18T08:21:58 | C++ | UTF-8 | C++ | false | false | 3,160 | cpp | #include "megdnn/oprs/nn.h"
#include "src/cuda/utils.h"
#include "test/common/checker.h"
#include "test/common/random_state.h"
#include "test/common/roi_pooling.h"
#include "test/cuda/benchmark.h"
#include "test/cuda/fixture.h"
using namespace megdnn;
using namespace test;
TEST_F(CUDA, DEFORMABLE_PSROI_POOLING_FWD) {
Checker<DeformablePSROIPooling> checker(handle_cuda());
auto run = [&checker](
size_t N, size_t C, size_t IH, size_t IW, size_t OH, size_t OW,
bool no_trans, size_t nr_bbox, size_t nr_cls, size_t part_sz,
size_t sample_per_part, float trans_std, float spatial_scale) {
DeformablePSROIPooling::Param param;
param.no_trans = no_trans;
param.pooled_h = OH;
param.pooled_w = OW;
param.trans_std = trans_std;
param.spatial_scale = spatial_scale;
param.part_size = part_sz;
param.sample_per_part = sample_per_part;
ROIPoolingRNG rois(N);
checker.set_rng(1, &rois);
checker.set_param(param).execs(
{{N, C, IH, IW}, {nr_bbox, 5}, {nr_cls, 2, OH, OW}, {}, {}});
};
run(2, 4, 5, 5, 3, 3, true, 2, 2, 1, 1, 1.f, 1.f);
run(2, 4, 5, 5, 3, 3, false, 2, 2, 1, 1, 1.f, 1.f);
run(2, 4, 5, 5, 3, 3, false, 2, 2, 1, 1, 0.5f, 1.5f);
run(2, 4, 100, 100, 60, 60, false, 2, 2, 1, 1, 0.5f, 1.5f);
run(10, 3, 102, 108, 12, 13, false, 7, 2, 2, 2, 0.5f, 1.5f);
run(2, 32, 100, 100, 50, 50, false, 16, 4, 1, 1, 1.f, 1.f);
}
TEST_F(CUDA, DEFORMABLE_PSROI_POOLING_BWD) {
Checker<DeformablePSROIPoolingBackward> checker(handle_cuda());
auto run = [&checker](
size_t N, size_t C, size_t IH, size_t IW, size_t OH, size_t OW,
bool no_trans, size_t nr_bbox, size_t nr_cls, size_t part_sz,
size_t sample_per_part, float trans_std, float spatial_scale) {
DeformablePSROIPooling::Param param;
param.no_trans = no_trans;
param.pooled_h = OH;
param.pooled_w = OW;
param.trans_std = trans_std;
param.spatial_scale = spatial_scale;
param.part_size = part_sz;
param.sample_per_part = sample_per_part;
ROIPoolingRNG rois(N);
checker.set_rng(1, &rois);
checker.set_param(param).execs({
{N, C, IH, IW}, // data
{nr_bbox, 5}, // rois
{nr_cls, 2, OH, OW}, // trans
{nr_bbox, C, OH, OW}, // out_diff
{nr_bbox, C, OH, OW}, // out_count
{N, C, IH, IW}, // data_diff
{nr_cls, 2, OH, OW} // trans_diff
});
};
run(2, 4, 5, 5, 3, 3, true, 2, 2, 1, 1, 1.f, 1.f);
run(2, 4, 5, 5, 3, 3, false, 2, 2, 2, 2, 1.f, 1.f);
run(2, 4, 5, 5, 3, 3, false, 2, 2, 1, 1, 1.f, 1.f);
run(2, 4, 5, 5, 3, 3, false, 2, 2, 1, 1, 0.5f, 1.5f);
run(2, 4, 100, 100, 60, 60, false, 2, 2, 1, 1, 0.5f, 1.5f);
run(10, 3, 102, 108, 12, 13, false, 7, 2, 2, 2, 0.5f, 1.5f);
run(2, 32, 100, 100, 50, 50, false, 16, 4, 1, 1, 1.f, 1.f);
}
// vim: syntax=cpp.doxygen
| [
"[email protected]"
] | |
1a10ca27098fb15139d8fb57eb3d6c7215a74099 | 4ceb431679147aedd57c04308f769a2521b1a9e4 | /Problems and Solutions/696 - Frog Dating.cpp | db283502379213a8cc42c9fcbea866fb2dd1673f | [] | no_license | tushar20008/Competitive-Coding | 188797383cfa4f3b722543f5a999847c0756388b | 9ec0891d6023029590cb096417b6477a011f3d61 | refs/heads/master | 2021-01-18T18:51:57.586151 | 2018-05-01T10:59:30 | 2018-05-01T10:59:30 | 86,875,720 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,306 | cpp | #include <iostream>
#include <math.h>
using namespace std;
long int gcd(long int p, long int q, long int *x, long int *y)
{
if (p == 0)
{
*x = 0;
*y = 1;
return q;
}
long int x1, y1;
long int g = gcd(q%p, p, &x1, &y1);
*x = y1 - (q/p) * x1;
*y = x1;
return g;
/*
int x1,y1,g;
if(q>p)
return gcd(q,p,y,x);
if(q==0)
{
*x=1,*y=0;
return p;
}
g=gcd(p,p%q,&x1,&y1);
*x=x1;
*y=x1 -floor(p/q)*y1;
return g;
*/
}
int main()
{
long int x,y,m,n,L;
while(cin>>x>>y>>m>>n>>L)
{
long int A=n-m; // Ax=B(mod L)
long int B=x-y;
if(B<0 && A<0)
{
B=-B;
A=-A;
}
//int B=(x-y)%L;
//if(B<0)
// B=L+B;
long int X,Y;
long int G=0;
while(G!=1)
{
G=gcd(abs(A),abs(B),&X,&Y);
G=gcd(L,G,&X,&Y);
//cout<<A<<" "<<B<<" "<<G<<endl;
A/=G;
B/=G;
L/=G;
}
G=gcd(A,L,&X,&Y);
//cout<<"A = "<<A<<" , L = "<<L<<" , X = "<<X<<" , Y = "<<Y<<" , G = "<<G<<endl;
//cout<<"B = "<<B<<endl;
if(B%G==0)// Ax = B mod L. Let G = gcd(A, L). If G does not divide B, the congruence has no solution.
{
int ans=(X*(B/G))%L; // If A and B are positive
if(ans>0)
cout<<ans<<endl;
else
cout<<ans+L<<endl;
}
else
cout<<"Impossible"<<endl;
}
return 420;
}
| [
"[email protected]"
] | |
7c48a5a45418cb52bd492e5da0c57a2cd89b9421 | cd954f06232e3b9fe008f9a6291689e75f179a88 | /codeforces/1466/c.cpp | ae53441e0f277eda7682a6bc74d28621fe7e6a09 | [
"MIT"
] | permissive | upupming/algorithm | 35446f4b15f3a505041ac65c1dc6f825951d8e99 | a3807ba05960b9025e55d668ef95b3375ae71895 | refs/heads/master | 2023-08-09T03:07:18.047084 | 2023-08-01T05:57:13 | 2023-08-01T05:57:13 | 217,478,998 | 239 | 34 | MIT | 2021-08-13T05:42:26 | 2019-10-25T07:41:19 | C++ | UTF-8 | C++ | false | false | 623 | cpp | #include <cstring>
#include <iostream>
using namespace std;
const int N = 1e5 + 20;
int t, n, st[N];
string x;
int main() {
cin >> t;
while (t--) {
int ans = 0;
memset(st, 0, sizeof st);
cin >> x;
int n = x.length();
for (int i = 0; i < n; i++) {
if (st[i]) continue;
if (i + 1 < n && x[i] == x[i + 1]) {
st[i + 1] = 1;
ans++;
}
if (i + 2 < n && x[i] == x[i + 2]) {
st[i + 2] = 1;
ans++;
}
}
cout << ans << endl;
}
return 0;
} | [
"[email protected]"
] | |
33b7a1322d27b38d9840977a0280b1a393a25e34 | c0a8fcd26dd3c4ba9c9b7c646cd3f5dfcfdc607a | /IBM_InfoSphere_Application/Submission_Arguments_Word_Count_Application_IBM_InfoSphere/output/application.Project1_Part1_Section3/Standalone/src/operator/Sink.h | bb176aa949d3aebbe515c3a73f3106f45c0bc9a9 | [] | no_license | Ray1207/Stream-Computing-Application | 006b384c09d3316022ccd267cb41fb3de7b1dab4 | 66ad27959234b3eaf572ef2c72c1cdeb561fbc95 | refs/heads/master | 2021-01-02T09:15:45.827039 | 2013-09-21T06:24:09 | 2013-09-21T06:24:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,118 | h | // eJytUd9rwjAQJq_1_0FUX2YJm01e5hZCKo4ECqK0Zx7EVCmmm0TUqSTuvY_174Yf2zIGEOWkHB33N33fXcqT71Cs5TpEsJeobTIQGBvE1Q9z9dlTv0uHWzkEG22u9VkVJJtFJG7ICL3b2jRR_0U4G4zJbDbGvJ9P1ukGzQadpy3pNHvesnrZxBTuCB_0iMnwa9cI4CkR3qtYvbPrc7zy_0pp1Vsi8KQAgMpZsAoDiCUCotGV8AG2v8EGtexIC_1FBn1jUtxpnCSMe6jg4N0kTDhb4RcqxwT6sdSrCjRjXmMpfmRsZngoZ9gjQEXnBo2DfNYLuSZ0bUTAQxIO933imMOhLZbv_0AWVEE4Pe0iN0o0snoiXrPnmK3ydE6w0q3vmuuO9UxN2HTaEO4TakfK3oLquaSqSE1DXHOtnzJOVc11nVvHTnBv_1CuAmXCyBzghNK5C_0Ar9CkaWWBowg_1AXzWdOges_0VD4qwCz4nAt0kae0daBhK_0oH2wo62havDYJPdoALDe
#ifndef SPL_OPER_INSTANCE_SINK_H_
#define SPL_OPER_INSTANCE_SINK_H_
#include <SPL/Runtime/Serialization/NetworkByteBuffer.h>
#include <SPL/Runtime/Operator/Operator.h>
#include <SPL/Runtime/Operator/ParameterValue.h>
#include <SPL/Runtime/Operator/OperatorContext.h>
#include <SPL/Runtime/Operator/Port/AutoPortMutex.h>
#include <SPL/Runtime/ProcessingElement/PE.h>
#include <SPL/Runtime/Type/SPLType.h>
#include <SPL/Runtime/Utility/CV.h>
using namespace UTILS_NAMESPACE;
#include "../type/BeJwrMSwxzjTNycxLLc40Lc8vSgFSyRmJRcWWRanFpTklwSWJAOxcA2C.h"
#include "../type/BeJwrMc40zcnMSy3ONC3PL0oBUskZiUXFAGflAjd.h"
#define MY_OPERATOR Sink$OP
#define MY_BASE_OPERATOR Sink_Base
#define MY_OPERATOR_SCOPE SPL::_Operator
namespace SPL {
namespace _Operator {
class MY_BASE_OPERATOR : public Operator
{
public:
typedef SPL::BeJwrMSwxzjTNycxLLc40Lc8vSgFSyRmJRcWWRanFpTklwSWJAOxcA2C IPort0Type;
MY_BASE_OPERATOR();
~MY_BASE_OPERATOR();
inline void tupleLogic(Tuple const & tuple, uint32_t port);
void processRaw(Tuple const & tuple, uint32_t port);
inline void punctLogic(Punctuation const & punct, uint32_t port);
void processRaw(Punctuation const & punct, uint32_t port);
SPL::rstring lit$0;
SPL::rstring lit$1;
SPL::rstring lit$2;
protected:
Mutex $svMutex;
void checkpointStateVariables(NetworkByteBuffer & opstate) const {
}
void restoreStateVariables(NetworkByteBuffer & opstate) {
}
private:
static bool globalInit_;
static bool globalIniter();
ParameterMapType paramValues_;
ParameterMapType& getParameters() { return paramValues_;}
void addParameterValue(std::string const & param, ConstValueHandle const& value)
{
ParameterMapType::iterator it = paramValues_.find(param);
if (it == paramValues_.end())
it = paramValues_.insert (std::make_pair (param, ParameterValueListType())).first;
it->second.push_back(&ParameterValue::create(value));
}
void addParameterValue(std::string const & param)
{
ParameterMapType::iterator it = paramValues_.find(param);
if (it == paramValues_.end())
it = paramValues_.insert (std::make_pair (param, ParameterValueListType())).first;
it->second.push_back(&ParameterValue::create());
}
};
class MY_OPERATOR : public MY_BASE_OPERATOR
{
public:
MY_OPERATOR() {}
};
} // namespace _Operator
} // namespace SPL
#undef MY_OPERATOR_SCOPE
#undef MY_BASE_OPERATOR
#undef MY_OPERATOR
#endif // SPL_OPER_INSTANCE_SINK_H_
| [
"[email protected]"
] | |
77e090acee1988a8bc108acaf086618e6c08ed3e | 08dd0048db82af92f15e87c426f20671434dee6a | /test/util.t.cpp | e13f65fb24351411cf285f6c9b4cb4017da3d9a5 | [
"MIT"
] | permissive | kpeace/gsl-lite | 315c6f7c549e69d576125e215fde13aa6867e0a3 | b9649a4d51d8656ed96a89cdd7812878db17f07d | refs/heads/master | 2021-04-27T16:57:10.815927 | 2018-02-12T09:22:12 | 2018-02-12T09:22:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,169 | cpp | //
// gsl-lite is based on GSL: Guideline Support Library.
// For more information see https://github.com/martinmoene/gsl-lite
//
// Copyright (c) 2015 Martin Moene
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "gsl-lite.t.hpp"
#include <functional>
#define gsl_CPP11_OR_GREATER_WRT_FINAL ( gsl_CPP11_OR_GREATER || gsl_COMPILER_MSVC_VERSION >= 11 )
CASE( "finally: Allows to run lambda on leaving scope" )
{
#if gsl_CPP11_OR_GREATER_WRT_FINAL
struct F { static void incr( int & i ) { i += 1; } };
int i = 0;
{
auto _ = finally( [&]() { F::incr( i ); } );
EXPECT( i == 0 );
}
EXPECT( i == 1 );
#else
EXPECT( !!"lambda is not available (no C++11)" );
#endif
}
CASE( "finally: Allows to run function (bind) on leaving scope" )
{
#if gsl_CPP11_OR_GREATER_WRT_FINAL
struct F { static void incr( int & i ) { i += 1; } };
int i = 0;
{
auto _ = finally( std::bind( &F::incr, std::ref( i ) ) );
EXPECT( i == 0 );
}
EXPECT( i == 1 );
#else
EXPECT( !!"auto and std::ref perhaps not available (no C++11)" );
#endif
}
namespace{ int g_i = 0; }
CASE( "finally: Allows to run function (pointer) on leaving scope" )
{
struct F { static void incr() { g_i += 1; } };
#if gsl_CPP11_OR_GREATER_WRT_FINAL
g_i = 0;
{
auto _ = finally( &F::incr );
EXPECT( g_i == 0 );
}
EXPECT( g_i == 1 );
#else
g_i = 0;
{
final_action _ = finally( &F::incr );
EXPECT( g_i == 0 );
}
EXPECT( g_i == 1 );
#endif
}
CASE( "finally: Allows to move final_action" )
{
#if gsl_CPP11_OR_GREATER_WRT_FINAL
struct F { static void incr( int & i ) { i += 1; } };
int i = 0;
{
auto _1 = finally( [&]() { F::incr( i ); } );
{
auto _2 = std::move( _1 );
EXPECT( i == 0 );
}
EXPECT( i == 1 );
{
auto _2 = std::move( _1 );
EXPECT( i == 1 );
}
EXPECT( i == 1 );
}
EXPECT( i == 1 );
#else
struct F { static void incr() { g_i += 1; } };
g_i = 0;
{
final_action _1 = finally( &F::incr );
{
final_action _2 = _1;
EXPECT( g_i == 0 );
}
EXPECT( g_i == 1 );
{
final_action _2 = _1;
EXPECT( g_i == 1 );
}
EXPECT( g_i == 1 );
}
EXPECT( g_i == 1 );
#endif
}
CASE( "finally: Allows moving final_action to throw" "[.]")
{
#if gsl_CPP11_OR_GREATER_WRT_FINAL
struct action
{
int & i_;
void operator()(){ i_ += 1; }
action( int & i ) : i_( i ) {}
action( action && other ) : i_( other.i_) { throw std::runtime_error("action move-ctor"); }
};
int i = 0;
{
{
EXPECT_THROWS( finally( action( i ) ) );
}
EXPECT( i == 1 );
}
// ...
#else
EXPECT( !!"lambda is not available (no C++11)" );
#endif
}
CASE( "on_return: Allows to perform action on leaving scope without exception (gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD)" )
{
#if gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD
#if gsl_CPP11_OR_GREATER_WRT_FINAL
struct F {
static void incr() { g_i += 1; }
static void pass() { try { auto _ = on_return( &F::incr ); /*throw std::exception();*/ } catch (...) {} }
static void fail() { try { auto _ = on_return( &F::incr ); throw std::exception(); } catch (...) {} }
};
#else
struct F {
static void incr() { g_i += 1; }
static void pass() { try { final_action_return _ = on_return( &F::incr ); /*throw std::exception();*/ } catch (...) {} }
static void fail() { try { final_action_return _ = on_return( &F::incr ); throw std::exception(); } catch (...) {} }
};
#endif
{ g_i = 0; F::pass(); EXPECT( g_i == 1 ); }
{ g_i = 0; F::fail(); EXPECT( g_i == 0 ); }
#else
EXPECT( !!"on_return not available (no gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD)" );
#endif
}
CASE( "on_error: Allows to perform action on leaving scope via an exception (gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD)" )
{
#if gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD
#if gsl_CPP11_OR_GREATER_WRT_FINAL
struct F {
static void incr() { g_i += 1; }
static void pass() { try { auto _ = on_error( &F::incr ); /*throw std::exception();*/ } catch (...) {} }
static void fail() { try { auto _ = on_error( &F::incr ); throw std::exception(); } catch (...) {} }
};
#else
struct F {
static void incr() { g_i += 1; }
static void pass() { try { final_action_error _ = on_error( &F::incr ); /*throw std::exception();*/ } catch (...) {} }
static void fail() { try { final_action_error _ = on_error( &F::incr ); throw std::exception(); } catch (...) {} }
};
#endif
{ g_i = 0; F::pass(); EXPECT( g_i == 0 ); }
{ g_i = 0; F::fail(); EXPECT( g_i == 1 ); }
#else
EXPECT( !!"on_error not available (no gsl_FEATURE_EXPERIMENTAL_RETURN_GUARD)" );
#endif
}
CASE( "narrow_cast<>: Allows narrowing without value loss" )
{
EXPECT( narrow_cast<char>( 120 ) == 120 );
}
CASE( "narrow_cast<>: Allows narrowing with value loss" )
{
EXPECT( narrow_cast<unsigned char>( 300 ) == 44 );
}
CASE( "narrow<>(): Allows narrowing without value loss" )
{
EXPECT( narrow<char>( 120 ) == 120 );
}
CASE( "narrow<>(): Terminates when narrowing with value loss" )
{
EXPECT_THROWS_AS( narrow<char>( 300 ), narrowing_error );
}
CASE( "narrow<>(): Terminates when narrowing with sign loss" )
{
EXPECT_THROWS_AS( narrow<unsigned>( -42 ), narrowing_error );
}
// end of file
| [
"[email protected]"
] | |
f3d07fcfbdce062618d0bd08bf6b7cdda7239e82 | 15eab6a629486562d589bb1b402a4d07c8abaed5 | /labs/AlgoLabs/No11/ass_problem.cpp | d38146e4a35637cb7c72588c70fe05180835e66c | [] | no_license | Xagen37/Homework-and-compendiums | ff9914541e8ba9968f71e5c31b72cddbc478c592 | 95fa7090bdbb00092b6224a3922fd0443b6b46de | refs/heads/master | 2023-04-05T14:46:42.483239 | 2023-03-27T21:06:42 | 2023-03-27T21:06:42 | 225,426,084 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,115 | cpp | #include <algorithm>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
using type_t = long long int;
struct Edge
{
type_t from, to;
type_t cap, flow, cost;
type_t id, rev_id;
};
vector<type_t> dijkstra(type_t s, vector<vector<type_t>>& gr, vector<Edge>& edges, vector<pair<type_t, type_t>>& par)
{
set <pair <type_t, type_t>> q;
vector<type_t> dp(gr.size(), LLONG_MAX);
dp[s] = 0;
q.insert({ s, 0 });
par[s] = { -1, -1 };
while (!q.empty())
{
type_t v = q.begin()->second;
q.erase(q.begin());
for (type_t u : gr[v])
{
type_t& to = edges[u].to;
type_t& cost = edges[u].cost;
if (edges[u].flow < edges[u].cap && dp[v] + cost < dp[to])
{
q.erase({ dp[to], to });
dp[to] = dp[v] + cost;
q.insert({ dp[to], to });
par[to] = { v, u };
}
}
}
return dp;
}
struct Result
{
bool is_ok;
type_t flow;
vector<type_t> path;
};
Result get_path(type_t s, type_t t, vector<vector<type_t>>& gr, vector<Edge>& edges, vector<pair<type_t, type_t>>& par, vector<long long int>& dp)
{
if (dp[t] == LLONG_MAX)
return Result{ false, 0, vector<type_t>() };
vector<type_t> path;
pair<type_t, type_t> curr_v = par[t];
while (curr_v.first != -1)
{
path.push_back(curr_v.second);
curr_v = par[curr_v.first];
}
reverse(path.begin(), path.end());
type_t min_cap = LLONG_MAX;
for (type_t e : path)
{
min_cap = min(min_cap, edges[e].cap - edges[e].flow);
}
return { true, min_cap, path };
}
void min_cost_max_flow(type_t s, type_t t, vector<vector<type_t>>& gr, vector<Edge>& edges)
{
while (true)
{
vector<pair<type_t, type_t>> par(gr.size());
vector<type_t> dp = dijkstra(s, gr, edges, par);
Result res = get_path(s, t, gr, edges, par, dp);
if (!res.is_ok)
break;
for (type_t e : res.path)
{
edges[e].flow += res.flow;
edges[edges[e].rev_id].flow -= res.flow;
}
}
}
pair<type_t, vector<type_t>> bulgarian(vector<vector<type_t>>& gr)
{
int size = gr.size();
vector<type_t> u(size), v(size);
vector<type_t> p(size);
vector<type_t> way(size);
for (int i = 1; i < size; i++)
{
p[0] = i;
vector<type_t> min_v(size, LLONG_MAX);
vector<bool> used(size, false);
int j = 0;
while (p[j])
{
used[j] = true;
type_t curr_i = p[j], curr_j = 0;
type_t delta = LLONG_MAX;
for (int k = 1; k < size; k++)
{
if (used[k]) continue;
type_t A = gr[curr_i][k] - u[curr_i] - v[k];
if (A < min_v[k])
{
min_v[k] = A;
way[k] = j;
}
if (min_v[k] < delta)
{
delta = min_v[k];
curr_j = k;
}
}
for (int k = 0; k < size; k++)
{
if (used[k])
{
u[p[k]] += delta;
v[k] -= delta;
}
else
min_v[k] -= delta;
}
j = curr_j;
}
while (j)
{
type_t next_j = way[j];
p[j] = p[next_j];
j = next_j;
}
}
vector<type_t> answ(size);
for (int k = 1; k < size; k++)
{
answ[p[k]] = k;
}
return { -v[0], answ };
}
int main()
{
int n; cin >> n;
vector<vector<type_t>> gr(n + 1, vector<type_t>(n + 1));
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> gr[i][j];
}
}
auto res = bulgarian(gr);
cout << res.first << '\n';
for (int i = 1; i < res.second.size(); i++)
{
cout << i << ' ' << res.second[i] << '\n';
}
return 0;
} | [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.