text string | size int64 | token_count int64 |
|---|---|---|
#include "UIManager.h"
namespace Trixs
{
UIManager::UIManager(Window* window)
{
}
UIManager::~UIManager()
{
}
} | 123 | 57 |
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lite/kernels/arm/concat_compute.h"
#include <gtest/gtest.h>
#include <limits>
#include <string>
#include <vector>
#include "lite/backends/arm/math/funcs.h"
#include "lite/core/op_registry.h"
#include "lite/core/tensor.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace arm {
bool infer_shape(const operators::ConcatParam& param) {
std::vector<lite::DDim> input_dims;
for (auto p : param.x) {
input_dims.push_back(p->dims());
}
size_t axis = static_cast<size_t>(param.axis);
const size_t n = input_dims.size();
CHECK_GT_OR_FALSE(n, 0);
auto& out_dims = input_dims[0];
size_t in_zero_dims_size = out_dims.size();
for (size_t i = 1; i < n; i++) {
for (size_t j = 0; j < in_zero_dims_size; j++) {
if (j == axis) {
out_dims[axis] += input_dims[i][j];
} else {
CHECK_EQ_OR_FALSE(out_dims[j], input_dims[i][j]);
}
}
}
if (out_dims[axis] < 0) {
out_dims[axis] = -1;
}
// Set output dims
param.output->Resize(lite::DDim(out_dims));
return true;
}
void concat_compute_ref(const operators::ConcatParam& param) {
std::vector<lite::Tensor*> input = param.x;
int axis = param.axis;
infer_shape(param);
lite::Tensor* output = param.output;
int num = input.size();
int rows = 1;
auto dim_0 = input[0]->dims();
for (int i = 0; i < axis; ++i) {
rows *= dim_0[i];
}
int out_rows = rows, out_cols = 0;
std::vector<int> input_cols(input.size());
for (int i = 0; i < num; ++i) {
int input_i_numel = input[i]->dims().size() == 0 ? 0 : 1;
for (int didx = 0; didx < input[i]->dims().size(); ++didx) {
input_i_numel *= input[i]->dims()[didx];
}
int t_cols = input_i_numel / rows;
out_cols += t_cols;
input_cols[i] = t_cols;
}
// computation
auto output_data = output->mutable_data<float>();
int col_idx = 0;
for (int j = 0; j < num; ++j) {
int col_len = input_cols[j];
auto input_data = input[j]->data<float>();
for (int k = 0; k < out_rows; ++k) {
memcpy(output_data + k * out_cols + col_idx,
input_data + k * col_len,
sizeof(float) * col_len);
}
col_idx += col_len;
}
}
TEST(concat_arm, init) {
ConcatCompute concat;
ASSERT_EQ(concat.precision(), PRECISION(kAny));
ASSERT_EQ(concat.target(), TARGET(kARM));
}
TEST(concat_arm, compute_input_single) {
ConcatCompute concat;
operators::ConcatParam param;
LOG(INFO) << "test concat start";
lite::Tensor output;
lite::Tensor output_ref;
lite::Tensor tensorA;
DDimLite ddimA({10, 4, 3, 2});
tensorA.Resize(ddimA);
for (int i = 0; i < ddimA.data()[0] * ddimA.data()[1] * ddimA.data()[2] *
ddimA.data()[3];
i++) {
tensorA.mutable_data<float>()[i] = i;
}
param.x.push_back(&tensorA);
for (int cur_axis : {0, 1}) {
param.output = &output;
param.axis = cur_axis;
CHECK(infer_shape(param));
concat.SetParam(param);
LOG(INFO) << "test concat start cur_axis:" << cur_axis;
concat.Run();
LOG(INFO) << "concat.Run end";
param.output = &output_ref;
LOG(INFO) << "concat_compute_ref start";
concat_compute_ref(param);
LOG(INFO) << "concat_compute_ref end";
auto* output_data = output.data<float>();
auto* output_ref_data = output_ref.data<float>();
for (int i = 0; i < (ddimA.data()[0]) * ddimA.data()[1] * ddimA.data()[2] *
ddimA.data()[3];
i++) {
// LOG(INFO) << "output[" << i << "]:" << output_data[i] << "
// output_ref_data[" << i << "]:" << output_ref_data[i];
EXPECT_NEAR(output_data[i], output_ref_data[i], 1e-5);
}
}
}
TEST(concat_arm, compute_input_multi) {
ConcatCompute concat;
operators::ConcatParam param;
LOG(INFO) << "test concat start";
// init param
// x: tensorA, tensorB, tensorC, tensorD
// axis: 0
lite::Tensor output;
lite::Tensor output_ref;
lite::Tensor tensorA;
lite::Tensor tensorB;
lite::Tensor tensorC;
lite::Tensor tensorD;
DDimLite ddimA({10, 4, 3, 2});
DDimLite ddimB({20, 4, 3, 2});
DDimLite ddimC({30, 4, 3, 2});
DDimLite ddimD({40, 4, 3, 2});
tensorA.Resize(ddimA);
tensorB.Resize(ddimB);
tensorC.Resize(ddimC);
tensorD.Resize(ddimD);
for (int i = 0; i < ddimA.data()[0] * ddimA.data()[1] * ddimA.data()[2] *
ddimA.data()[3];
i++) {
tensorA.mutable_data<float>()[i] = i;
}
for (int i = 0; i < ddimB.data()[0] * ddimB.data()[1] * ddimB.data()[2] *
ddimB.data()[3];
i++) {
tensorB.mutable_data<float>()[i] = i + 1;
}
for (int i = 0; i < ddimC.data()[0] * ddimC.data()[1] * ddimC.data()[2] *
ddimC.data()[3];
i++) {
tensorC.mutable_data<float>()[i] = i + 2;
}
for (int i = 0; i < ddimD.data()[0] * ddimD.data()[1] * ddimD.data()[2] *
ddimD.data()[3];
i++) {
tensorD.mutable_data<float>()[i] = i + 3;
}
param.x.push_back(&tensorA);
param.x.push_back(&tensorB);
param.x.push_back(&tensorC);
param.x.push_back(&tensorD);
for (int cur_axis : {0}) {
param.output = &output;
param.axis = cur_axis;
CHECK(infer_shape(param));
concat.SetParam(param);
LOG(INFO) << "test concat start cur_axis:" << cur_axis;
concat.Run();
LOG(INFO) << "concat.Run end";
param.output = &output_ref;
LOG(INFO) << "concat_compute_ref start";
concat_compute_ref(param);
LOG(INFO) << "concat_compute_ref end";
auto* output_data = output.data<float>();
auto* output_ref_data = output_ref.data<float>();
int elem_num = (ddimA.data()[0] + ddimB.data()[0] + ddimC.data()[0] +
ddimD.data()[0]) *
ddimA.data()[1] * ddimA.data()[2] * ddimA.data()[3];
for (int i = 0; i < elem_num; i++) {
// LOG(INFO) << "output[" << i << "]:" << output_data[i] << "
// output_ref_data[" << i << "]:" << output_ref_data[i];
EXPECT_NEAR(output_data[i], output_ref_data[i], 1e-5);
}
}
}
TEST(concat, retrive_op) {
auto concat =
KernelRegistry::Global().Create<TARGET(kARM), PRECISION(kAny)>("concat");
ASSERT_FALSE(concat.empty());
ASSERT_TRUE(concat.front());
}
} // namespace arm
} // namespace kernels
} // namespace lite
} // namespace paddle
USE_LITE_KERNEL(concat, kARM, kAny, kNCHW, def);
| 6,995 | 2,843 |
#include <iostream>
#include <string>
#include <cctype>
#include <cmath>
using namespace std;
int x = 1,y=1;
int h[31]= {
1,1,1,1,1,1,
2,2,2,2,2,2,
3,3,3,3,3,3,
4,4,4,4,4,4,
5,5,5,5,5,5};
int v[31]= {
1,2,3,4,5,6,
1,2,3,4,5,6,
1,2,3,4,5,6,
1,2,3,4,5,6,
1,2,3,4,5,6};
int getPos(char c)
{
if(isalpha(c))
return c-'A';
if(c==' ')
return 26;
if(c=='-')
return 27;
if(c=='.')
return 28;
if(c=='#')
return 29;
}
int getNum(int n)
{
int t = 0;
t += abs(h[n] - x);
t += abs(v[n] - y);
x = h[n];
y = v[n];
return t;
}
int main()
{
string line;
getline(cin,line);
int sum = 0;
for(int i=0;i!=line.size();i++)
sum+=getNum(getPos(line[i]));
sum += getNum(getPos('#'));
cout << sum <<endl;
system("pause");
return 0;
}
| 799 | 468 |
#include <assert.h>
#include <vector>
using namespace std;
class Solution
{
public:
// 先排序,再依次遍历数组元素,若当前元素小于等于它前一个元素,则将其变为前一个数+1。
int minIncrementForUnique(vector<int> &A)
{
int ans = 0;
int len = A.size();
sort(A.begin(), A.end());
for (int i = 1; i < len; ++i)
{
int r = A[i], l = A[i - 1];
if (r <= l)
{
ans += (l - r + 1);
A[i] = l + 1;
}
}
return ans;
}
};
int main()
{
Solution s;
vector<int> A1 = {1, 2, 2};
assert(s.minIncrementForUnique(A1) == 1);
vector<int> A2 = {3, 2, 1, 2, 1, 7};
assert(s.minIncrementForUnique(A2) == 6);
vector<int> A3 = {};
assert(s.minIncrementForUnique(A3) == 0);
} | 789 | 358 |
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2006 Ferdinando Ametrano
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
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 license for more details.
*/
/*! \file swaptionvolcube2.hpp
\brief Swaption volatility cube, fit-later-interpolate-early approach
*/
#ifndef quantlib_swaption_volcube_fit_later_interpolate_early_h
#define quantlib_swaption_volcube_fit_later_interpolate_early_h
#include <ql/termstructures/volatility/swaption/swaptionvolcube.hpp>
#include <ql/math/interpolations/interpolation2d.hpp>
namespace QuantLib {
class SwaptionVolCube2 : public SwaptionVolatilityCube{
public:
/*! The swaption vol cube is made up of ordered swaption vol surface
layers, each layer referring to a swap index of a given length
(in years), all indexes belonging to the same family. In order
to identify the family (and its market conventions) an index of
whatever length from that family must be passed in as
swapIndexBase.
Often for short swap length the swap index family is different,
e.g. the EUR case: swap vs 6M Euribor is used for length>1Y,
while swap vs 3M Euribor is used for the 1Y length. The
shortSwapIndexBase is used to identify this second family.
*/
SwaptionVolCube2(
const Handle<SwaptionVolatilityStructure>& atmVolStructure,
const std::vector<Period>& optionTenors,
const std::vector<Period>& swapTenors,
const std::vector<Spread>& strikeSpreads,
const std::vector<std::vector<Handle<Quote> > >& volSpreads,
const std::shared_ptr<SwapIndex>& swapIndexBase,
const std::shared_ptr<SwapIndex>& shortSwapIndexBase,
bool vegaWeightedSmileFit);
//! \name LazyObject interface
//@{
void performCalculations() const;
//@}
//! \name SwaptionVolatilityCube inspectors
//@{
const Matrix& volSpreads(Size i) const { return volSpreadsMatrix_[i]; }
std::shared_ptr<SmileSection> smileSectionImpl(
const Date& optionDate,
const Period& swapTenor) const;
std::shared_ptr<SmileSection> smileSectionImpl(
Time optionTime,
Time swapLength) const;
//@}
private:
mutable std::vector<Interpolation2D> volSpreadsInterpolator_;
mutable std::vector<Matrix> volSpreadsMatrix_;
};
}
#endif
| 3,292 | 946 |
/**************************************************************************************[IntTypes.h]
Copyright (c) 2009-2010, Niklas Sorensson
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.
**************************************************************************************************/
#pragma once
#ifndef Ghack_IntTypes_h
#define Ghack_IntTypes_h
#ifdef __sun
// Not sure if there are newer versions that support C99 headers. The
// needed features are implemented in the headers below though:
# include <sys/int_types.h>
# include <sys/int_fmtio.h>
# include <sys/int_limits.h>
#else
# include <stdint.h>
# include <inttypes.h>
#endif
#include <limits.h>
#ifndef PRIu64
#define PRIu64 "lu"
#define PRIi64 "ld"
#endif
//=================================================================================================
#endif
/****************************************************************************************[XAlloc.h]
Copyright (c) 2009-2010, Niklas Sorensson
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 Ghack_XAlloc_h
#define Ghack_XAlloc_h
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
namespace GHack {
//=================================================================================================
// Simple layer on top of malloc/realloc to catch out-of-memory situtaions and provide some typing:
class OutOfMemoryException{};
static inline void* xrealloc(void *ptr, size_t size)
{
void* mem = realloc(ptr, size);
if (mem == NULL && errno == ENOMEM){
throw OutOfMemoryException();
}else {
return mem;
}
}
//=================================================================================================
}
#endif
/*******************************************************************************************[Vec.h]
Copyright (c) 2003-2007, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 Ghack_Vec_h
#define Ghack_Vec_h
#include <assert.h>
#include <new>
namespace GHack {
//=================================================================================================
// Automatically resizable arrays
//
// NOTE! Don't use this vector on datatypes that cannot be re-located in memory (with realloc)
template<class T>
class vec {
T* data;
int sz;
int cap;
// Don't allow copying (error prone):
vec<T>& operator = (vec<T>& other) { assert(0); return *this; }
vec (vec<T>& other) { assert(0); }
// Helpers for calculating next capacity:
static inline int imax (int x, int y) { int mask = (y-x) >> (sizeof(int)*8-1); return (x&mask) + (y&(~mask)); }
//static inline void nextCap(int& cap){ cap += ((cap >> 1) + 2) & ~1; }
static inline void nextCap(int& cap){ cap += ((cap >> 1) + 2) & ~1; }
public:
// Constructors:
vec() : data(NULL) , sz(0) , cap(0) { }
explicit vec(int size) : data(NULL) , sz(0) , cap(0) { growTo(size); }
vec(int size, const T& pad) : data(NULL) , sz(0) , cap(0) { growTo(size, pad); }
~vec() { clear(true); }
// Pointer to first element:
operator T* (void) { return data; }
// Size operations:
int size (void) const { return sz; }
void shrink (int nelems) { assert(nelems <= sz); for (int i = 0; i < nelems; i++) sz--, data[sz].~T(); }
void shrink_ (int nelems) { assert(nelems <= sz); sz -= nelems; }
int capacity (void) const { return cap; }
void capacity (int min_cap);
void growTo (int size);
void growTo (int size, const T& pad);
void clear (bool dealloc = false);
// Stack interface:
void push (void) { if (sz == cap) capacity(sz+1); new (&data[sz]) T(); sz++; }
void push (const T& elem) { if (sz == cap) capacity(sz+1); data[sz++] = elem; }
void push_ (const T& elem) { assert(sz < cap); data[sz++] = elem; }
void pop (void) { assert(sz > 0); sz--, data[sz].~T(); }
// NOTE: it seems possible that overflow can happen in the 'sz+1' expression of 'push()', but
// in fact it can not since it requires that 'cap' is equal to INT_MAX. This in turn can not
// happen given the way capacities are calculated (below). Essentially, all capacities are
// even, but INT_MAX is odd.
const T& last (void) const { return data[sz-1]; }
T& last (void) { return data[sz-1]; }
// Vector interface:
const T& operator [] (int index) const { return data[index]; }
T& operator [] (int index) { return data[index]; }
// Duplicatation (preferred instead):
void copyTo(vec<T>& copy) const { copy.clear(); copy.growTo(sz); for (int i = 0; i < sz; i++) copy[i] = data[i]; }
void moveTo(vec<T>& dest) { dest.clear(true); dest.data = data; dest.sz = sz; dest.cap = cap; data = NULL; sz = 0; cap = 0; }
};
template<class T>
void vec<T>::capacity(int min_cap) {
if (cap >= min_cap) return;
int add = imax((min_cap - cap + 1) & ~1, ((cap >> 1) + 2) & ~1); // NOTE: grow by approximately 3/2
if (add > INT_MAX - cap || (((data = (T*)::realloc(data, (cap += add) * sizeof(T))) == NULL) && errno == ENOMEM))
throw OutOfMemoryException();
}
template<class T>
void vec<T>::growTo(int size, const T& pad) {
if (sz >= size) return;
capacity(size);
for (int i = sz; i < size; i++) data[i] = pad;
sz = size; }
template<class T>
void vec<T>::growTo(int size) {
if (sz >= size) return;
capacity(size);
for (int i = sz; i < size; i++) new (&data[i]) T();
sz = size; }
template<class T>
void vec<T>::clear(bool dealloc) {
if (data != NULL){
for (int i = 0; i < sz; i++) data[i].~T();
sz = 0;
if (dealloc) free(data), data = NULL, cap = 0; } }
//=================================================================================================
}
#endif
/*******************************************************************************************[Alg.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 Ghack_Alg_h
#define Ghack_Alg_h
namespace GHack {
//=================================================================================================
// Useful functions on vector-like types:
//=================================================================================================
// Removing and searching for elements:
//
template<class V, class T>
static inline void remove(V& ts, const T& t)
{
int j = 0;
for (; j < ts.size() && ts[j] != t; j++);
assert(j < ts.size());
for (; j < ts.size()-1; j++) ts[j] = ts[j+1];
ts.pop();
}
template<class V, class T>
static inline bool find(V& ts, const T& t)
{
int j = 0;
for (; j < ts.size() && ts[j] != t; j++);
return j < ts.size();
}
//=================================================================================================
// Copying vectors with support for nested vector types:
//
// Base case:
template<class T>
static inline void copy(const T& from, T& to)
{
to = from;
}
// Recursive case:
template<class T>
static inline void copy(const vec<T>& from, vec<T>& to, bool append = false)
{
if (!append)
to.clear();
for (int i = 0; i < from.size(); i++){
to.push();
copy(from[i], to.last());
}
}
template<class T>
static inline void append(const vec<T>& from, vec<T>& to){ copy(from, to, true); }
//=================================================================================================
}
#endif
/*****************************************************************************************[Alloc.h]
Copyright (c) 2008-2010, Niklas Sorensson
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 Ghack_Alloc_h
#define Ghack_Alloc_h
namespace GHack {
//=================================================================================================
// Simple Region-based memory allocator:
template<class T>
class RegionAllocator
{
T* memory;
uint32_t sz;
uint32_t cap;
uint32_t wasted_;
void capacity(uint32_t min_cap);
public:
// TODO: make this a class for better type-checking?
typedef uint32_t Ref;
enum { Ref_Undef = UINT32_MAX };
enum { Unit_Size = sizeof(uint32_t) };
explicit RegionAllocator(uint32_t start_cap = 1024*1024) : memory(NULL), sz(0), cap(0), wasted_(0){ capacity(start_cap); }
~RegionAllocator()
{
if (memory != NULL)
::free(memory);
}
uint32_t size () const { return sz; }
uint32_t wasted () const { return wasted_; }
Ref alloc (int size);
void free (int size) { wasted_ += size; }
// Deref, Load Effective Address (LEA), Inverse of LEA (AEL):
T& operator[](Ref r) { assert(r >= 0 && r < sz); return memory[r]; }
const T& operator[](Ref r) const { assert(r >= 0 && r < sz); return memory[r]; }
T* lea (Ref r) { assert(r >= 0 && r < sz); return &memory[r]; }
const T* lea (Ref r) const { assert(r >= 0 && r < sz); return &memory[r]; }
Ref ael (const T* t) { assert((void*)t >= (void*)&memory[0] && (void*)t < (void*)&memory[sz-1]);
return (Ref)(t - &memory[0]); }
void moveTo(RegionAllocator& to) {
if (to.memory != NULL) ::free(to.memory);
to.memory = memory;
to.sz = sz;
to.cap = cap;
to.wasted_ = wasted_;
memory = NULL;
sz = cap = wasted_ = 0;
}
};
template<class T>
void RegionAllocator<T>::capacity(uint32_t min_cap)
{
if (cap >= min_cap) return;
uint32_t prev_cap = cap;
while (cap < min_cap){
// NOTE: Multiply by a factor (13/8) without causing overflow, then add 2 and make the
// result even by clearing the least significant bit. The resulting sequence of capacities
// is carefully chosen to hit a maximum capacity that is close to the '2^32-1' limit when
// using 'uint32_t' as indices so that as much as possible of this space can be used.
uint32_t delta = ((cap >> 1) + (cap >> 3) + 2) & ~1;
cap += delta;
if (cap <= prev_cap)
throw OutOfMemoryException();
}
//printf(" .. (%p) cap = %u\n", this, cap);
assert(cap > 0);
memory = (T*)xrealloc(memory, sizeof(T)*cap);
}
template<class T>
typename RegionAllocator<T>::Ref
RegionAllocator<T>::alloc(int size)
{
//printf("ALLOC called (this = %p, size = %d)\n", this, size); fflush(stdout);
assert(size > 0);
capacity(sz + size);
uint32_t prev_sz = sz;
sz += size;
// Handle overflow:
if (sz < prev_sz)
throw OutOfMemoryException();
return prev_sz;
}
//=================================================================================================
}
#endif
/******************************************************************************************[Heap.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 Ghack_Heap_h
#define Ghack_Heap_h
namespace GHack {
//=================================================================================================
// A heap implementation with support for decrease/increase key.
template<class Comp>
class Heap {
Comp lt; // The heap is a minimum-heap with respect to this comparator
vec<int> heap; // Heap of integers
vec<int> indices; // Each integers position (index) in the Heap
// Index "traversal" functions
static inline int left (int i) { return i*2+1; }
static inline int right (int i) { return (i+1)*2; }
static inline int parent(int i) { return (i-1) >> 1; }
void percolateUp(int i)
{
int x = heap[i];
int p = parent(i);
while (i != 0 && lt(x, heap[p])){
heap[i] = heap[p];
indices[heap[p]] = i;
i = p;
p = parent(p);
}
heap [i] = x;
indices[x] = i;
}
void percolateDown(int i)
{
int x = heap[i];
while (left(i) < heap.size()){
int child = right(i) < heap.size() && lt(heap[right(i)], heap[left(i)]) ? right(i) : left(i);
if (!lt(heap[child], x)) break;
heap[i] = heap[child];
indices[heap[i]] = i;
i = child;
}
heap [i] = x;
indices[x] = i;
}
public:
Heap(const Comp& c) : lt(c) { }
int size () const { return heap.size(); }
bool empty () const { return heap.size() == 0; }
bool inHeap (int n) const { return n < indices.size() && indices[n] >= 0; }
int operator[](int index) const { assert(index < heap.size()); return heap[index]; }
void decrease (int n) { assert(inHeap(n)); percolateUp (indices[n]); }
void increase (int n) { assert(inHeap(n)); percolateDown(indices[n]); }
// Safe variant of insert/decrease/increase:
void update(int n)
{
if (!inHeap(n))
insert(n);
else {
percolateUp(indices[n]);
percolateDown(indices[n]); }
}
void insert(int n)
{
indices.growTo(n+1, -1);
assert(!inHeap(n));
indices[n] = heap.size();
heap.push(n);
percolateUp(indices[n]);
}
int removeMin()
{
int x = heap[0];
heap[0] = heap.last();
indices[heap[0]] = 0;
indices[x] = -1;
heap.pop();
if (heap.size() > 1) percolateDown(0);
return x;
}
// Rebuild the heap from scratch, using the elements in 'ns':
void build(vec<int>& ns) {
for (int i = 0; i < heap.size(); i++)
indices[heap[i]] = -1;
heap.clear();
for (int i = 0; i < ns.size(); i++){
indices[ns[i]] = i;
heap.push(ns[i]); }
for (int i = heap.size() / 2 - 1; i >= 0; i--)
percolateDown(i);
}
void clear(bool dealloc = false)
{
for (int i = 0; i < heap.size(); i++)
indices[heap[i]] = -1;
heap.clear(dealloc);
}
};
//=================================================================================================
}
#endif
/*******************************************************************************************[Map.h]
Copyright (c) 2006-2010, Niklas Sorensson
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 Ghack_Map_h
#define Ghack_Map_h
namespace GHack {
//=================================================================================================
// Default hash/equals functions
//
template<class K> struct Hash { uint32_t operator()(const K& k) const { return hash(k); } };
template<class K> struct Equal { bool operator()(const K& k1, const K& k2) const { return k1 == k2; } };
template<class K> struct DeepHash { uint32_t operator()(const K* k) const { return hash(*k); } };
template<class K> struct DeepEqual { bool operator()(const K* k1, const K* k2) const { return *k1 == *k2; } };
static inline uint32_t hash(uint32_t x){ return x; }
static inline uint32_t hash(uint64_t x){ return (uint32_t)x; }
static inline uint32_t hash(int32_t x) { return (uint32_t)x; }
static inline uint32_t hash(int64_t x) { return (uint32_t)x; }
//=================================================================================================
// Some primes
//
static const int nprimes = 25;
static const int primes [nprimes] = { 31, 73, 151, 313, 643, 1291, 2593, 5233, 10501, 21013, 42073, 84181, 168451, 337219, 674701, 1349473, 2699299, 5398891, 10798093, 21596719, 43193641, 86387383, 172775299, 345550609, 691101253 };
//=================================================================================================
// Hash table implementation of Maps
//
template<class K, class D, class H = Hash<K>, class E = Equal<K> >
class Map {
public:
struct Pair { K key; D data; };
private:
H hash;
E equals;
vec<Pair>* table;
int cap;
int size;
// Don't allow copying (error prone):
Map<K,D,H,E>& operator = (Map<K,D,H,E>& other) { assert(0); }
Map (Map<K,D,H,E>& other) { assert(0); }
bool checkCap(int new_size) const { return new_size > cap; }
int32_t index (const K& k) const { return hash(k) % cap; }
void _insert (const K& k, const D& d) {
vec<Pair>& ps = table[index(k)];
ps.push(); ps.last().key = k; ps.last().data = d; }
void rehash () {
const vec<Pair>* old = table;
int old_cap = cap;
int newsize = primes[0];
for (int i = 1; newsize <= cap && i < nprimes; i++)
newsize = primes[i];
table = new vec<Pair>[newsize];
cap = newsize;
for (int i = 0; i < old_cap; i++){
for (int j = 0; j < old[i].size(); j++){
_insert(old[i][j].key, old[i][j].data); }}
delete [] old;
// printf(" --- rehashing, old-cap=%d, new-cap=%d\n", cap, newsize);
}
public:
Map () : table(NULL), cap(0), size(0) {}
Map (const H& h, const E& e) : hash(h), equals(e), table(NULL), cap(0), size(0){}
~Map () { delete [] table; }
// PRECONDITION: the key must already exist in the map.
const D& operator [] (const K& k) const
{
assert(size != 0);
const D* res = NULL;
const vec<Pair>& ps = table[index(k)];
for (int i = 0; i < ps.size(); i++)
if (equals(ps[i].key, k))
res = &ps[i].data;
assert(res != NULL);
return *res;
}
// PRECONDITION: the key must already exist in the map.
D& operator [] (const K& k)
{
assert(size != 0);
D* res = NULL;
vec<Pair>& ps = table[index(k)];
for (int i = 0; i < ps.size(); i++)
if (equals(ps[i].key, k))
res = &ps[i].data;
assert(res != NULL);
return *res;
}
// PRECONDITION: the key must *NOT* exist in the map.
void insert (const K& k, const D& d) { if (checkCap(size+1)) rehash(); _insert(k, d); size++; }
bool peek (const K& k, D& d) const {
if (size == 0) return false;
const vec<Pair>& ps = table[index(k)];
for (int i = 0; i < ps.size(); i++)
if (equals(ps[i].key, k)){
d = ps[i].data;
return true; }
return false;
}
bool has (const K& k) const {
if (size == 0) return false;
const vec<Pair>& ps = table[index(k)];
for (int i = 0; i < ps.size(); i++)
if (equals(ps[i].key, k))
return true;
return false;
}
// PRECONDITION: the key must exist in the map.
void remove(const K& k) {
assert(table != NULL);
vec<Pair>& ps = table[index(k)];
int j = 0;
for (; j < ps.size() && !equals(ps[j].key, k); j++);
assert(j < ps.size());
ps[j] = ps.last();
ps.pop();
size--;
}
void clear () {
cap = size = 0;
delete [] table;
table = NULL;
}
int elems() const { return size; }
int bucket_count() const { return cap; }
// NOTE: the hash and equality objects are not moved by this method:
void moveTo(Map& other){
delete [] other.table;
other.table = table;
other.cap = cap;
other.size = size;
table = NULL;
size = cap = 0;
}
// NOTE: given a bit more time, I could make a more C++-style iterator out of this:
const vec<Pair>& bucket(int i) const { return table[i]; }
};
//=================================================================================================
}
#endif
/*****************************************************************************************[Queue.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 Ghack_Queue_h
#define Ghack_Queue_h
namespace GHack {
//=================================================================================================
template<class T>
class Queue {
vec<T> buf;
int first;
int end;
public:
typedef T Key;
Queue() : buf(1), first(0), end(0) {}
void clear (bool dealloc = false) { buf.clear(dealloc); buf.growTo(1); first = end = 0; }
int size () const { return (end >= first) ? end - first : end - first + buf.size(); }
const T& operator [] (int index) const { assert(index >= 0); assert(index < size()); return buf[(first + index) % buf.size()]; }
T& operator [] (int index) { assert(index >= 0); assert(index < size()); return buf[(first + index) % buf.size()]; }
T peek () const { assert(first != end); return buf[first]; }
void pop () { assert(first != end); first++; if (first == buf.size()) first = 0; }
void insert(T elem) { // INVARIANT: buf[end] is always unused
buf[end++] = elem;
if (end == buf.size()) end = 0;
if (first == end){ // Resize:
vec<T> tmp((buf.size()*3 + 1) >> 1);
//**/printf("queue alloc: %d elems (%.1f MB)\n", tmp.size(), tmp.size() * sizeof(T) / 1000000.0);
int i = 0;
for (int j = first; j < buf.size(); j++) tmp[i++] = buf[j];
for (int j = 0 ; j < end ; j++) tmp[i++] = buf[j];
first = 0;
end = buf.size();
tmp.moveTo(buf);
}
}
};
//=================================================================================================
}
#endif
/******************************************************************************************[Sort.h]
Copyright (c) 2003-2007, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 Ghack_Sort_h
#define Ghack_Sort_h
//=================================================================================================
// Some sorting algorithms for vec's
namespace GHack {
template<class T>
struct LessThan_default {
bool operator () (T x, T y) { return x < y; }
};
template <class T, class LessThan>
void selectionSort(T* array, int size, LessThan lt)
{
int i, j, best_i;
T tmp;
for (i = 0; i < size-1; i++){
best_i = i;
for (j = i+1; j < size; j++){
if (lt(array[j], array[best_i]))
best_i = j;
}
tmp = array[i]; array[i] = array[best_i]; array[best_i] = tmp;
}
}
template <class T> static inline void selectionSort(T* array, int size) {
selectionSort(array, size, LessThan_default<T>()); }
template <class T, class LessThan>
void sort(T* array, int size, LessThan lt)
{
if (size <= 15)
selectionSort(array, size, lt);
else{
T pivot = array[size / 2];
T tmp;
int i = -1;
int j = size;
for(;;){
do i++; while(lt(array[i], pivot));
do j--; while(lt(pivot, array[j]));
if (i >= j) break;
tmp = array[i]; array[i] = array[j]; array[j] = tmp;
}
sort(array , i , lt);
sort(&array[i], size-i, lt);
}
}
template <class T> static inline void sort(T* array, int size) {
sort(array, size, LessThan_default<T>()); }
//=================================================================================================
// For 'vec's:
template <class T, class LessThan> void sort(vec<T>& v, LessThan lt) {
sort((T*)v, v.size(), lt); }
template <class T> void sort(vec<T>& v) {
sort(v, LessThan_default<T>()); }
//=================================================================================================
}
#endif
/************************************************************************************[ParseUtils.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 Ghack_ParseUtils_h
#define Ghack_ParseUtils_h
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
namespace GHack {
//-------------------------------------------------------------------------------------------------
// End-of-file detection functions for StreamBuffer and char*:
static inline bool isEof(const char* in) { return *in == '\0'; }
//-------------------------------------------------------------------------------------------------
// Generic parse functions parametrized over the input-stream type.
template<class B>
static void skipWhitespace(B& in) {
while ((*in >= 9 && *in <= 13) || *in == 32)
++in; }
template<class B>
static void skipLine(B& in) {
for (;;){
if (isEof(in)) return;
if (*in == '\n') { ++in; return; }
++in; } }
template<class B>
static double parseDouble(B& in) { // only in the form X.XXXXXe-XX
bool neg= false;
double accu = 0.0;
double currentExponent = 1;
int exponent;
skipWhitespace(in);
if(*in == EOF) return 0;
if (*in == '-') neg = true, ++in;
else if (*in == '+') ++in;
if (*in < '1' || *in > '9') printf("PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
accu = (double)(*in - '0');
++in;
if (*in != '.') printf("PARSE ERROR! Unexpected char: %c\n", *in),exit(3);
++in; // skip dot
currentExponent = 0.1;
while (*in >= '0' && *in <= '9')
accu = accu + currentExponent * ((double)(*in - '0')),
currentExponent /= 10,
++in;
if (*in != 'e') printf("PARSE ERROR! Unexpected char: %c\n", *in),exit(3);
++in; // skip dot
exponent = parseInt(in); // read exponent
accu *= pow(10,exponent);
return neg ? -accu:accu;
}
template<class B>
static int parseInt(B& in) {
int val = 0;
bool neg = false;
skipWhitespace(in);
if (*in == '-') neg = true, ++in;
else if (*in == '+') ++in;
if (*in < '0' || *in > '9') fprintf(stderr, "PARSE ERROR! Unexpected char: %c\n", *in), exit(3);
while (*in >= '0' && *in <= '9')
val = val*10 + (*in - '0'),
++in;
return neg ? -val : val; }
// String matching: in case of a match the input iterator will be advanced the corresponding
// number of characters.
template<class B>
static bool match(B& in, const char* str) {
int i;
for (i = 0; str[i] != '\0'; i++)
if (in[i] != str[i])
return false;
in += i;
return true;
}
// String matching: consumes characters eagerly, but does not require random access iterator.
template<class B>
static bool eagerMatch(B& in, const char* str) {
for (; *str != '\0'; ++str, ++in)
if (*str != *in)
return false;
return true; }
//=================================================================================================
}
#endif
/***************************************************************************************[Options.h]
Copyright (c) 2008-2010, Niklas Sorensson
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 Ghack_Options_h
#define Ghack_Options_h
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
namespace GHack {
//==================================================================================================
// Top-level option parse/help functions:
extern void parseOptions (int& argc, char** argv, bool strict = false);
extern void printUsageAndExit(int argc, char** argv, bool verbose = false);
extern void setUsageHelp (const char* str);
extern void setHelpPrefixStr (const char* str);
//==================================================================================================
// Options is an abstract class that gives the interface for all types options:
class Option
{
protected:
const char* name;
const char* description;
const char* category;
const char* type_name;
static vec<Option*>& getOptionList () { static vec<Option*> options; return options; }
static const char*& getUsageString() { static const char* usage_str; return usage_str; }
static const char*& getHelpPrefixString() { static const char* help_prefix_str = ""; return help_prefix_str; }
struct OptionLt {
bool operator()(const Option* x, const Option* y) {
int test1 = strcmp(x->category, y->category);
return test1 < 0 || (test1 == 0 && strcmp(x->type_name, y->type_name) < 0);
}
};
Option(const char* name_,
const char* desc_,
const char* cate_,
const char* type_) :
name (name_)
, description(desc_)
, category (cate_)
, type_name (type_)
{
getOptionList().push(this);
}
public:
virtual ~Option() {}
virtual bool parse (const char* str) = 0;
virtual void help (bool verbose = false) = 0;
friend void parseOptions (int& argc, char** argv, bool strict);
friend void printUsageAndExit (int argc, char** argv, bool verbose);
friend void setUsageHelp (const char* str);
friend void setHelpPrefixStr (const char* str);
};
//==================================================================================================
// Range classes with specialization for floating types:
struct IntRange {
int begin;
int end;
IntRange(int b, int e) : begin(b), end(e) {}
};
struct Int64Range {
int64_t begin;
int64_t end;
Int64Range(int64_t b, int64_t e) : begin(b), end(e) {}
};
struct DoubleRange {
double begin;
double end;
bool begin_inclusive;
bool end_inclusive;
DoubleRange(double b, bool binc, double e, bool einc) : begin(b), end(e), begin_inclusive(binc), end_inclusive(einc) {}
};
//==================================================================================================
// Double options:
class DoubleOption : public Option
{
protected:
DoubleRange range;
double value;
public:
DoubleOption(const char* c, const char* n, const char* d, double def = double(), DoubleRange r = DoubleRange(-HUGE_VAL, false, HUGE_VAL, false))
: Option(n, d, c, "<double>"), range(r), value(def) {
// FIXME: set LC_NUMERIC to "C" to make sure that strtof/strtod parses decimal point correctly.
}
operator double (void) const { return value; }
operator double& (void) { return value; }
DoubleOption& operator=(double x) { value = x; return *this; }
virtual bool parse(const char* str){
const char* span = str;
if (!match(span, "-") || !match(span, name) || !match(span, "="))
return false;
char* end;
double tmp = strtod(span, &end);
if (end == NULL)
return false;
else if (tmp >= range.end && (!range.end_inclusive || tmp != range.end)){
fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name);
exit(1);
}else if (tmp <= range.begin && (!range.begin_inclusive || tmp != range.begin)){
fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name);
exit(1); }
value = tmp;
// fprintf(stderr, "READ VALUE: %g\n", value);
return true;
}
virtual void help (bool verbose = false){
fprintf(stderr, " -%-12s = %-8s %c%4.2g .. %4.2g%c (default: %g)\n",
name, type_name,
range.begin_inclusive ? '[' : '(',
range.begin,
range.end,
range.end_inclusive ? ']' : ')',
value);
if (verbose){
fprintf(stderr, "\n %s\n", description);
fprintf(stderr, "\n");
}
}
};
//==================================================================================================
// Int options:
class IntOption : public Option
{
protected:
IntRange range;
int32_t value;
public:
IntOption(const char* c, const char* n, const char* d, int32_t def = int32_t(), IntRange r = IntRange(INT32_MIN, INT32_MAX))
: Option(n, d, c, "<int32>"), range(r), value(def) {}
operator int32_t (void) const { return value; }
operator int32_t& (void) { return value; }
IntOption& operator= (int32_t x) { value = x; return *this; }
virtual bool parse(const char* str){
const char* span = str;
if (!match(span, "-") || !match(span, name) || !match(span, "="))
return false;
char* end;
int32_t tmp = strtol(span, &end, 10);
if (end == NULL)
return false;
else if (tmp > range.end){
fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name);
exit(1);
}else if (tmp < range.begin){
fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name);
exit(1); }
value = tmp;
return true;
}
virtual void help (bool verbose = false){
fprintf(stderr, " -%-12s = %-8s [", name, type_name);
if (range.begin == INT32_MIN)
fprintf(stderr, "imin");
else
fprintf(stderr, "%4d", range.begin);
fprintf(stderr, " .. ");
if (range.end == INT32_MAX)
fprintf(stderr, "imax");
else
fprintf(stderr, "%4d", range.end);
fprintf(stderr, "] (default: %d)\n", value);
if (verbose){
fprintf(stderr, "\n %s\n", description);
fprintf(stderr, "\n");
}
}
};
// Leave this out for visual C++ until Microsoft implements C99 and gets support for strtoll.
#ifndef _MSC_VER
class Int64Option : public Option
{
protected:
Int64Range range;
int64_t value;
public:
Int64Option(const char* c, const char* n, const char* d, int64_t def = int64_t(), Int64Range r = Int64Range(INT64_MIN, INT64_MAX))
: Option(n, d, c, "<int64>"), range(r), value(def) {}
operator int64_t (void) const { return value; }
operator int64_t& (void) { return value; }
Int64Option& operator= (int64_t x) { value = x; return *this; }
virtual bool parse(const char* str){
const char* span = str;
if (!match(span, "-") || !match(span, name) || !match(span, "="))
return false;
char* end;
int64_t tmp = strtoll(span, &end, 10);
if (end == NULL)
return false;
else if (tmp > range.end){
fprintf(stderr, "ERROR! value <%s> is too large for option \"%s\".\n", span, name);
exit(1);
}else if (tmp < range.begin){
fprintf(stderr, "ERROR! value <%s> is too small for option \"%s\".\n", span, name);
exit(1); }
value = tmp;
return true;
}
virtual void help (bool verbose = false){
fprintf(stderr, " -%-12s = %-8s [", name, type_name);
if (range.begin == INT64_MIN)
fprintf(stderr, "imin");
else
fprintf(stderr, "%4" PRIi64, range.begin);
fprintf(stderr, " .. ");
if (range.end == INT64_MAX)
fprintf(stderr, "imax");
else
fprintf(stderr, "%4" PRIi64, range.end);
fprintf(stderr, "] (default: %" PRIi64")\n", value);
if (verbose){
fprintf(stderr, "\n %s\n", description);
fprintf(stderr, "\n");
}
}
};
#endif
//==================================================================================================
// String option:
class StringOption : public Option
{
const char* value;
public:
StringOption(const char* c, const char* n, const char* d, const char* def = NULL)
: Option(n, d, c, "<string>"), value(def) {}
operator const char* (void) const { return value; }
operator const char*& (void) { return value; }
StringOption& operator= (const char* x) { value = x; return *this; }
virtual bool parse(const char* str){
const char* span = str;
if (!match(span, "-") || !match(span, name) || !match(span, "="))
return false;
value = span;
return true;
}
virtual void help (bool verbose = false){
fprintf(stderr, " -%-10s = %8s\n", name, type_name);
if (verbose){
fprintf(stderr, "\n %s\n", description);
fprintf(stderr, "\n");
}
}
};
//==================================================================================================
// Bool option:
class BoolOption : public Option
{
bool value;
public:
BoolOption(const char* c, const char* n, const char* d, bool v)
: Option(n, d, c, "<bool>"), value(v) {}
operator bool (void) const { return value; }
operator bool& (void) { return value; }
BoolOption& operator=(bool b) { value = b; return *this; }
virtual bool parse(const char* str){
const char* span = str;
if (match(span, "-")){
bool b = !match(span, "no-");
if (strcmp(span, name) == 0){
value = b;
return true; }
}
return false;
}
virtual void help (bool verbose = false){
fprintf(stderr, " -%s, -no-%s", name, name);
for (uint32_t i = 0; i < 32 - strlen(name)*2; i++)
fprintf(stderr, " ");
fprintf(stderr, " ");
fprintf(stderr, "(default: %s)\n", value ? "on" : "off");
if (verbose){
fprintf(stderr, "\n %s\n", description);
fprintf(stderr, "\n");
}
}
};
//=================================================================================================
}
#endif
/****************************************************************************************[System.h]
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 Ghack_System_h
#define Ghack_System_h
//-------------------------------------------------------------------------------------------------
namespace GHack {
static inline double cpuTime(void); // CPU-time in seconds.
extern double memUsed(); // Memory in mega bytes (returns 0 for unsupported architectures).
extern double memUsedPeak(); // Peak-memory in mega bytes (returns 0 for unsupported architectures).
}
//-------------------------------------------------------------------------------------------------
// Implementation of inline functions:
#if defined(_MSC_VER) || defined(__MINGW32__)
#include <time.h>
static inline double GHack::cpuTime(void) { return (double)clock() / CLOCKS_PER_SEC; }
#else
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
static inline double GHack::cpuTime(void) {
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
return (double)ru.ru_utime.tv_sec + (double)ru.ru_utime.tv_usec / 1000000; }
#endif
#endif
/***********************************************************************************[SolverTypes.h]
Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon
CRIL - Univ. Artois, France
LRI - Univ. Paris Sud, France
Glucose sources are based on MiniSat (see below MiniSat copyrights). Permissions and copyrights of
Glucose are exactly the same as Minisat on which it is based on. (see below).
---------------
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 Ghack_SolverTypes_h
#define Ghack_SolverTypes_h
#include <assert.h>
namespace GHack {
//=================================================================================================
// Variables, literals, lifted booleans, clauses:
// NOTE! Variables are just integers. No abstraction here. They should be chosen from 0..N,
// so that they can be used as array indices.
typedef int Var;
#define var_Undef (-1)
struct Lit {
int x;
// Use this as a constructor:
friend Lit mkLit(Var var, bool sign);
bool operator == (Lit p) const { return x == p.x; }
bool operator != (Lit p) const { return x != p.x; }
bool operator < (Lit p) const { return x < p.x; } // '<' makes p, ~p adjacent in the ordering.
};
inline Lit mkLit (Var var, bool sign = false) { Lit p; p.x = var + var + (int)sign; return p; }
inline Lit operator ~(Lit p) { Lit q; q.x = p.x ^ 1; return q; }
inline Lit operator ^(Lit p, bool b) { Lit q; q.x = p.x ^ (unsigned int)b; return q; }
inline bool sign (Lit p) { return p.x & 1; }
inline int var (Lit p) { return p.x >> 1; }
// Mapping Literals to and from compact integers suitable for array indexing:
inline int toInt (Var v) { return v; }
inline int toInt (Lit p) { return p.x; }
inline Lit toLit (int i) { Lit p; p.x = i; return p; }
//const Lit lit_Undef = mkLit(var_Undef, false); // }- Useful special constants.
//const Lit lit_Error = mkLit(var_Undef, true ); // }
const Lit lit_Undef = { -2 }; // }- Useful special constants.
const Lit lit_Error = { -1 }; // }
//=================================================================================================
// Lifted booleans:
//
// NOTE: this implementation is optimized for the case when comparisons between values are mostly
// between one variable and one constant. Some care had to be taken to make sure that gcc
// does enough constant propagation to produce sensible code, and this appears to be somewhat
// fragile unfortunately.
class lbool {
uint8_t value;
public:
constexpr explicit lbool(uint8_t v) : value(v) { }
lbool() : value(0) { }
explicit lbool(bool x) : value(!x) { }
bool operator == (lbool b) const { return ((b.value&2) & (value&2)) | (!(b.value&2)&(value == b.value)); }
bool operator != (lbool b) const { return !(*this == b); }
lbool operator ^ (bool b) const { return lbool((uint8_t)(value^(uint8_t)b)); }
lbool operator && (lbool b) const {
uint8_t sel = (this->value << 1) | (b.value << 3);
uint8_t v = (0xF7F755F4 >> sel) & 3;
return lbool(v); }
lbool operator || (lbool b) const {
uint8_t sel = (this->value << 1) | (b.value << 3);
uint8_t v = (0xFCFCF400 >> sel) & 3;
return lbool(v); }
friend int toInt (lbool l);
friend lbool toLbool(int v);
};
inline int toInt (lbool l) { return l.value; }
inline lbool toLbool(int v) { return lbool((uint8_t)v); }
constexpr auto l_True = GHack::lbool((uint8_t)0);
constexpr auto l_False = GHack::lbool((uint8_t)1);
constexpr auto l_Undef = GHack::lbool((uint8_t)2);
//=================================================================================================
// Clause -- a simple class for representing a clause:
struct Clause;
typedef RegionAllocator<uint32_t>::Ref CRef;
struct Clause {
int t;
struct {
unsigned mark : 2;
unsigned learnt : 1;
unsigned has_extra : 1;
unsigned reloced : 1;
unsigned lbd : 26;
unsigned canbedel : 1;
unsigned size : 32;
unsigned szWithoutSelectors : 32;
} header;
union { Lit lit; float act; uint32_t abs; CRef rel; } data[0];
friend class ClauseAllocator;
// NOTE: This constructor cannot be used directly (doesn't allocate enough memory).
template<class V>
Clause(const V& ps, bool use_extra, bool learnt) {
header.mark = t = 0;
header.learnt = learnt;
header.has_extra = use_extra;
header.reloced = 0;
header.size = ps.size();
header.lbd = 0;
header.canbedel = 1;
for (int i = 0; i < ps.size(); i++)
data[i].lit = ps[i];
if (header.has_extra){
if (header.learnt)
data[header.size].act = 0;
else
calcAbstraction(); }
}
public:
void calcAbstraction() {
assert(header.has_extra);
uint32_t abstraction = 0;
for (int i = 0; i < size(); i++)
abstraction |= 1 << (var(data[i].lit) & 31);
data[header.size].abs = abstraction; }
int size () const { return header.size; }
void shrink (int i) { assert(i <= size()); if (header.has_extra) data[header.size-i] = data[header.size]; header.size -= i; }
void pop () { shrink(1); }
bool learnt () const { return header.learnt; }
bool has_extra () const { return header.has_extra; }
uint32_t mark () const { return header.mark; }
void mark (uint32_t m) { header.mark = m; }
const Lit& last () const { return data[header.size-1].lit; }
bool reloced () const { return header.reloced; }
CRef relocation () const { return data[0].rel; }
void relocate (CRef c) { header.reloced = 1; data[0].rel = c; }
// NOTE: somewhat unsafe to change the clause in-place! Must manually call 'calcAbstraction' afterwards for
// subsumption operations to behave correctly.
Lit& operator [] (int i) { return data[i].lit; }
Lit operator [] (int i) const { return data[i].lit; }
operator const Lit* (void) const { return (Lit*)data; }
float& activity () { assert(header.has_extra); return data[header.size].act; }
uint32_t abstraction () const { assert(header.has_extra); return data[header.size].abs; }
Lit subsumes (const Clause& other) const;
void strengthen (Lit p);
void setLBD(int i) {header.lbd = i;}
// unsigned int& lbd () { return header.lbd; }
unsigned int lbd () const { return header.lbd; }
void setCanBeDel(bool b) {header.canbedel = b;}
bool canBeDel() {return header.canbedel;}
void setSizeWithoutSelectors (unsigned int n) {header.szWithoutSelectors = n; }
unsigned int sizeWithoutSelectors () const { return header.szWithoutSelectors; }
};
//=================================================================================================
// ClauseAllocator -- a simple class for allocating memory for clauses:
const CRef CRef_Undef = RegionAllocator<uint32_t>::Ref_Undef;
class ClauseAllocator : public RegionAllocator<uint32_t>
{
static int clauseWord32Size(int size, bool has_extra){
return (sizeof(Clause) + (sizeof(Lit) * (size + (int)has_extra))) / sizeof(uint32_t); }
public:
bool extra_clause_field;
ClauseAllocator(uint32_t start_cap) : RegionAllocator<uint32_t>(start_cap), extra_clause_field(false){}
ClauseAllocator() : extra_clause_field(false){}
void moveTo(ClauseAllocator& to){
to.extra_clause_field = extra_clause_field;
RegionAllocator<uint32_t>::moveTo(to); }
template<class Lits>
CRef alloc(const Lits& ps, bool learnt = false)
{
assert(sizeof(Lit) == sizeof(uint32_t));
assert(sizeof(float) == sizeof(uint32_t));
bool use_extra = learnt | extra_clause_field;
CRef cid = RegionAllocator<uint32_t>::alloc(clauseWord32Size(ps.size(), use_extra));
new (lea(cid)) Clause(ps, use_extra, learnt);
return cid;
}
// Deref, Load Effective Address (LEA), Inverse of LEA (AEL):
Clause& operator[](Ref r) { return (Clause&)RegionAllocator<uint32_t>::operator[](r); }
const Clause& operator[](Ref r) const { return (Clause&)RegionAllocator<uint32_t>::operator[](r); }
Clause* lea (Ref r) { return (Clause*)RegionAllocator<uint32_t>::lea(r); }
const Clause* lea (Ref r) const { return (Clause*)RegionAllocator<uint32_t>::lea(r); }
Ref ael (const Clause* t){ return RegionAllocator<uint32_t>::ael((uint32_t*)t); }
void free(CRef cid)
{
Clause& c = operator[](cid);
RegionAllocator<uint32_t>::free(clauseWord32Size(c.size(), c.has_extra()));
}
void reloc(CRef& cr, ClauseAllocator& to)
{
Clause& c = operator[](cr);
if (c.reloced()) { cr = c.relocation(); return; }
cr = to.alloc(c, c.learnt());
c.relocate(cr);
// Copy extra data-fields:
// (This could be cleaned-up. Generalize Clause-constructor to be applicable here instead?)
to[cr].mark(c.mark());
if (to[cr].learnt()) {
to[cr].t = c.t;
to[cr].activity() = c.activity();
to[cr].setLBD(c.lbd());
to[cr].setSizeWithoutSelectors(c.sizeWithoutSelectors());
to[cr].setCanBeDel(c.canBeDel());
}
else if (to[cr].has_extra()) to[cr].calcAbstraction();
}
};
//=================================================================================================
// OccLists -- a class for maintaining occurence lists with lazy deletion:
template<class Idx, class Vec, class Deleted>
class OccLists
{
vec<Vec> occs;
vec<char> dirty;
vec<Idx> dirties;
Deleted deleted;
public:
OccLists(const Deleted& d) : deleted(d) {}
void init (const Idx& idx){ occs.growTo(toInt(idx)+1); dirty.growTo(toInt(idx)+1, 0); }
// Vec& operator[](const Idx& idx){ return occs[toInt(idx)]; }
Vec& operator[](const Idx& idx){ return occs[toInt(idx)]; }
Vec& lookup (const Idx& idx){ if (dirty[toInt(idx)]) clean(idx); return occs[toInt(idx)]; }
void cleanAll ();
void clean (const Idx& idx);
void smudge (const Idx& idx){
if (dirty[toInt(idx)] == 0){
dirty[toInt(idx)] = 1;
dirties.push(idx);
}
}
void clear(bool free = true){
occs .clear(free);
dirty .clear(free);
dirties.clear(free);
}
};
template<class Idx, class Vec, class Deleted>
void OccLists<Idx,Vec,Deleted>::cleanAll()
{
for (int i = 0; i < dirties.size(); i++)
// Dirties may contain duplicates so check here if a variable is already cleaned:
if (dirty[toInt(dirties[i])])
clean(dirties[i]);
dirties.clear();
}
template<class Idx, class Vec, class Deleted>
void OccLists<Idx,Vec,Deleted>::clean(const Idx& idx)
{
Vec& vec = occs[toInt(idx)];
int i, j;
for (i = j = 0; i < vec.size(); i++)
if (!deleted(vec[i]))
vec[j++] = vec[i];
vec.shrink(i - j);
dirty[toInt(idx)] = 0;
}
//=================================================================================================
// CMap -- a class for mapping clauses to values:
template<class T>
class CMap
{
struct CRefHash {
uint32_t operator()(CRef cr) const { return (uint32_t)cr; } };
typedef Map<CRef, T, CRefHash> HashTable;
HashTable map;
public:
// Size-operations:
void clear () { map.clear(); }
int size () const { return map.elems(); }
// Insert/Remove/Test mapping:
void insert (CRef cr, const T& t){ map.insert(cr, t); }
void growTo (CRef cr, const T& t){ map.insert(cr, t); } // NOTE: for compatibility
void remove (CRef cr) { map.remove(cr); }
bool has (CRef cr, T& t) { return map.peek(cr, t); }
// Vector interface (the clause 'c' must already exist):
const T& operator [] (CRef cr) const { return map[cr]; }
T& operator [] (CRef cr) { return map[cr]; }
// Iteration (not transparent at all at the moment):
int bucket_count() const { return map.bucket_count(); }
const vec<typename HashTable::Pair>& bucket(int i) const { return map.bucket(i); }
// Move contents to other map:
void moveTo(CMap& other){ map.moveTo(other.map); }
// TMP debug:
void debug(){
printf(" --- size = %d, bucket_count = %d\n", size(), map.bucket_count()); }
};
/*_________________________________________________________________________________________________
|
| subsumes : (other : const Clause&) -> Lit
|
| Description:
| Checks if clause subsumes 'other', and at the same time, if it can be used to simplify 'other'
| by subsumption resolution.
|
| Result:
| lit_Error - No subsumption or simplification
| lit_Undef - Clause subsumes 'other'
| p - The literal p can be deleted from 'other'
|________________________________________________________________________________________________@*/
inline Lit Clause::subsumes(const Clause& other) const
{
//if (other.size() < size() || (extra.abst & ~other.extra.abst) != 0)
//if (other.size() < size() || (!learnt() && !other.learnt() && (extra.abst & ~other.extra.abst) != 0))
assert(!header.learnt); assert(!other.header.learnt);
assert(header.has_extra); assert(other.header.has_extra);
if (other.header.size < header.size || (data[header.size].abs & ~other.data[other.header.size].abs) != 0)
return lit_Error;
Lit ret = lit_Undef;
const Lit* c = (const Lit*)(*this);
const Lit* d = (const Lit*)other;
for (unsigned i = 0; i < header.size; i++) {
// search for c[i] or ~c[i]
for (unsigned j = 0; j < other.header.size; j++)
if (c[i] == d[j])
goto ok;
else if (ret == lit_Undef && c[i] == ~d[j]){
ret = c[i];
goto ok;
}
// did not find it
return lit_Error;
ok:;
}
return ret;
}
inline void Clause::strengthen(Lit p)
{
remove(*this, p);
calcAbstraction();
}
//=================================================================================================
}
#endif
/***********************************************************************************[BoundedQueue.h]
Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon
CRIL - Univ. Artois, France
LRI - Univ. Paris Sud, France
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 BoundedQueue_h
#define BoundedQueue_h
//=================================================================================================
namespace GHack {
template <class T>
class bqueue {
vec<T> elems;
int first;
int last;
unsigned long long sumofqueue;
int maxsize;
int queuesize; // Number of current elements (must be < maxsize !)
bool expComputed;
double exp,value;
public:
bqueue(void) : first(0), last(0), sumofqueue(0), maxsize(0), queuesize(0),expComputed(false) { }
void initSize(int size) {growTo(size);exp = 2.0/(size+1);} // Init size of bounded size queue
void push(T x) {
expComputed = false;
if (queuesize==maxsize) {
assert(last==first); // The queue is full, next value to enter will replace oldest one
sumofqueue -= elems[last];
if ((++last) == maxsize) last = 0;
} else
queuesize++;
sumofqueue += x;
elems[first] = x;
if ((++first) == maxsize) {first = 0;last = 0;}
}
T peek() { assert(queuesize>0); return elems[last]; }
void pop() {sumofqueue-=elems[last]; queuesize--; if ((++last) == maxsize) last = 0;}
unsigned long long getsum() const {return sumofqueue;}
unsigned int getavg() const {return (unsigned int)(sumofqueue/((unsigned long long)queuesize));}
int maxSize() const {return maxsize;}
double getavgDouble() const {
double tmp = 0;
for(int i=0;i<elems.size();i++) {
tmp+=elems[i];
}
return tmp/elems.size();
}
int isvalid() const {return (queuesize==maxsize);}
void growTo(int size) {
elems.growTo(size);
first=0; maxsize=size; queuesize = 0;last = 0;
for(int i=0;i<size;i++) elems[i]=0;
}
double getAvgExp() {
if(expComputed) return value;
double a=exp;
value = elems[first];
for(int i = first;i<maxsize;i++) {
value+=a*((double)elems[i]);
a=a*exp;
}
for(int i = 0;i<last;i++) {
value+=a*((double)elems[i]);
a=a*exp;
}
value = value*(1-exp)/(1-a);
expComputed = true;
return value;
}
void fastclear() {first = 0; last = 0; queuesize=0; sumofqueue=0;} // to be called after restarts... Discard the queue
int size(void) { return queuesize; }
void clear(bool dealloc = false) { elems.clear(dealloc); first = 0; maxsize=0; queuesize=0;sumofqueue=0;}
};
}
//=================================================================================================
#endif
/************************************************************************************[Constants.h]
Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon
CRIL - Univ. Artois, France
LRI - Univ. Paris Sud, France
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.
**************************************************************************************************/
#define DYNAMICNBLEVEL
#define CONSTANTREMOVECLAUSE
#define UPDATEVARACTIVITY
// Constants for clauses reductions
#define RATIOREMOVECLAUSES 2
// Constants for restarts
#define LOWER_BOUND_FOR_BLOCKING_RESTART 10000
/****************************************************************************************[Solver.h]
Glucose -- Copyright (c) 2009, Gilles Audemard, Laurent Simon
CRIL - Univ. Artois, France
LRI - Univ. Paris Sud, France
Glucose sources are based on MiniSat (see below MiniSat copyrights). Permissions and copyrights of
Glucose are exactly the same as Minisat on which it is based on. (see below).
---------------
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 Ghack_Solver_h
#define Ghack_Solver_h
namespace GHack {
//=================================================================================================
// Solver -- the main class:
class Solver {
public:
// Constructor/Destructor:
//
Solver();
virtual ~Solver();
// Problem specification:
//
Var newVar (bool polarity = true, bool dvar = true); // Add a new variable with parameters specifying variable mode.
bool addClause (const vec<Lit>& ps); // Add a clause to the solver.
bool addEmptyClause(); // Add the empty clause, making the solver contradictory.
bool addClause (Lit p); // Add a unit clause to the solver.
bool addClause (Lit p, Lit q); // Add a binary clause to the solver.
bool addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver.
bool addClause_( vec<Lit>& ps); // Add a clause to the solver without making superflous internal copy. Will
// change the passed vector 'ps'.
// Solving:
//
bool simplify (); // Removes already satisfied clauses.
bool solve (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions.
lbool solveLimited (const vec<Lit>& assumps); // Search for a model that respects a given set of assumptions (With resource constraints).
bool solve (); // Search without assumptions.
bool solve (Lit p); // Search for a model that respects a single assumption.
bool solve (Lit p, Lit q); // Search for a model that respects two assumptions.
bool solve (Lit p, Lit q, Lit r); // Search for a model that respects three assumptions.
bool okay () const; // FALSE means solver is in a conflicting state
void toDimacs (FILE* f, const vec<Lit>& assumps); // Write CNF to file in DIMACS-format.
void toDimacs (const char *file, const vec<Lit>& assumps);
void toDimacs (FILE* f, Clause& c, vec<Var>& map, Var& max);
void printLit(Lit l);
void printClause(CRef c);
void printInitialClause(CRef c);
// Convenience versions of 'toDimacs()':
void toDimacs (const char* file);
void toDimacs (const char* file, Lit p);
void toDimacs (const char* file, Lit p, Lit q);
void toDimacs (const char* file, Lit p, Lit q, Lit r);
// Variable mode:
//
void setPolarity (Var v, bool b); // Declare which polarity the decision heuristic should use for a variable. Requires mode 'polarity_user'.
void setDecisionVar (Var v, bool b); // Declare if a variable should be eligible for selection in the decision heuristic.
// Read state:
//
lbool value (Var x) const; // The current value of a variable.
lbool value (Lit p) const; // The current value of a literal.
lbool modelValue (Var x) const; // The value of a variable in the last model. The last call to solve must have been satisfiable.
lbool modelValue (Lit p) const; // The value of a literal in the last model. The last call to solve must have been satisfiable.
int nAssigns () const; // The current number of assigned literals.
int nClauses () const; // The current number of original clauses.
int nLearnts () const; // The current number of learnt clauses.
int nVars () const; // The current number of variables.
int nFreeVars () const;
// Incremental mode
void setIncrementalMode();
void initNbInitialVars(int nb);
void printIncrementalStats();
// Resource contraints:
//
void setConfBudget(int64_t x);
void setPropBudget(int64_t x);
void budgetOff();
void interrupt(); // Trigger a (potentially asynchronous) interruption of the solver.
void clearInterrupt(); // Clear interrupt indicator flag.
// Memory managment:
//
virtual void garbageCollect();
void checkGarbage(double gf);
void checkGarbage();
// Extra results: (read-only member variable)
//
vec<lbool> model; // If problem is satisfiable, this vector contains the model (if any).
vec<Lit> conflict; // If problem is unsatisfiable (possibly under assumptions),
// this vector represent the final conflict clause expressed in the assumptions.
// Mode of operation:
//
int verbosity;
int verbEveryConflicts;
int showModel;
// Constants For restarts
double K;
double R;
double sizeLBDQueue;
double sizeTrailQueue;
// Constants for reduce DB
int firstReduceDB;
int incReduceDB;
int specialIncReduceDB,I,O,G,H,Y,Z,A,e;
unsigned int lbLBDFrozenClause;
// Constant for reducing clause
int lbSizeMinimizingClause;
unsigned int lbLBDMinimizingClause;
double var_decay;
double clause_decay;
double random_var_freq;
double random_seed;
int ccmin_mode; // Controls conflict clause minimization (0=none, 1=basic, 2=deep).
int phase_saving; // Controls the level of phase saving (0=none, 1=limited, 2=full).
bool rnd_pol; // Use random polarities for branching heuristics.
bool rnd_init_act; // Initialize variable activities with a small random value.
double garbage_frac; // The fraction of wasted memory allowed before a garbage collection is triggered.
// Certified UNSAT ( Thanks to Marijn Heule)
FILE* certifiedOutput;
bool certifiedUNSAT;
bool vbyte;
void write_char (unsigned char c);
void write_lit (int n);
// Statistics: (read-only member variable)
//
uint64_t nbRemovedClauses,nbReducedClauses,nbDL2,nbBin,nbUn,nbReduceDB,solves, starts, decisions, rnd_decisions, propagations, conflicts,conflictsRestarts,nbstopsrestarts,nbstopsrestartssame,lastblockatrestart;
uint64_t dec_vars, clauses_literals, learnts_literals, max_literals, tot_literals;
protected:
long curRestart;
// Helper structures:
//
struct VarData { CRef reason; int level; };
static inline VarData mkVarData(CRef cr, int l){ VarData d = {cr, l}; return d; }
struct Watcher {
CRef cref;
Lit blocker;
Watcher(CRef cr, Lit p) : cref(cr), blocker(p) {}
bool operator==(const Watcher& w) const { return cref == w.cref; }
bool operator!=(const Watcher& w) const { return cref != w.cref; }
};
struct WatcherDeleted
{
const ClauseAllocator& ca;
WatcherDeleted(const ClauseAllocator& _ca) : ca(_ca) {}
bool operator()(const Watcher& w) const { return ca[w.cref].mark() == 1; }
};
struct VarOrderLt {
const vec<double>& activity;
bool operator () (Var x, Var y) const { return activity[x] > activity[y]; }
VarOrderLt(const vec<double>& act) : activity(act) { }
};
// Solver state:
//
int lastIndexRed;
bool ok; // If FALSE, the constraints are already unsatisfiable. No part of the solver state may be used!
double cla_inc; // Amount to bump next clause with.
vec<double> activity; // A heuristic measurement of the activity of a variable.
double var_inc; // Amount to bump next variable with.
OccLists<Lit, vec<Watcher>, WatcherDeleted>
watches; // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
OccLists<Lit, vec<Watcher>, WatcherDeleted>
watchesBin; // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
vec<CRef> clauses; // List of problem clauses.
vec<CRef> learnts,C,T; // List of learnt clauses.
vec<lbool> assigns; // The current assignments.
vec<char> polarity; // The preferred polarity of each variable.
vec<char> decision; // Declares if a variable is eligible for selection in the decision heuristic.
vec<Lit> trail; // Assignment stack; stores all assigments made in the order they were made.
vec<int> nbpos;
vec<int> trail_lim; // Separator indices for different decision levels in 'trail'.
vec<VarData> vardata; // Stores reason and level for each variable.
int qhead; // Head of queue (as index into the trail -- no more explicit propagation queue in MiniSat).
int simpDB_assigns; // Number of top-level assignments since last execution of 'simplify()'.
int64_t simpDB_props; // Remaining number of propagations that must be made before next execution of 'simplify()'.
vec<Lit> assumptions; // Current set of assumptions provided to solve by the user.
Heap<VarOrderLt> order_heap; // A priority queue of variables ordered with respect to the variable activity.
double progress_estimate;// Set by 'search()'.
bool remove_satisfied; // Indicates whether possibly inefficient linear scan for satisfied clauses should be performed in 'simplify'.
vec<unsigned int> permDiff; // permDiff[var] contains the current conflict number... Used to count the number of LBD
#ifdef UPDATEVARACTIVITY
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
vec<Lit> lastDecisionLevel;
#endif
ClauseAllocator ca;
int nbclausesbeforereduce; // To know when it is time to reduce clause database
bqueue<unsigned int> trailQueue,lbdQueue; // Bounded queues for restarts.
float sumLBD; // used to compute the global average of LBD. Restarts...
int sumAssumptions;
// Temporaries (to reduce allocation overhead). Each variable is prefixed by the method in which it is
// used, exept 'seen' wich is used in several places.
//
vec<char> seen;
vec<Lit> analyze_stack;
vec<Lit> analyze_toclear;
vec<Lit> add_tmp;
unsigned int MYFLAG;
double max_learnts;
double learntsize_adjust_confl;
int learntsize_adjust_cnt;
// Resource contraints:
//
int64_t conflict_budget; // -1 means no budget.
int64_t propagation_budget; // -1 means no budget.
bool asynch_interrupt;
// Variables added for incremental mode
int incremental; // Use incremental SAT Solver
int nbVarsInitialFormula; // nb VAR in formula without assumptions (incremental SAT)
double totalTime4Sat,totalTime4Unsat;
int nbSatCalls,nbUnsatCalls;
vec<int> assumptionPositions,initialPositions;
// Main internal methods:
//
void insertVarOrder (Var x); // Insert a variable in the decision order priority queue.
Lit pickBranchLit (); // Return the next decision variable.
void newDecisionLevel (); // Begins a new decision level.
void uncheckedEnqueue (Lit p, CRef from = CRef_Undef); // Enqueue a literal. Assumes value of literal is undefined.
bool enqueue (Lit p, CRef from = CRef_Undef); // Test if fact 'p' contradicts current state, enqueue otherwise.
CRef propagate (); // Perform unit propagation. Returns possibly conflicting clause.
void cancelUntil (int level); // Backtrack until a certain level.
void analyze (CRef confl, vec<Lit>& out_learnt, vec<Lit> & selectors, int& out_btlevel,unsigned int &nblevels,unsigned int &szWithoutSelectors); // (bt = backtrack)
void analyzeFinal (Lit p, vec<Lit>& out_conflict); // COULD THIS BE IMPLEMENTED BY THE ORDINARIY "analyze" BY SOME REASONABLE GENERALIZATION?
bool litRedundant (Lit p, uint32_t abstract_levels); // (helper method for 'analyze()')
lbool search (int& nof_conflicts); // Search for a given number of conflicts.
lbool solve_ (); // Main solve method (assumptions given in 'assumptions').
void reduceDB (); // Reduce the set of learnt clauses.
void removeSatisfied (vec<CRef>& cs); // Shrink 'cs' to contain only non-satisfied clauses.
void rebuildOrderHeap ();
// Maintaining Variable/Clause activity:
//
void varDecayActivity (); // Decay all variables with the specified factor. Implemented by increasing the 'bump' value instead.
void varBumpActivity (Var v, double inc); // Increase a variable with the current 'bump' value.
void varBumpActivity (Var v); // Increase a variable with the current 'bump' value.
void claDecayActivity (); // Decay all clauses with the specified factor. Implemented by increasing the 'bump' value instead.
void claBumpActivity (Clause& c); // Increase a clause with the current 'bump' value.
// Operations on clauses:
//
void attachClause (CRef cr); // Attach a clause to watcher lists.
void detachClause (CRef cr, bool strict = false); // Detach a clause to watcher lists.
void removeClause (CRef cr); // Detach and free a clause.
bool locked (const Clause& c) const; // Returns TRUE if a clause is a reason for some implication in the current state.
bool satisfied (const Clause& c) const; // Returns TRUE if a clause is satisfied in the current state.
unsigned int computeLBD(const vec<Lit> & lits,int end=-1);
unsigned int computeLBD(const Clause &c);
void minimisationWithBinaryResolution(vec<Lit> &out_learnt);
void relocAll (ClauseAllocator& to);
// Misc:
//
int decisionLevel () const; // Gives the current decisionlevel.
uint32_t abstractLevel (Var x) const; // Used to represent an abstraction of sets of decision levels.
CRef reason (Var x) const;
int level (Var x) const;
double progressEstimate () const; // DELETE THIS ?? IT'S NOT VERY USEFUL ...
bool withinBudget () const;
inline bool isSelector(Var v) {return (incremental && v>nbVarsInitialFormula);}
// Static helpers:
//
// Returns a random float 0 <= x < 1. Seed must never be 0.
static inline double drand(double& seed) {
seed *= 1389796;
int q = (int)(seed / 2147483647);
seed -= (double)q * 2147483647;
return seed / 2147483647; }
// Returns a random integer 0 <= x < size. Seed must never be 0.
static inline int irand(double& seed, int size) {
return (int)(drand(seed) * size); }
};
//=================================================================================================
// Implementation of inline methods:
inline CRef Solver::reason(Var x) const { return vardata[x].reason; }
inline int Solver::level (Var x) const { return vardata[x].level; }
inline void Solver::insertVarOrder(Var x) {
if (!order_heap.inHeap(x) && decision[x]) order_heap.insert(x); }
inline void Solver::varDecayActivity() { var_inc *= (1 / var_decay); }
inline void Solver::varBumpActivity(Var v) { varBumpActivity(v, var_inc); }
inline void Solver::varBumpActivity(Var v, double inc) {
if ( (activity[v] += inc) > 1e100 ) {
// Rescale:
for (int i = 0; i < nVars(); i++)
activity[i] *= 1e-100;
var_inc *= 1e-100; }
// Update order_heap with respect to new activity:
if (order_heap.inHeap(v))
order_heap.decrease(v); }
inline void Solver::claDecayActivity() { cla_inc *= (1 / clause_decay); }
inline void Solver::claBumpActivity (Clause& c) {
if ( (c.activity() += cla_inc) > 1e20 ) {
// Rescale:
for (int i = 0; i < learnts.size(); i++)
ca[learnts[i]].activity() *= 1e-20;
cla_inc *= 1e-20; } }
inline void Solver::checkGarbage(void){ return checkGarbage(garbage_frac); }
inline void Solver::checkGarbage(double gf){
if (ca.wasted() > ca.size() * gf)
garbageCollect(); }
// NOTE: enqueue does not set the ok flag! (only public methods do)
inline bool Solver::enqueue (Lit p, CRef from) { return value(p) != l_Undef ? value(p) != l_False : (uncheckedEnqueue(p, from), true); }
inline bool Solver::addClause (const vec<Lit>& ps) { ps.copyTo(add_tmp); return addClause_(add_tmp); }
inline bool Solver::addEmptyClause () { add_tmp.clear(); return addClause_(add_tmp); }
inline bool Solver::addClause (Lit p) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); }
inline bool Solver::addClause (Lit p, Lit q) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); }
inline bool Solver::addClause (Lit p, Lit q, Lit r) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); }
inline bool Solver::locked (const Clause& c) const {
if(c.size()>2)
return value(c[0]) == l_True && reason(var(c[0])) != CRef_Undef && ca.lea(reason(var(c[0]))) == &c;
return
(value(c[0]) == l_True && reason(var(c[0])) != CRef_Undef && ca.lea(reason(var(c[0]))) == &c)
||
(value(c[1]) == l_True && reason(var(c[1])) != CRef_Undef && ca.lea(reason(var(c[1]))) == &c);
}
inline void Solver::newDecisionLevel() { trail_lim.push(trail.size()); }
inline int Solver::decisionLevel () const { return trail_lim.size(); }
inline uint32_t Solver::abstractLevel (Var x) const { return 1 << (level(x) & 31); }
inline lbool Solver::value (Var x) const { return assigns[x]; }
inline lbool Solver::value (Lit p) const { return assigns[var(p)] ^ sign(p); }
inline lbool Solver::modelValue (Var x) const { return model[x]; }
inline lbool Solver::modelValue (Lit p) const { return model[var(p)] ^ sign(p); }
inline int Solver::nAssigns () const { return trail.size(); }
inline int Solver::nClauses () const { return clauses.size(); }
inline int Solver::nLearnts () const { return learnts.size(); }
inline int Solver::nVars () const { return vardata.size(); }
inline int Solver::nFreeVars () const { return (int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]); }
inline void Solver::setPolarity (Var v, bool b) { polarity[v] = b; }
inline void Solver::setDecisionVar(Var v, bool b)
{
if ( b && !decision[v]) dec_vars++;
else if (!b && decision[v]) dec_vars--;
decision[v] = b;
insertVarOrder(v);
}
inline void Solver::setConfBudget(int64_t x){ conflict_budget = conflicts + x; }
inline void Solver::setPropBudget(int64_t x){ propagation_budget = propagations + x; }
inline void Solver::interrupt(){ asynch_interrupt = true; }
inline void Solver::clearInterrupt(){ asynch_interrupt = false; }
inline void Solver::budgetOff(){ conflict_budget = propagation_budget = -1; }
inline bool Solver::withinBudget() const {
return !asynch_interrupt &&
(conflict_budget < 0 || conflicts < (uint64_t)conflict_budget) &&
(propagation_budget < 0 || propagations < (uint64_t)propagation_budget); }
// FIXME: after the introduction of asynchronous interrruptions the solve-versions that return a
// pure bool do not give a safe interface. Either interrupts must be possible to turn off here, or
// all calls to solve must return an 'lbool'. I'm not yet sure which I prefer.
inline bool Solver::solve () { budgetOff(); assumptions.clear(); return solve_() == l_True; }
inline bool Solver::solve (Lit p) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_() == l_True; }
inline bool Solver::solve (Lit p, Lit q) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_() == l_True; }
inline bool Solver::solve (Lit p, Lit q, Lit r) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_() == l_True; }
inline bool Solver::solve (const vec<Lit>& assumps){ budgetOff(); assumps.copyTo(assumptions); return solve_() == l_True; }
inline lbool Solver::solveLimited (const vec<Lit>& assumps){ assumps.copyTo(assumptions); return solve_(); }
inline bool Solver::okay () const { return ok; }
inline void Solver::toDimacs (const char* file){ vec<Lit> as; toDimacs(file, as); }
inline void Solver::toDimacs (const char* file, Lit p){ vec<Lit> as; as.push(p); toDimacs(file, as); }
inline void Solver::toDimacs (const char* file, Lit p, Lit q){ vec<Lit> as; as.push(p); as.push(q); toDimacs(file, as); }
inline void Solver::toDimacs (const char* file, Lit p, Lit q, Lit r){ vec<Lit> as; as.push(p); as.push(q); as.push(r); toDimacs(file, as); }
//=================================================================================================
// Debug etc:
inline void Solver::printLit(Lit l)
{
printf("%s%d:%c", sign(l) ? "-" : "", var(l)+1, value(l) == l_True ? '1' : (value(l) == l_False ? '0' : 'X'));
}
inline void Solver::printClause(CRef cr)
{
Clause &c = ca[cr];
for (int i = 0; i < c.size(); i++){
printLit(c[i]);
printf(" ");
}
}
inline void Solver::printInitialClause(CRef cr)
{
Clause &c = ca[cr];
for (int i = 0; i < c.size(); i++){
if(!isSelector(var(c[i]))) {
printLit(c[i]);
printf(" ");
}
}
}
//=================================================================================================
}
#endif
/***************************************************************************************[Solver.cc]
Glucose -- Copyright (c) 2013, Gilles Audemard, Laurent Simon
CRIL - Univ. Artois, France
LRI - Univ. Paris Sud, France
Glucose sources are based on MiniSat (see below MiniSat copyrights). Permissions and copyrights of
Glucose are exactly the same as Minisat on which it is based on. (see below).
---------------
Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 <math.h>
#define M mark
#define Q conflicts
#define P push
#define B claBumpActivity
namespace GHack {
//=================================================================================================
// Options:
static const char* _cat = "CORE";
static const char* _cr = "CORE -- RESTART";
static const char* _cred = "CORE -- REDUCE";
static const char* _cm = "CORE -- MINIMIZE";
static const char* _certified = "CORE -- CERTIFIED UNSAT";
static BoolOption opt_incremental (_cat,"incremental", "Use incremental SAT solving",false);
static DoubleOption opt_K (_cr, "K", "The constant used to force restart", 0.8, DoubleRange(0, false, 1, false));
static DoubleOption opt_R (_cr, "R", "The constant used to block restart", 1.4, DoubleRange(1, false, 5, false));
static IntOption opt_size_lbd_queue (_cr, "szLBDQueue", "The size of moving average for LBD (restarts)", 50, IntRange(10, INT32_MAX));
static IntOption opt_size_trail_queue (_cr, "szTrailQueue", "The size of moving average for trail (block restarts)", 5000, IntRange(10, INT32_MAX));
static IntOption opt_first_reduce_db (_cred, "firstReduceDB", "The number of conflicts before the first reduce DB", 2000, IntRange(0, INT32_MAX));
static IntOption opt_inc_reduce_db (_cred, "incReduceDB", "Increment for reduce DB", 300, IntRange(0, INT32_MAX));
static IntOption opt_spec_inc_reduce_db (_cred, "specialIncReduceDB", "Special increment for reduce DB", 1000, IntRange(0, INT32_MAX));
static IntOption opt_lb_lbd_frozen_clause (_cred, "minLBDFrozenClause", "Protect clauses if their LBD decrease and is lower than (for one turn)", 30, IntRange(0, INT32_MAX));
static IntOption opt_lb_size_minimzing_clause (_cm, "minSizeMinimizingClause", "The min size required to minimize clause", 30, IntRange(3, INT32_MAX));
static IntOption opt_lb_lbd_minimzing_clause (_cm, "minLBDMinimizingClause", "The min LBD required to minimize clause", 6, IntRange(3, INT32_MAX));
static DoubleOption opt_var_decay (_cat, "var-decay", "The variable activity decay factor", 0.8, DoubleRange(0, false, 1, false));
static DoubleOption opt_clause_decay (_cat, "cla-decay", "The clause activity decay factor", 0.999, DoubleRange(0, false, 1, false));
static DoubleOption opt_random_var_freq (_cat, "rnd-freq", "The frequency with which the decision heuristic tries to choose a random variable", 0, DoubleRange(0, true, 1, true));
static DoubleOption opt_random_seed (_cat, "rnd-seed", "Used by the random variable selection", 91648253, DoubleRange(0, false, HUGE_VAL, false));
static IntOption opt_ccmin_mode (_cat, "ccmin-mode", "Controls conflict clause minimization (0=none, 1=basic, 2=deep)", 2, IntRange(0, 2));
static IntOption opt_phase_saving (_cat, "phase-saving", "Controls the level of phase saving (0=none, 1=limited, 2=full)", 2, IntRange(0, 2));
static BoolOption opt_rnd_init_act (_cat, "rnd-init", "Randomize the initial activity", false);
/*
static IntOption opt_restart_first (_cat, "rfirst", "The base restart interval", 100, IntRange(1, INT32_MAX));
static DoubleOption opt_restart_inc (_cat, "rinc", "Restart interval increase factor", 2, DoubleRange(1, false, HUGE_VAL, false));
*/
static DoubleOption opt_garbage_frac (_cat, "gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered", 0.20, DoubleRange(0, false, HUGE_VAL, false));
static BoolOption opt_certified (_certified, "certified", "Certified UNSAT using DRUP format", false);
static StringOption opt_certified_file (_certified, "certified-output", "Certified UNSAT output file", "NULL");
static BoolOption opt_vbyte (_certified, "vbyte", "Emit proof in variable-byte encoding", false);
//=================================================================================================
// Constructor/Destructor:
inline Solver::Solver() :
// Parameters (user settable):
//
verbosity (0)
, showModel (0)
, K (opt_K)
, R (opt_R)
, sizeLBDQueue (opt_size_lbd_queue)
, sizeTrailQueue (opt_size_trail_queue)
, firstReduceDB (opt_first_reduce_db)
, incReduceDB (opt_inc_reduce_db)
, specialIncReduceDB (opt_spec_inc_reduce_db)
, lbLBDFrozenClause (opt_lb_lbd_frozen_clause)
, lbSizeMinimizingClause (opt_lb_size_minimzing_clause)
, lbLBDMinimizingClause (opt_lb_lbd_minimzing_clause)
, var_decay (opt_var_decay)
, clause_decay (opt_clause_decay)
, random_var_freq (opt_random_var_freq)
, random_seed (opt_random_seed)
, ccmin_mode (opt_ccmin_mode)
, phase_saving (opt_phase_saving)
, rnd_pol (false)
, rnd_init_act (opt_rnd_init_act)
, garbage_frac (opt_garbage_frac)
, certifiedOutput (NULL)
, certifiedUNSAT (opt_certified)
, vbyte (opt_vbyte)
// Statistics: (formerly in 'SolverStats')
//
, nbRemovedClauses(0),nbReducedClauses(0), nbDL2(0),nbBin(0),nbUn(0) , nbReduceDB(0)
, solves(0), starts(0), decisions(0), rnd_decisions(0), propagations(0),conflicts(0),conflictsRestarts(0),nbstopsrestarts(0),nbstopsrestartssame(0),lastblockatrestart(0)
, dec_vars(0), clauses_literals(0), learnts_literals(0), max_literals(0), tot_literals(0)
, curRestart(1)
, ok (true)
, cla_inc (1)
, var_inc (1)
, watches (WatcherDeleted(ca))
, watchesBin (WatcherDeleted(ca))
, qhead (0)
, simpDB_assigns (-1)
, simpDB_props (0)
, order_heap (VarOrderLt(activity))
, progress_estimate (0)
, remove_satisfied (true)
// Resource constraints:
//
, conflict_budget (-1)
, propagation_budget (-1)
, asynch_interrupt (false)
, incremental(opt_incremental)
, nbVarsInitialFormula(INT32_MAX)
{
MYFLAG=H=Y=O=e=0;
G=1; A=4; Z=15000;
// Initialize only first time. Useful for incremental solving, useless otherwise
lbdQueue.initSize(sizeLBDQueue);
trailQueue.initSize(sizeTrailQueue);
sumLBD = 0;
nbclausesbeforereduce = firstReduceDB;
totalTime4Sat=0;totalTime4Unsat=0;
nbSatCalls=0;nbUnsatCalls=0;
if(certifiedUNSAT) {
if(!strcmp(opt_certified_file,"NULL")) {
vbyte = false; // Cannot write binary to stdout
certifiedOutput = fopen("/dev/stdout", "wb");
} else {
certifiedOutput = fopen(opt_certified_file, "wb");
}
// fprintf(certifiedOutput,"o proof DRUP\n");
}
}
inline Solver::~Solver()
{
}
/****************************************************************
Set the incremental mode
****************************************************************/
// This function set the incremental mode to true.
// You can add special code for this mode here.
inline void Solver::setIncrementalMode() {
incremental = true;
}
// Number of variables without selectors
inline void Solver::initNbInitialVars(int nb) {
nbVarsInitialFormula = nb;
}
//=================================================================================================
// Minor methods:
// Creates a new SAT variable in the solver. If 'decision' is cleared, variable will not be
// used as a decision variable (NOTE! This has effects on the meaning of a SATISFIABLE result).
//
inline Var Solver::newVar(bool sign, bool dvar)
{
int v = nVars();
watches .init(mkLit(v, false));
watches .init(mkLit(v, true ));
watchesBin .init(mkLit(v, false));
watchesBin .init(mkLit(v, true ));
assigns .push(l_Undef);
vardata .push(mkVarData(CRef_Undef, 0));
//activity .push(0);
activity .push(rnd_init_act ? drand(random_seed) * 0.00001 : 0);
seen .push(0);
permDiff .push(0);
polarity .push(sign);
decision .push();
trail .capacity(v+1);
setDecisionVar(v, dvar);
return v;
}
inline unsigned char b[2097152];
inline void Solver::write_char (unsigned char ch) {
b[e++] = ch; }
//if (putc_unlocked ((int)
#define write_char b[e++] =
//= EOF) exit(1); }
inline void Solver::write_lit (int n) {
for (; n > 127; n >>= 7)
write_char (128 | (n & 127));
write_char (n); if (e > 1048576) fwrite(b, 1, e, certifiedOutput), e = 0; }
inline bool Solver::addClause_(vec<Lit>& ps)
{
assert(decisionLevel() == 0);
if (!ok) return false;
// Check if clause is satisfied and remove false/duplicate literals:
sort(ps);
vec<Lit> oc;
oc.clear();
Lit p; int i, j, flag = 0;
if(certifiedUNSAT) {
for (i = j = 0, p = lit_Undef; i < ps.size(); i++) {
oc.push(ps[i]);
if (value(ps[i]) == l_True || ps[i] == ~p || value(ps[i]) == l_False)
flag = 1;
}
}
for (i = j = 0, p = lit_Undef; i < ps.size(); i++)
if (value(ps[i]) == l_True || ps[i] == ~p)
return true;
else if (value(ps[i]) != l_False && ps[i] != p)
ps[j++] = p = ps[i];
ps.shrink(i - j);
if (i != j && (certifiedUNSAT)) {
if (vbyte) {
write_char('a');
for (i = j = 0, p = lit_Undef; i < ps.size(); i++)
write_lit(2*(var(ps[i])+1) + sign(ps[i]));
write_lit(0);
write_char('d');
for (i = j = 0, p = lit_Undef; i < oc.size(); i++)
write_lit(2*(var(oc[i])+1) + sign(oc[i]));
write_lit(0);
}
else {
for (i = j = 0, p = lit_Undef; i < ps.size(); i++)
fprintf(certifiedOutput, "%i ", (var(ps[i]) + 1) * (-2 * sign(ps[i]) + 1));
fprintf(certifiedOutput, "0\n");
fprintf(certifiedOutput, "d ");
for (i = j = 0, p = lit_Undef; i < oc.size(); i++)
fprintf(certifiedOutput, "%i ", (var(oc[i]) + 1) * (-2 * sign(oc[i]) + 1));
fprintf(certifiedOutput, "0\n");
}
}
if (ps.size() == 0)
return ok = false;
else if (ps.size() == 1){
uncheckedEnqueue(ps[0]);
return ok = (propagate() == CRef_Undef);
}else{
CRef cr = ca.alloc(ps, false);
clauses.push(cr);
attachClause(cr);
}
return true;
}
inline void Solver::attachClause(CRef cr) {
const Clause& c = ca[cr];
assert(c.size() > 1);
if(c.size()==2) {
watchesBin[~c[0]].push(Watcher(cr, c[1]));
watchesBin[~c[1]].push(Watcher(cr, c[0]));
} else {
watches[~c[0]].push(Watcher(cr, c[1]));
watches[~c[1]].push(Watcher(cr, c[0]));
}
if (c.learnt()) learnts_literals += c.size();
else clauses_literals += c.size(); }
inline void Solver::detachClause(CRef cr, bool strict) {
const Clause& c = ca[cr];
assert(c.size() > 1);
if(c.size()==2) {
if (strict){
remove(watchesBin[~c[0]], Watcher(cr, c[1]));
remove(watchesBin[~c[1]], Watcher(cr, c[0]));
}else{
// Lazy detaching: (NOTE! Must clean all watcher lists before garbage collecting this clause)
watchesBin.smudge(~c[0]);
watchesBin.smudge(~c[1]);
}
} else {
if (strict){
remove(watches[~c[0]], Watcher(cr, c[1]));
remove(watches[~c[1]], Watcher(cr, c[0]));
}else{
// Lazy detaching: (NOTE! Must clean all watcher lists before garbage collecting this clause)
watches.smudge(~c[0]);
watches.smudge(~c[1]);
}
}
if (c.learnt()) learnts_literals -= c.size();
else clauses_literals -= c.size(); }
inline void Solver::removeClause(CRef cr) {
Clause& c = ca[cr];
if (certifiedUNSAT) {
if (vbyte) {
write_char ('d');
for (int i = 0; i < c.size(); i++)
write_lit(2*(var(c[i])+1) + sign(c[i]));
write_lit (0);
}
else {
fprintf(certifiedOutput, "d ");
for (int i = 0; i < c.size(); i++)
fprintf(certifiedOutput, "%i ", (var(c[i]) + 1) * (-2 * sign(c[i]) + 1));
fprintf(certifiedOutput, "0\n");
}
}
detachClause(cr);
// Don't leave pointers to free'd memory!
if (locked(c)) vardata[var(c[0])].reason = CRef_Undef;
c.mark(1);
ca.free(cr);
}
inline bool Solver::satisfied(const Clause& c) const {
if(incremental) // Check clauses with many selectors is too time consuming
return (value(c[0]) == l_True) || (value(c[1]) == l_True);
// Default mode.
for (int i = 0; i < c.size(); i++)
if (value(c[i]) == l_True)
return true;
return false;
}
/************************************************************
* Compute LBD functions
*************************************************************/
inline unsigned int Solver::computeLBD(const vec<Lit> & lits,int end) {
int nblevels = 0;
MYFLAG++;
if(incremental) { // ----------------- INCREMENTAL MODE
if(end==-1) end = lits.size();
unsigned int nbDone = 0;
for(int i=0;i<lits.size();i++) {
if(nbDone>=end) break;
if(isSelector(var(lits[i]))) continue;
nbDone++;
int l = level(var(lits[i]));
if (permDiff[l] != MYFLAG) {
permDiff[l] = MYFLAG;
nblevels++;
}
}
} else { // -------- DEFAULT MODE. NOT A LOT OF DIFFERENCES... BUT EASIER TO READ
for(int i=0;i<lits.size();i++) {
int l = level(var(lits[i]));
if (l && permDiff[l] != MYFLAG) {
permDiff[l] = MYFLAG;
nblevels++;
}
}
}
return nblevels;
}
inline unsigned int Solver::computeLBD(const Clause &c) {
int nblevels = 0;
MYFLAG++;
if(incremental) { // ----------------- INCREMENTAL MODE
int nbDone = 0;
for(int i=0;i<c.size();i++) {
if(nbDone>=c.sizeWithoutSelectors()) break;
if(isSelector(var(c[i]))) continue;
nbDone++;
int l = level(var(c[i]));
if (permDiff[l] != MYFLAG) {
permDiff[l] = MYFLAG;
nblevels++;
}
}
} else { // -------- DEFAULT MODE. NOT A LOT OF DIFFERENCES... BUT EASIER TO READ
for(int i=0;i<c.size();i++) {
int l = level(var(c[i]));
if (l && permDiff[l] != MYFLAG) {
permDiff[l] = MYFLAG;
nblevels++;
}
}
}
return nblevels;
}
/******************************************************************
* Minimisation with binary reolution
******************************************************************/
inline void Solver::minimisationWithBinaryResolution(vec<Lit> &out_learnt) {
// Find the LBD measure
unsigned int lbd = computeLBD(out_learnt);
Lit p = ~out_learnt[0];
if(lbd<=lbLBDMinimizingClause){
MYFLAG++;
for(int i = 1;i<out_learnt.size();i++) {
permDiff[var(out_learnt[i])] = MYFLAG;
}
vec<Watcher>& wbin = watchesBin[p];
int nb = 0;
for(int k = 0;k<wbin.size();k++) {
Lit imp = wbin[k].blocker;
if(permDiff[var(imp)]==MYFLAG && value(imp)==l_True) {
nb++;
permDiff[var(imp)]= MYFLAG-1;
}
}
int l = out_learnt.size()-1;
if(nb>0) {
nbReducedClauses++;
for(int i = 1;i<out_learnt.size()-nb;i++) {
if(permDiff[var(out_learnt[i])]!=MYFLAG) {
Lit p = out_learnt[l];
out_learnt[l] = out_learnt[i];
out_learnt[i] = p;
l--;i--;
}
}
out_learnt.shrink(nb);
}
}
}
// Revert to the state at given level (keeping all assignment at 'level' but not beyond).
//
inline void Solver::cancelUntil(int level) {
if (decisionLevel() > level){
for (int c = trail.size()-1; c >= trail_lim[level]; c--){
Var x = var(trail[c]);
assigns [x] = l_Undef;
if (phase_saving > 1 || ((phase_saving == 1) && c > trail_lim.last()))
polarity[x] = sign(trail[c]);
insertVarOrder(x); }
qhead = trail_lim[level];
trail.shrink(trail.size() - trail_lim[level]);
trail_lim.shrink(trail_lim.size() - level);
}
}
//=================================================================================================
// Major methods:
inline Lit Solver::pickBranchLit()
{
Var next = var_Undef;
// Random decision:
if (drand(random_seed) < random_var_freq && !order_heap.empty()){
next = order_heap[irand(random_seed,order_heap.size())];
if (value(next) == l_Undef && decision[next])
rnd_decisions++; }
// Activity based decision:
while (next == var_Undef || value(next) != l_Undef || !decision[next])
if (order_heap.empty()){
next = var_Undef;
break;
}else
next = order_heap.removeMin();
return next == var_Undef ? lit_Undef : mkLit(next, rnd_pol ? drand(random_seed) < 0.5 : polarity[next]);
}
/*_________________________________________________________________________________________________
|
| analyze : (confl : Clause*) (out_learnt : vec<Lit>&) (out_btlevel : int&) -> [void]
|
| Description:
| Analyze conflict and produce a reason clause.
|
| Pre-conditions:
| * 'out_learnt' is assumed to be cleared.
| * Current decision level must be greater than root level.
|
| Post-conditions:
| * 'out_learnt[0]' is the asserting literal at level 'out_btlevel'.
| * If out_learnt.size() > 1 then 'out_learnt[1]' has the greatest decision level of the
| rest of literals. There may be others from the same level though.
|
|________________________________________________________________________________________________@*/
inline void Solver::analyze(CRef confl, vec<Lit>& out_learnt,vec<Lit>&selectors, int& out_btlevel,unsigned int &lbd,unsigned int &szWithoutSelectors)
{
int pathC = 0;
Lit p = lit_Undef;
// Generate conflict clause:
//
out_learnt.push(); // (leave room for the asserting literal)
int index = trail.size() - 1;
do{
assert(confl != CRef_Undef); // (otherwise should be UIP)
Clause& c = ca[confl];
// Special case for binary clauses
// The first one has to be SAT
if( p != lit_Undef && c.size()==2 && value(c[0])==l_False) {
assert(value(c[1])==l_True);
Lit tmp = c[0];
c[0] = c[1], c[1] = tmp;
}
if (0 && c.learnt())
claBumpActivity(c);
#ifdef DYNAMICNBLEVEL
// DYNAMIC NBLEVEL trick (see competition'09 companion paper)
if(c.learnt() && c.M() != 3) {
unsigned int nblevels = I = computeLBD(c);
if(nblevels<c.lbd() ) { // improve the LBD
if(c.lbd()<=lbLBDFrozenClause) {
c.setCanBeDel(false);
}
// seems to be interesting : keep it for the next round
c.setLBD(nblevels); // Update it
if (I < A){
C.P(confl);
c.M(3);
}else if (I < 7 && !c.M()){
T.P(confl);
c.M(2); }
}
if (c.M() == 2) c.t = Q;
if (!c.M()) B(c);
}
#endif
for (int j = (p == lit_Undef) ? 0 : 1; j < c.size(); j++){
Lit q = c[j];
if (!seen[var(q)] && level(var(q)) > 0){
if(!isSelector(var(q)))
varBumpActivity(var(q));
seen[var(q)] = 1;
if (level(var(q)) >= decisionLevel()) {
pathC++;
#ifdef UPDATEVARACTIVITY
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
if(!isSelector(var(q)) && (reason(var(q))!= CRef_Undef) && ca[reason(var(q))].learnt())
lastDecisionLevel.push(q);
#endif
} else {
if(isSelector(var(q))) {
assert(value(q) == l_False);
selectors.push(q);
} else
out_learnt.push(q);
}
}
}
// Select next clause to look at:
while (!seen[var(trail[index--])]);
p = trail[index+1];
confl = reason(var(p));
seen[var(p)] = 0;
pathC--;
}while (pathC > 0);
out_learnt[0] = ~p;
// Simplify conflict clause:
//
int i, j;
for(int i = 0;i<selectors.size();i++)
out_learnt.push(selectors[i]);
out_learnt.copyTo(analyze_toclear);
if (ccmin_mode == 2){
uint32_t abstract_level = 0;
for (i = 1; i < out_learnt.size(); i++)
abstract_level |= abstractLevel(var(out_learnt[i])); // (maintain an abstraction of levels involved in conflict)
for (i = j = 1; i < out_learnt.size(); i++)
if (reason(var(out_learnt[i])) == CRef_Undef || !litRedundant(out_learnt[i], abstract_level))
out_learnt[j++] = out_learnt[i];
}else if (ccmin_mode == 1){
for (i = j = 1; i < out_learnt.size(); i++){
Var x = var(out_learnt[i]);
if (reason(x) == CRef_Undef)
out_learnt[j++] = out_learnt[i];
else{
Clause& c = ca[reason(var(out_learnt[i]))];
// Thanks to Siert Wieringa for this bug fix!
for (int k = ((c.size()==2) ? 0:1); k < c.size(); k++)
if (!seen[var(c[k])] && level(var(c[k])) > 0){
out_learnt[j++] = out_learnt[i];
break; }
}
}
}else
i = j = out_learnt.size();
max_literals += out_learnt.size();
out_learnt.shrink(i - j);
tot_literals += out_learnt.size();
/* ***************************************
Minimisation with binary clauses of the asserting clause
First of all : we look for small clauses
Then, we reduce clauses with small LBD.
Otherwise, this can be useless
*/
if(!incremental && out_learnt.size()<=lbSizeMinimizingClause) {
minimisationWithBinaryResolution(out_learnt);
}
// Find correct backtrack level:
//
if (out_learnt.size() == 1)
out_btlevel = 0;
else{
int max_i = 1;
// Find the first literal assigned at the next-highest level:
for (int i = 2; i < out_learnt.size(); i++)
if (level(var(out_learnt[i])) > level(var(out_learnt[max_i])))
max_i = i;
// Swap-in this literal at index 1:
Lit p = out_learnt[max_i];
out_learnt[max_i] = out_learnt[1];
out_learnt[1] = p;
out_btlevel = level(var(p));
}
// Compute the size of the clause without selectors (incremental mode)
if(incremental) {
szWithoutSelectors = 0;
for(int i=0;i<out_learnt.size();i++) {
if(!isSelector(var((out_learnt[i])))) szWithoutSelectors++;
else if(i>0) break;
}
} else
szWithoutSelectors = out_learnt.size();
// Compute LBD
lbd = computeLBD(out_learnt,out_learnt.size()-selectors.size());
#ifdef UPDATEVARACTIVITY
// UPDATEVARACTIVITY trick (see competition'09 companion paper)
if(lastDecisionLevel.size()>0) {
for(int i = 0;i<lastDecisionLevel.size();i++) {
if(ca[reason(var(lastDecisionLevel[i]))].lbd()<lbd)
varBumpActivity(var(lastDecisionLevel[i]));
}
lastDecisionLevel.clear();
}
#endif
lbd--;
for (int j = 0; j < analyze_toclear.size(); j++) seen[var(analyze_toclear[j])] = 0; // ('seen[]' is now cleared)
for(int j = 0 ; j<selectors.size() ; j++) seen[var(selectors[j])] = 0;
}
// Check if 'p' can be removed. 'abstract_levels' is used to abort early if the algorithm is
// visiting literals at levels that cannot be removed later.
inline bool Solver::litRedundant(Lit p, uint32_t abstract_levels)
{
analyze_stack.clear(); analyze_stack.push(p);
int top = analyze_toclear.size();
while (analyze_stack.size() > 0){
assert(reason(var(analyze_stack.last())) != CRef_Undef);
Clause& c = ca[reason(var(analyze_stack.last()))]; analyze_stack.pop();
if(c.size()==2 && value(c[0])==l_False) {
assert(value(c[1])==l_True);
Lit tmp = c[0];
c[0] = c[1], c[1] = tmp;
}
for (int i = 1; i < c.size(); i++){
Lit p = c[i];
if (!seen[var(p)] && level(var(p)) > 0){
if (reason(var(p)) != CRef_Undef && (abstractLevel(var(p)) & abstract_levels) != 0){
seen[var(p)] = 1;
analyze_stack.push(p);
analyze_toclear.push(p);
}else{
for (int j = top; j < analyze_toclear.size(); j++)
seen[var(analyze_toclear[j])] = 0;
analyze_toclear.shrink(analyze_toclear.size() - top);
return false;
}
}
}
}
return true;
}
/*_________________________________________________________________________________________________
|
| analyzeFinal : (p : Lit) -> [void]
|
| Description:
| Specialized analysis procedure to express the final conflict in terms of assumptions.
| Calculates the (possibly empty) set of assumptions that led to the assignment of 'p', and
| stores the result in 'out_conflict'.
|________________________________________________________________________________________________@*/
inline void Solver::analyzeFinal(Lit p, vec<Lit>& out_conflict)
{
out_conflict.clear();
out_conflict.push(p);
if (decisionLevel() == 0)
return;
seen[var(p)] = 1;
for (int i = trail.size()-1; i >= trail_lim[0]; i--){
Var x = var(trail[i]);
if (seen[x]){
if (reason(x) == CRef_Undef){
assert(level(x) > 0);
out_conflict.push(~trail[i]);
}else{
Clause& c = ca[reason(x)];
// for (int j = 1; j < c.size(); j++) Minisat (glucose 2.0) loop
// Bug in case of assumptions due to special data structures for Binary.
// Many thanks to Sam Bayless (sbayless@cs.ubc.ca) for discover this bug.
for (int j = ((c.size()==2) ? 0:1); j < c.size(); j++)
if (level(var(c[j])) > 0)
seen[var(c[j])] = 1;
}
seen[x] = 0;
}
}
seen[var(p)] = 0;
}
inline void Solver::uncheckedEnqueue(Lit p, CRef from)
{
assert(value(p) == l_Undef);
assigns[var(p)] = lbool(!sign(p));
vardata[var(p)] = mkVarData(from, decisionLevel());
trail.push_(p);
}
/*_________________________________________________________________________________________________
|
| propagate : [void] -> [Clause*]
|
| Description:
| Propagates all enqueued facts. If a conflict arises, the conflicting clause is returned,
| otherwise CRef_Undef.
|
| Post-conditions:
| * the propagation queue is empty, even if there was a conflict.
|________________________________________________________________________________________________@*/
inline CRef Solver::propagate()
{
CRef confl = CRef_Undef;
int num_props = 0;
watches.cleanAll();
watchesBin.cleanAll();
while (qhead < trail.size()){
Lit p = trail[qhead++]; // 'p' is enqueued fact to propagate.
vec<Watcher>& ws = watches[p];
Watcher *i, *j, *end;
num_props++;
// First, Propagate binary clauses
vec<Watcher>& wbin = watchesBin[p];
for(int k = 0;k<wbin.size();k++) {
Lit imp = wbin[k].blocker;
if(value(imp) == l_False) {
return wbin[k].cref;
}
if(value(imp) == l_Undef) {
uncheckedEnqueue(imp,wbin[k].cref);
}
}
for (i = j = (Watcher*)ws, end = i + ws.size(); i != end;){
// Try to avoid inspecting the clause:
Lit blocker = i->blocker;
if (value(blocker) == l_True){
*j++ = *i++; continue; }
// Make sure the false literal is data[1]:
CRef cr = i->cref;
Clause& c = ca[cr];
Lit false_lit = ~p;
if (c[0] == false_lit)
c[0] = c[1], c[1] = false_lit;
assert(c[1] == false_lit);
i++;
// If 0th watch is true, then clause is already satisfied.
Lit first = c[0];
Watcher w = Watcher(cr, first);
if (first != blocker && value(first) == l_True){
*j++ = w; continue; }
// Look for new watch:
if(incremental) { // ----------------- INCREMENTAL MODE
int choosenPos = -1;
for (int k = 2; k < c.size(); k++) {
if (value(c[k]) != l_False){
if(decisionLevel()>assumptions.size()) {
choosenPos = k;
break;
} else {
choosenPos = k;
if(value(c[k])==l_True || !isSelector(var(c[k]))) {
break;
}
}
}
}
if(choosenPos!=-1) {
c[1] = c[choosenPos]; c[choosenPos] = false_lit;
watches[~c[1]].push(w);
goto NextClause; }
} else { // ----------------- DEFAULT MODE (NOT INCREMENTAL)
for (int k = 2; k < c.size(); k++) {
if (value(c[k]) != l_False){
c[1] = c[k]; c[k] = false_lit;
watches[~c[1]].push(w);
goto NextClause; }
}
}
// Did not find watch -- clause is unit under assignment:
*j++ = w;
if (value(first) == l_False){
confl = cr;
qhead = trail.size();
// Copy the remaining watches:
while (i < end)
*j++ = *i++;
}else {
uncheckedEnqueue(first, cr);
}
NextClause:;
}
ws.shrink(i - j);
}
propagations += num_props;
simpDB_props -= num_props;
return confl;
}
/*_________________________________________________________________________________________________
|
| reduceDB : () -> [void]
|
| Description:
| Remove half of the learnt clauses, minus the clauses locked by the current assignment. Locked
| clauses are clauses that are reason to some assignment. Binary clauses are never removed.
|________________________________________________________________________________________________@*/
struct reduceDB_lt {
ClauseAllocator& ca;
reduceDB_lt(ClauseAllocator& ca_) : ca(ca_) {}
bool operator () (CRef x, CRef y) {
/*
// Main criteria... Like in MiniSat we keep all binary clauses
if(ca[x].size()> 2 && ca[y].size()==2) return 1;
if(ca[y].size()>2 && ca[x].size()==2) return 0;
if(ca[x].size()==2 && ca[y].size()==2) return 0;
// Second one based on literal block distance
if(ca[x].lbd()> ca[y].lbd()) return 1;
if(ca[x].lbd()< ca[y].lbd()) return 0;
*/
// Finally we can use old activity or size, we choose the last one
return ca[x].activity() < ca[y].activity();
//return x->size() < y->size();
//return ca[x].size() > 2 && (ca[y].size() == 2 || ca[x].activity() < ca[y].activity()); }
}
};
inline void Solver::reduceDB()
{
int i, j;
nbReduceDB++;
sort(learnts, reduceDB_lt(ca));
// We have a lot of "good" clauses, it is difficult to compare them. Keep more !
//if(ca[learnts[learnts.size() / RATIOREMOVECLAUSES]].lbd()<=3) nbclausesbeforereduce +=specialIncReduceDB;
// Useless :-)
//if(ca[learnts.last()].lbd()<=5) nbclausesbeforereduce +=specialIncReduceDB;
// Don't delete binary or locked clauses. From the rest, delete clauses from the first half
// Keep clauses which seem to be usefull (their lbd was reduce during this sequence)
int limit = learnts.size() / 2;
for (i = j = 0; i < learnts.size(); i++){
Clause& c = ca[learnts[i]];
if (!c.M())
if (c.lbd()>2 && c.size() > 2 && c.canBeDel() && !locked(c) && (i < limit)) {
removeClause(learnts[i]);
nbRemovedClauses++;
}
else {
if(!c.canBeDel()) limit++; //we keep c, so we can delete an other clause
c.setCanBeDel(true); // At the next step, c can be delete
learnts[j++] = learnts[i];
}
}
learnts.shrink(i - j);
checkGarbage();
}
inline void Solver::removeSatisfied(vec<CRef>& cs)
{
int i, j;
for (i = j = 0; i < cs.size(); i++){
Clause& c = ca[cs[i]];
if (c.M() == O)
if (satisfied(c))
removeClause(cs[i]);
else
cs[j++] = cs[i];
}
cs.shrink(i - j);
}
inline void Solver::rebuildOrderHeap()
{
vec<Var> vs;
for (Var v = 0; v < nVars(); v++)
if (decision[v] && value(v) == l_Undef)
vs.push(v);
order_heap.build(vs);
}
/*_________________________________________________________________________________________________
|
| simplify : [void] -> [bool]
|
| Description:
| Simplify the clause database according to the current top-level assigment. Currently, the only
| thing done here is the removal of satisfied clauses, but more things can be put here.
|________________________________________________________________________________________________@*/
inline bool Solver::simplify()
{
assert(decisionLevel() == 0);
if (!ok || propagate() != CRef_Undef)
return ok = false;
if (nAssigns() == simpDB_assigns || (simpDB_props > 0))
return true;
// Remove satisfied clauses:
#define S removeSatisfied
O = 3; S(C);
O = 2; S(T);
O = 0;
removeSatisfied(learnts);
if (remove_satisfied) // Can be turned off.
removeSatisfied(clauses);
checkGarbage();
rebuildOrderHeap();
simpDB_assigns = nAssigns();
simpDB_props = clauses_literals + learnts_literals; // (shouldn't depend on stats really, but it will do for now)
return true;
}
/*_________________________________________________________________________________________________
|
| search : (nof_conflicts : int) (params : const SearchParams&) -> [lbool]
|
| Description:
| Search for a model the specified number of conflicts.
| NOTE! Use negative value for 'nof_conflicts' indicate infinity.
|
| Output:
| 'l_True' if a partial assigment that is consistent with respect to the clauseset is found. If
| all variables are decision variables, this means that the clause set is satisfiable. 'l_False'
| if the clause set is unsatisfiable. 'l_Undef' if the bound on number of conflicts is reached.
|________________________________________________________________________________________________@*/
inline lbool Solver::search(int& n//of_conflicts
)
{
assert(ok);
int backtrack_level;
int conflictC = 0;
vec<Lit> learnt_clause,selectors;
unsigned int nblevels,szWoutSelectors;
bool blocked=false;
starts++;
for (;;){
CRef confl = propagate();
if (confl != CRef_Undef){
// CONFLICT
conflicts++; conflictC++;conflictsRestarts++;
Y--; Z--; n--;
if (Q == 100000 && C.size() < 100) A = 6;
if(0 && conflicts%5000==0 && var_decay<0.95)
var_decay += 0.01;
if (0 && verbosity >= 1 && conflicts%verbEveryConflicts==0){
printf("c | %8d %7d %5d | %7d %8d %8d | %5d %8d %6d %8d | %6.3f %% |\n",
(int)starts,(int)nbstopsrestarts, (int)(conflicts/starts),
(int)dec_vars - (trail_lim.size() == 0 ? trail.size() : trail_lim[0]), nClauses(), (int)clauses_literals,
(int)nbReduceDB, nLearnts(), (int)nbDL2,(int)nbRemovedClauses, progressEstimate()*100);
}
if (decisionLevel() == 0) {
return l_False;
}
/*
trailQueue.push(trail.size());
// BLOCK RESTART (CP 2012 paper)
if( conflictsRestarts>LOWER_BOUND_FOR_BLOCKING_RESTART && lbdQueue.isvalid() && trail.size()>R*trailQueue.getavg()) {
lbdQueue.fastclear();
nbstopsrestarts++;
if(!blocked) {lastblockatrestart=starts;nbstopsrestartssame++;blocked=true;}
}
*/
learnt_clause.clear();
selectors.clear();
analyze(confl, learnt_clause, selectors,backtrack_level,nblevels,szWoutSelectors);
if (G){
H++;
lbdQueue.push(nblevels);
sumLBD += nblevels > 50 ? 50 : nblevels;
}
cancelUntil(backtrack_level);
if (certifiedUNSAT) {
if (vbyte) {
write_char('a');
for (int i = 0; i < learnt_clause.size(); i++)
write_lit(2*(var(learnt_clause[i])+1) + sign(learnt_clause[i]));
write_lit(0);
}
else {
for (int i = 0; i < learnt_clause.size(); i++)
fprintf(certifiedOutput, "%i " , (var(learnt_clause[i]) + 1) *
(-2 * sign(learnt_clause[i]) + 1) );
fprintf(certifiedOutput, "0\n");
}
}
if (learnt_clause.size() == 1){
uncheckedEnqueue(learnt_clause[0]);nbUn++;
}else{
#define EE ca[cr]
CRef cr = ca.alloc(learnt_clause, true);
ca[cr].setLBD(I = nblevels);
ca[cr].setSizeWithoutSelectors(szWoutSelectors);
if(nblevels<=2) nbDL2++; // stats
if(ca[cr].size()==2) nbBin++; // stats
if (I < A){
C.P(cr);
EE.M(3);
}else if (I < 7){
T.P(cr);
EE.M(2);
EE.t = Q;
}else{
learnts.push(cr); B(EE); }
attachClause(cr);
//claBumpActivity(ca[cr]);
uncheckedEnqueue(learnt_clause[0], cr);
}
varDecayActivity();
claDecayActivity();
}else{
// Our dynamic restart, see the SAT09 competition compagnion paper
if ((!G && n <= 0) || (G &&
( lbdQueue.isvalid() && ((lbdQueue.getavg()*(n > 0 ? K : .9)) > (sumLBD / H//conflictsRestarts
))))) {
lbdQueue.fastclear();
progress_estimate = progressEstimate();
int bt = 0;
if(incremental) { // DO NOT BACKTRACK UNTIL 0.. USELESS
bt = (decisionLevel()<assumptions.size()) ? decisionLevel() : assumptions.size();
}
cancelUntil(bt);
return l_Undef; }
// Simplify the set of problem clauses:
if (decisionLevel() == 0 && !simplify()) {
return l_False;
}
if (Y <= 0){
for (I = Y = 0; I < T.size(); I++){
Clause& c = ca[T[I]];
if (c.M() == 2)
if (!locked(c) && c.t + 30000 < Q){
learnts.P(T[I]);
c.M(0);
c.activity() = 0;
B(c);
}else
T[Y++] = T[I];
}
T.shrink(I - Y);
Y = 10000;
}
// Perform clause database reduction !
if(Z <= 0)//conflicts>=curRestart* nbclausesbeforereduce)
{
assert(learnts.size()>0);
curRestart = (conflicts/ nbclausesbeforereduce)+1;
reduceDB();
nbclausesbeforereduce += incReduceDB;
Z = 15000;
}
Lit next = lit_Undef;
while (decisionLevel() < assumptions.size()){
// Perform user provided assumption:
Lit p = assumptions[decisionLevel()];
if (value(p) == l_True){
// Dummy decision level:
newDecisionLevel();
}else if (value(p) == l_False){
analyzeFinal(~p, conflict);
return l_False;
}else{
next = p;
break;
}
}
if (next == lit_Undef){
// New variable decision:
decisions++;
next = pickBranchLit();
if (next == lit_Undef){
// printf("c last restart ## conflicts : %d %d \n",conflictC,decisionLevel());
// Model found:
return l_True;
}
}
// Increase decision level and enqueue 'next'
newDecisionLevel();
uncheckedEnqueue(next);
}
}
}
inline double Solver::progressEstimate() const
{
double progress = 0;
double F = 1.0 / nVars();
for (int i = 0; i <= decisionLevel(); i++){
int beg = i == 0 ? 0 : trail_lim[i - 1];
int end = i == decisionLevel() ? trail.size() : trail_lim[i];
progress += pow(F, i) * (end - beg);
}
return progress / nVars();
}
inline void Solver::printIncrementalStats() {
printf("c---------- Glucose Stats -------------------------\n");
printf("c restarts : %lld\n", starts);
printf("c nb ReduceDB : %lld\n", nbReduceDB);
printf("c nb removed Clauses : %lld\n",nbRemovedClauses);
printf("c nb learnts DL2 : %lld\n", nbDL2);
printf("c nb learnts size 2 : %lld\n", nbBin);
printf("c nb learnts size 1 : %lld\n", nbUn);
printf("c conflicts : %lld \n",conflicts);
printf("c decisions : %lld\n",decisions);
printf("c propagations : %lld\n",propagations);
printf("c SAT Calls : %d in %g seconds\n",nbSatCalls,totalTime4Sat);
printf("c UNSAT Calls : %d in %g seconds\n",nbUnsatCalls,totalTime4Unsat);
printf("c--------------------------------------------------\n");
}
// NOTE: assumptions passed in member-variable 'assumptions'.
inline lbool Solver::solve_()
{
if(incremental && certifiedUNSAT) {
printf("Can not use incremental and certified unsat in the same time\n");
exit(-1);
}
model.clear();
conflict.clear();
if (!ok) return l_False;
double curTime = cpuTime();
solves++;
lbool status = l_Undef;
if(!incremental && verbosity>=1) {
printf("c ========================================[ MAGIC CONSTANTS ]==============================================\n");
printf("c | Constants are supposed to work well together :-) |\n");
printf("c | however, if you find better choices, please let us known... |\n");
printf("c |-------------------------------------------------------------------------------------------------------|\n");
printf("c | | | |\n");
printf("c | - Restarts: | - Reduce Clause DB: | - Minimize Asserting: |\n");
printf("c | * LBD Queue : %6d | * First : %6d | * size < %3d |\n",lbdQueue.maxSize(),nbclausesbeforereduce,lbSizeMinimizingClause);
printf("c | * Trail Queue : %6d | * Inc : %6d | * lbd < %3d |\n",trailQueue.maxSize(),incReduceDB,lbLBDMinimizingClause);
printf("c | * K : %6.2f | * Special : %6d | |\n",K,specialIncReduceDB);
printf("c | * R : %6.2f | * Protected : (lbd)< %2d | |\n",R,lbLBDFrozenClause);
printf("c | | | |\n");
printf("c ==================================[ Search Statistics (every %6d conflicts) ]=========================\n",verbEveryConflicts);
printf("c | |\n");
printf("c | RESTARTS | ORIGINAL | LEARNT | Progress |\n");
printf("c | NB Blocked Avg Cfc | Vars Clauses Literals | Red Learnts LBD2 Removed | |\n");
printf("c =========================================================================================================\n");
}
// Search:
int curr_restarts = 0, a = 91, w;
while (status == l_Undef){
w = !H ? 10000 : a + G * a;
var_decay = G ? .95 : .999;
while (status == l_Undef && w > 0)
status = search(w); // the parameter is useless in glucose, kept to allow modifications
//if (!withinBudget()) break;
curr_restarts++;
if (!(G = !G)) a += a / 10;
}
if (!incremental && verbosity >= 1)
printf("c =========================================================================================================\n");
if (certifiedUNSAT){ // Want certified output
if (status == l_False) {
if (vbyte) {
write_char('a');
write_lit(0);
fwrite(b, 1, e, certifiedOutput), e = 0;
}
else {
fprintf(certifiedOutput, "0\n");
}
}
fclose(certifiedOutput);
}
if (status == l_True){
// Extend & copy model:
model.growTo(nVars());
for (int i = 0; i < nVars(); i++) model[i] = value(i);
}else if (status == l_False && conflict.size() == 0)
ok = false;
cancelUntil(0);
double finalTime = cpuTime();
if(status==l_True) {
nbSatCalls++;
totalTime4Sat +=(finalTime-curTime);
}
if(status==l_False) {
nbUnsatCalls++;
totalTime4Unsat +=(finalTime-curTime);
}
return status;
}
//=================================================================================================
// Writing CNF to DIMACS:
//
// FIXME: this needs to be rewritten completely.
static Var mapVar(Var x, vec<Var>& map, Var& max)
{
if (map.size() <= x || map[x] == -1){
map.growTo(x+1, -1);
map[x] = max++;
}
return map[x];
}
inline void Solver::toDimacs(FILE* f, Clause& c, vec<Var>& map, Var& max)
{
if (satisfied(c)) return;
for (int i = 0; i < c.size(); i++)
if (value(c[i]) != l_False)
fprintf(f, "%s%d ", sign(c[i]) ? "-" : "", mapVar(var(c[i]), map, max)+1);
fprintf(f, "0\n");
}
inline void Solver::toDimacs(const char *file, const vec<Lit>& assumps)
{
FILE* f = fopen(file, "wr");
if (f == NULL)
fprintf(stderr, "could not open file %s\n", file), exit(1);
toDimacs(f, assumps);
fclose(f);
}
inline void Solver::toDimacs(FILE* f, const vec<Lit>& assumps)
{
// Handle case when solver is in contradictory state:
if (!ok){
fprintf(f, "p cnf 1 2\n1 0\n-1 0\n");
return; }
assumps.copyTo(assumptions);
vec<Var> map; Var max = 0;
// Cannot use removeClauses here because it is not safe
// to deallocate them at this point. Could be improved.
int cnt = 0;
for (int i = 0; i < clauses.size(); i++)
if (!satisfied(ca[clauses[i]]))
cnt++;
for (int i = 0; i < clauses.size(); i++)
if (!satisfied(ca[clauses[i]])){
Clause& c = ca[clauses[i]];
for (int j = 0; j < c.size(); j++)
if (value(c[j]) != l_False)
mapVar(var(c[j]), map, max);
}
// Assumptions are added as unit clauses:
cnt += assumptions.size();
fprintf(f, "p cnf %d %d\n", max, cnt);
for (int i = 0; i < assumptions.size(); i++){
assert(value(assumptions[i]) != l_False);
fprintf(f, "%s%d 0\n", sign(assumptions[i]) ? "-" : "", mapVar(var(assumptions[i]), map, max)+1);
}
for (int i = 0; i < clauses.size(); i++)
toDimacs(f, ca[clauses[i]], map, max);
if (verbosity > 0)
printf("Wrote %d clauses with %d variables.\n", cnt, max);
}
//=================================================================================================
// Garbage Collection methods:
inline void Solver::relocAll(ClauseAllocator& to)
{
// All watchers:
//
// for (int i = 0; i < watches.size(); i++)
watches.cleanAll();
watchesBin.cleanAll();
for (int v = 0; v < nVars(); v++)
for (int s = 0; s < 2; s++){
Lit p = mkLit(v, s);
// printf(" >>> RELOCING: %s%d\n", sign(p)?"-":"", var(p)+1);
vec<Watcher>& ws = watches[p];
for (int j = 0; j < ws.size(); j++)
ca.reloc(ws[j].cref, to);
vec<Watcher>& ws2 = watchesBin[p];
for (int j = 0; j < ws2.size(); j++)
ca.reloc(ws2[j].cref, to);
}
// All reasons:
//
for (int i = 0; i < trail.size(); i++){
Var v = var(trail[i]);
if (reason(v) != CRef_Undef && (ca[reason(v)].reloced() || locked(ca[reason(v)])))
ca.reloc(vardata[v].reason, to);
}
// All learnt:
//
#define X(V) for (I = 0; I < V.size();) ca.reloc(V[I++], to);
X(C);
X(T);
for (int i = 0; i < learnts.size(); i++)
ca.reloc(learnts[i], to);
// All original:
//
for (int i = 0; i < clauses.size(); i++)
ca.reloc(clauses[i], to);
}
inline void Solver::garbageCollect()
{
// Initialize the next region to a size corresponding to the estimated utilization degree. This
// is not precise but should avoid some unnecessary reallocations for the new region:
ClauseAllocator to(ca.size() - ca.wasted());
relocAll(to);
if (verbosity >= 2)
printf("| Garbage collection: %12d bytes => %12d bytes |\n",
ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size);
to.moveTo(ca);
}
}
/************************************************************************************[SimpSolver.h]
Copyright (c) 2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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 Ghack_SimpSolver_h
#define Ghack_SimpSolver_h
namespace GHack {
//=================================================================================================
class SimpSolver : public Solver {
public:
// Constructor/Destructor:
//
SimpSolver();
~SimpSolver();
// Problem specification:
//
Var newVar (bool polarity = true, bool dvar = true);
bool addClause (const vec<Lit>& ps);
bool addEmptyClause(); // Add the empty clause to the solver.
bool addClause (Lit p); // Add a unit clause to the solver.
bool addClause (Lit p, Lit q); // Add a binary clause to the solver.
bool addClause (Lit p, Lit q, Lit r); // Add a ternary clause to the solver.
bool addClause_( vec<Lit>& ps);
bool substitute(Var v, Lit x); // Replace all occurences of v with x (may cause a contradiction).
// Variable mode:
//
void setFrozen (Var v, bool b); // If a variable is frozen it will not be eliminated.
bool isEliminated(Var v) const;
// Solving:
//
bool solve (const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
lbool solveLimited(const vec<Lit>& assumps, bool do_simp = true, bool turn_off_simp = false);
bool solve ( bool do_simp = true, bool turn_off_simp = false);
bool solve (Lit p , bool do_simp = true, bool turn_off_simp = false);
bool solve (Lit p, Lit q, bool do_simp = true, bool turn_off_simp = false);
bool solve (Lit p, Lit q, Lit r, bool do_simp = true, bool turn_off_simp = false);
bool eliminate (bool turn_off_elim = false); // Perform variable elimination based simplification.
// Memory managment:
//
virtual void garbageCollect();
// Generate a (possibly simplified) DIMACS file:
//
#if 0
void toDimacs (const char* file, const vec<Lit>& assumps);
void toDimacs (const char* file);
void toDimacs (const char* file, Lit p);
void toDimacs (const char* file, Lit p, Lit q);
void toDimacs (const char* file, Lit p, Lit q, Lit r);
#endif
// Mode of operation:
//
int parsing;
int grow; // Allow a variable elimination step to grow by a number of clauses (default to zero).
int clause_lim; // Variables are not eliminated if it produces a resolvent with a length above this limit.
// -1 means no limit.
int subsumption_lim; // Do not check if subsumption against a clause larger than this. -1 means no limit.
double simp_garbage_frac; // A different limit for when to issue a GC during simplification (Also see 'garbage_frac').
bool use_asymm; // Shrink clauses by asymmetric branching.
bool use_rcheck; // Check if a clause is already implied. Prett costly, and subsumes subsumptions :)
bool use_elim; // Perform variable elimination.
// Statistics:
//
int merges;
int asymm_lits;
int eliminated_vars;
protected:
// Helper structures:
//
struct ElimLt {
const vec<int>& n_occ;
explicit ElimLt(const vec<int>& no) : n_occ(no) {}
// TODO: are 64-bit operations here noticably bad on 32-bit platforms? Could use a saturating
// 32-bit implementation instead then, but this will have to do for now.
uint64_t cost (Var x) const { return (uint64_t)n_occ[toInt(mkLit(x))] * (uint64_t)n_occ[toInt(~mkLit(x))]; }
bool operator()(Var x, Var y) const { return cost(x) < cost(y); }
// TODO: investigate this order alternative more.
// bool operator()(Var x, Var y) const {
// int c_x = cost(x);
// int c_y = cost(y);
// return c_x < c_y || c_x == c_y && x < y; }
};
struct ClauseDeleted {
const ClauseAllocator& ca;
explicit ClauseDeleted(const ClauseAllocator& _ca) : ca(_ca) {}
bool operator()(const CRef& cr) const { return ca[cr].mark() == 1; } };
// Solver state:
//
int elimorder;
bool use_simplification;
vec<uint32_t> elimclauses;
vec<char> touched;
OccLists<Var, vec<CRef>, ClauseDeleted>
occurs;
vec<int> n_occ;
Heap<ElimLt> elim_heap;
Queue<CRef> subsumption_queue;
vec<char> frozen;
vec<char> eliminated;
int bwdsub_assigns;
int n_touched;
// Temporaries:
//
CRef bwdsub_tmpunit;
// Main internal methods:
//
lbool solve_ (bool do_simp = true, bool turn_off_simp = false);
bool asymm (Var v, CRef cr);
bool asymmVar (Var v);
void updateElimHeap (Var v);
void gatherTouchedClauses ();
bool merge (const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause);
bool merge (const Clause& _ps, const Clause& _qs, Var v, int& size);
bool backwardSubsumptionCheck (bool verbose = false);
bool eliminateVar (Var v);
void extendModel ();
void removeClause (CRef cr);
bool strengthenClause (CRef cr, Lit l);
void cleanUpClauses ();
bool implied (const vec<Lit>& c);
void relocAll (ClauseAllocator& to);
};
//=================================================================================================
// Implementation of inline methods:
inline bool SimpSolver::isEliminated (Var v) const { return eliminated[v]; }
inline void SimpSolver::updateElimHeap(Var v) {
assert(use_simplification);
// if (!frozen[v] && !isEliminated(v) && value(v) == l_Undef)
if (elim_heap.inHeap(v) || (!frozen[v] && !isEliminated(v) && value(v) == l_Undef))
elim_heap.update(v); }
inline bool SimpSolver::addClause (const vec<Lit>& ps) { ps.copyTo(add_tmp); return addClause_(add_tmp); }
inline bool SimpSolver::addEmptyClause() { add_tmp.clear(); return addClause_(add_tmp); }
inline bool SimpSolver::addClause (Lit p) { add_tmp.clear(); add_tmp.push(p); return addClause_(add_tmp); }
inline bool SimpSolver::addClause (Lit p, Lit q) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); return addClause_(add_tmp); }
inline bool SimpSolver::addClause (Lit p, Lit q, Lit r) { add_tmp.clear(); add_tmp.push(p); add_tmp.push(q); add_tmp.push(r); return addClause_(add_tmp); }
inline void SimpSolver::setFrozen (Var v, bool b) { frozen[v] = (char)b; if (use_simplification && !b) { updateElimHeap(v); } }
inline bool SimpSolver::solve ( bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (Lit p , bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (Lit p, Lit q, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (Lit p, Lit q, Lit r, bool do_simp, bool turn_off_simp) { budgetOff(); assumptions.clear(); assumptions.push(p); assumptions.push(q); assumptions.push(r); return solve_(do_simp, turn_off_simp) == l_True; }
inline bool SimpSolver::solve (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){
budgetOff(); assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp) == l_True; }
inline lbool SimpSolver::solveLimited (const vec<Lit>& assumps, bool do_simp, bool turn_off_simp){
assumps.copyTo(assumptions); return solve_(do_simp, turn_off_simp); }
//=================================================================================================
}
#endif
/***********************************************************************************[SimpSolver.cc]
Copyright (c) 2006, Niklas Een, Niklas Sorensson
Copyright (c) 2007-2010, Niklas Sorensson
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.
**************************************************************************************************/
namespace GHack {
//=================================================================================================
// Options:
static BoolOption opt_use_asymm ("SIMP", "asymm", "Shrink clauses by asymmetric branching.", false);
static BoolOption opt_use_rcheck ("SIMP", "rcheck", "Check if a clause is already implied. (costly)", false);
static BoolOption opt_use_elim ("SIMP", "elim", "Perform variable elimination.", true);
static IntOption opt_grow ("SIMP", "grow", "Allow a variable elimination step to grow by a number of clauses.", 0);
static IntOption opt_clause_lim ("SIMP", "cl-lim", "Variables are not eliminated if it produces a resolvent with a length above this limit. -1 means no limit", 20, IntRange(-1, INT32_MAX));
static IntOption opt_subsumption_lim ("SIMP", "sub-lim", "Do not check if subsumption against a clause larger than this. -1 means no limit.", 1000, IntRange(-1, INT32_MAX));
static DoubleOption opt_simp_garbage_frac("SIMP", "simp-gc-frac", "The fraction of wasted memory allowed before a garbage collection is triggered during simplification.", 0.5, DoubleRange(0, false, HUGE_VAL, false));
//=================================================================================================
// Constructor/Destructor:
inline SimpSolver::SimpSolver() :
grow (opt_grow)
, clause_lim (opt_clause_lim)
, subsumption_lim (opt_subsumption_lim)
, simp_garbage_frac (opt_simp_garbage_frac)
, use_asymm (opt_use_asymm)
, use_rcheck (opt_use_rcheck)
, use_elim (opt_use_elim)
, merges (0)
, asymm_lits (0)
, eliminated_vars (0)
, elimorder (1)
, use_simplification (true)
, occurs (ClauseDeleted(ca))
, elim_heap (ElimLt(n_occ))
, bwdsub_assigns (0)
, n_touched (0)
{
vec<Lit> dummy(1,lit_Undef);
ca.extra_clause_field = true; // NOTE: must happen before allocating the dummy clause below.
bwdsub_tmpunit = ca.alloc(dummy);
remove_satisfied = false;
}
inline SimpSolver::~SimpSolver()
{
}
inline Var SimpSolver::newVar(bool sign, bool dvar) {
Var v = Solver::newVar(sign, dvar);
frozen .push((char)false);
eliminated.push((char)false);
if (use_simplification){
n_occ .push(0);
n_occ .push(0);
occurs .init(v);
touched .push(0);
elim_heap .insert(v);
}
return v; }
inline lbool SimpSolver::solve_(bool do_simp, bool turn_off_simp)
{
vec<Var> extra_frozen;
lbool result = l_True;
do_simp &= use_simplification;
if (do_simp){
// Assumptions must be temporarily frozen to run variable elimination:
for (int i = 0; i < assumptions.size(); i++){
Var v = var(assumptions[i]);
// If an assumption has been eliminated, remember it.
assert(!isEliminated(v));
if (!frozen[v]){
// Freeze and store.
setFrozen(v, true);
extra_frozen.push(v);
} }
result = lbool(eliminate(turn_off_simp));
}
if (result == l_True)
result = Solver::solve_();
else if (verbosity >= 1)
printf("===============================================================================\n");
if (result == l_True)
extendModel();
if (do_simp)
// Unfreeze the assumptions that were frozen:
for (int i = 0; i < extra_frozen.size(); i++)
setFrozen(extra_frozen[i], false);
return result;
}
inline bool SimpSolver::addClause_(vec<Lit>& ps)
{
#ifndef NDEBUG
for (int i = 0; i < ps.size(); i++)
assert(!isEliminated(var(ps[i])));
#endif
int nclauses = clauses.size();
if (use_rcheck && implied(ps))
return true;
if (!Solver::addClause_(ps))
return false;
if(!parsing && certifiedUNSAT) {
if (vbyte) {
write_char('a');
for (int i = 0; i < ps.size(); i++)
write_lit(2*(var(ps[i])+1) + sign(ps[i]));
write_lit(0);
}
else {
for (int i = 0; i < ps.size(); i++)
fprintf(certifiedOutput, "%i " , (var(ps[i]) + 1) * (-2 * sign(ps[i]) + 1) );
fprintf(certifiedOutput, "0\n");
}
}
if (use_simplification && clauses.size() == nclauses + 1){
CRef cr = clauses.last();
const Clause& c = ca[cr];
// NOTE: the clause is added to the queue immediately and then
// again during 'gatherTouchedClauses()'. If nothing happens
// in between, it will only be checked once. Otherwise, it may
// be checked twice unnecessarily. This is an unfortunate
// consequence of how backward subsumption is used to mimic
// forward subsumption.
subsumption_queue.insert(cr);
for (int i = 0; i < c.size(); i++){
occurs[var(c[i])].push(cr);
n_occ[toInt(c[i])]++;
touched[var(c[i])] = 1;
n_touched++;
if (elim_heap.inHeap(var(c[i])))
elim_heap.increase(var(c[i]));
}
}
return true;
}
inline void SimpSolver::removeClause(CRef cr)
{
const Clause& c = ca[cr];
if (use_simplification)
for (int i = 0; i < c.size(); i++){
n_occ[toInt(c[i])]--;
updateElimHeap(var(c[i]));
occurs.smudge(var(c[i]));
}
Solver::removeClause(cr);
}
inline bool SimpSolver::strengthenClause(CRef cr, Lit l)
{
Clause& c = ca[cr];
assert(decisionLevel() == 0);
assert(use_simplification);
// FIX: this is too inefficient but would be nice to have (properly implemented)
// if (!find(subsumption_queue, &c))
subsumption_queue.insert(cr);
if (certifiedUNSAT) {
if (vbyte) {
write_char('a');
for (int i = 0; i < c.size(); i++)
if (c[i] != l) write_lit(2*(var(c[i])+1) + sign(c[i]));
write_lit(0);
}
else {
for (int i = 0; i < c.size(); i++)
if (c[i] != l) fprintf(certifiedOutput, "%i " , (var(c[i]) + 1) * (-2 * sign(c[i]) + 1) );
fprintf(certifiedOutput, "0\n");
}
}
if (c.size() == 2){
removeClause(cr);
c.strengthen(l);
}else{
if (certifiedUNSAT) {
if (vbyte) {
write_char('d');
for (int i = 0; i < c.size(); i++)
write_lit(2*(var(c[i])+1) + sign(c[i]));
write_lit(0);
}
else {
fprintf(certifiedOutput, "d ");
for (int i = 0; i < c.size(); i++)
fprintf(certifiedOutput, "%i " , (var(c[i]) + 1) * (-2 * sign(c[i]) + 1) );
fprintf(certifiedOutput, "0\n");
}
}
detachClause(cr, true);
c.strengthen(l);
attachClause(cr);
remove(occurs[var(l)], cr);
n_occ[toInt(l)]--;
updateElimHeap(var(l));
}
return c.size() == 1 ? enqueue(c[0]) && propagate() == CRef_Undef : true;
}
// Returns FALSE if clause is always satisfied ('out_clause' should not be used).
inline bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, vec<Lit>& out_clause)
{
merges++;
out_clause.clear();
bool ps_smallest = _ps.size() < _qs.size();
const Clause& ps = ps_smallest ? _qs : _ps;
const Clause& qs = ps_smallest ? _ps : _qs;
for (int i = 0; i < qs.size(); i++){
if (var(qs[i]) != v){
for (int j = 0; j < ps.size(); j++)
if (var(ps[j]) == var(qs[i]))
if (ps[j] == ~qs[i])
return false;
else
goto next;
out_clause.push(qs[i]);
}
next:;
}
for (int i = 0; i < ps.size(); i++)
if (var(ps[i]) != v)
out_clause.push(ps[i]);
return true;
}
// Returns FALSE if clause is always satisfied.
inline bool SimpSolver::merge(const Clause& _ps, const Clause& _qs, Var v, int& size)
{
merges++;
bool ps_smallest = _ps.size() < _qs.size();
const Clause& ps = ps_smallest ? _qs : _ps;
const Clause& qs = ps_smallest ? _ps : _qs;
const Lit* __ps = (const Lit*)ps;
const Lit* __qs = (const Lit*)qs;
size = ps.size()-1;
for (int i = 0; i < qs.size(); i++){
if (var(__qs[i]) != v){
for (int j = 0; j < ps.size(); j++)
if (var(__ps[j]) == var(__qs[i]))
if (__ps[j] == ~__qs[i])
return false;
else
goto next;
size++;
}
next:;
}
return true;
}
inline void SimpSolver::gatherTouchedClauses()
{
if (n_touched == 0) return;
int i,j;
for (i = j = 0; i < subsumption_queue.size(); i++)
if (ca[subsumption_queue[i]].mark() == 0)
ca[subsumption_queue[i]].mark(2);
for (i = 0; i < touched.size(); i++)
if (touched[i]){
const vec<CRef>& cs = occurs.lookup(i);
for (j = 0; j < cs.size(); j++)
if (ca[cs[j]].mark() == 0){
subsumption_queue.insert(cs[j]);
ca[cs[j]].mark(2);
}
touched[i] = 0;
}
for (i = 0; i < subsumption_queue.size(); i++)
if (ca[subsumption_queue[i]].mark() == 2)
ca[subsumption_queue[i]].mark(0);
n_touched = 0;
}
inline bool SimpSolver::implied(const vec<Lit>& c)
{
assert(decisionLevel() == 0);
trail_lim.push(trail.size());
for (int i = 0; i < c.size(); i++)
if (value(c[i]) == l_True){
cancelUntil(0);
return false;
}else if (value(c[i]) != l_False){
assert(value(c[i]) == l_Undef);
uncheckedEnqueue(~c[i]);
}
bool result = propagate() != CRef_Undef;
cancelUntil(0);
return result;
}
// Backward subsumption + backward subsumption resolution
inline bool SimpSolver::backwardSubsumptionCheck(bool verbose)
{
int cnt = 0;
int subsumed = 0;
int deleted_literals = 0;
assert(decisionLevel() == 0);
while (subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()){
// Empty subsumption queue and return immediately on user-interrupt:
if (asynch_interrupt){
subsumption_queue.clear();
bwdsub_assigns = trail.size();
break; }
// Check top-level assignments by creating a dummy clause and placing it in the queue:
if (subsumption_queue.size() == 0 && bwdsub_assigns < trail.size()){
Lit l = trail[bwdsub_assigns++];
ca[bwdsub_tmpunit][0] = l;
ca[bwdsub_tmpunit].calcAbstraction();
subsumption_queue.insert(bwdsub_tmpunit); }
CRef cr = subsumption_queue.peek(); subsumption_queue.pop();
Clause& c = ca[cr];
if (c.mark()) continue;
if (verbose && verbosity >= 2 && cnt++ % 1000 == 0)
printf("subsumption left: %10d (%10d subsumed, %10d deleted literals)\r", subsumption_queue.size(), subsumed, deleted_literals);
assert(c.size() > 1 || value(c[0]) == l_True); // Unit-clauses should have been propagated before this point.
// Find best variable to scan:
Var best = var(c[0]);
for (int i = 1; i < c.size(); i++)
if (occurs[var(c[i])].size() < occurs[best].size())
best = var(c[i]);
// Search all candidates:
vec<CRef>& _cs = occurs.lookup(best);
CRef* cs = (CRef*)_cs;
for (int j = 0; j < _cs.size(); j++)
if (c.mark())
break;
else if (!ca[cs[j]].mark() && cs[j] != cr && (subsumption_lim == -1 || ca[cs[j]].size() < subsumption_lim)){
Lit l = c.subsumes(ca[cs[j]]);
if (l == lit_Undef)
subsumed++, removeClause(cs[j]);
else if (l != lit_Error){
deleted_literals++;
if (!strengthenClause(cs[j], ~l))
return false;
// Did current candidate get deleted from cs? Then check candidate at index j again:
if (var(l) == best)
j--;
}
}
}
return true;
}
inline bool SimpSolver::asymm(Var v, CRef cr)
{
Clause& c = ca[cr];
assert(decisionLevel() == 0);
if (c.mark() || satisfied(c)) return true;
trail_lim.push(trail.size());
Lit l = lit_Undef;
for (int i = 0; i < c.size(); i++)
if (var(c[i]) != v && value(c[i]) != l_False)
uncheckedEnqueue(~c[i]);
else
l = c[i];
if (propagate() != CRef_Undef){
cancelUntil(0);
asymm_lits++;
if (!strengthenClause(cr, l))
return false;
}else
cancelUntil(0);
return true;
}
inline bool SimpSolver::asymmVar(Var v)
{
assert(use_simplification);
const vec<CRef>& cls = occurs.lookup(v);
if (value(v) != l_Undef || cls.size() == 0)
return true;
for (int i = 0; i < cls.size(); i++)
if (!asymm(v, cls[i]))
return false;
return backwardSubsumptionCheck();
}
static void mkElimClause(vec<uint32_t>& elimclauses, Lit x)
{
elimclauses.push(toInt(x));
elimclauses.push(1);
}
static void mkElimClause(vec<uint32_t>& elimclauses, Var v, Clause& c)
{
int first = elimclauses.size();
int v_pos = -1;
// Copy clause to elimclauses-vector. Remember position where the
// variable 'v' occurs:
for (int i = 0; i < c.size(); i++){
elimclauses.push(toInt(c[i]));
if (var(c[i]) == v)
v_pos = i + first;
}
assert(v_pos != -1);
// Swap the first literal with the 'v' literal, so that the literal
// containing 'v' will occur first in the clause:
uint32_t tmp = elimclauses[v_pos];
elimclauses[v_pos] = elimclauses[first];
elimclauses[first] = tmp;
// Store the length of the clause last:
elimclauses.push(c.size());
}
inline bool SimpSolver::eliminateVar(Var v)
{
assert(!frozen[v]);
assert(!isEliminated(v));
assert(value(v) == l_Undef);
// Split the occurrences into positive and negative:
//
const vec<CRef>& cls = occurs.lookup(v);
vec<CRef> pos, neg;
for (int i = 0; i < cls.size(); i++)
(find(ca[cls[i]], mkLit(v)) ? pos : neg).push(cls[i]);
// Check wether the increase in number of clauses stays within the allowed ('grow'). Moreover, no
// clause must exceed the limit on the maximal clause size (if it is set):
//
int cnt = 0;
int clause_size = 0;
for (int i = 0; i < pos.size(); i++)
for (int j = 0; j < neg.size(); j++)
if (merge(ca[pos[i]], ca[neg[j]], v, clause_size) &&
(++cnt > cls.size() + grow || (clause_lim != -1 && clause_size > clause_lim)))
return true;
// Delete and store old clauses:
eliminated[v] = true;
setDecisionVar(v, false);
eliminated_vars++;
if (pos.size() > neg.size()){
for (int i = 0; i < neg.size(); i++)
mkElimClause(elimclauses, v, ca[neg[i]]);
mkElimClause(elimclauses, mkLit(v));
}else{
for (int i = 0; i < pos.size(); i++)
mkElimClause(elimclauses, v, ca[pos[i]]);
mkElimClause(elimclauses, ~mkLit(v));
}
// Produce clauses in cross product:
vec<Lit>& resolvent = add_tmp;
for (int i = 0; i < pos.size(); i++)
for (int j = 0; j < neg.size(); j++)
if (merge(ca[pos[i]], ca[neg[j]], v, resolvent) && !addClause_(resolvent))
return false;
for (int i = 0; i < cls.size(); i++)
removeClause(cls[i]);
// Free occurs list for this variable:
occurs[v].clear(true);
// Free watchers lists for this variable, if possible:
if (watches[ mkLit(v)].size() == 0) watches[ mkLit(v)].clear(true);
if (watches[~mkLit(v)].size() == 0) watches[~mkLit(v)].clear(true);
return backwardSubsumptionCheck();
}
inline bool SimpSolver::substitute(Var v, Lit x)
{
assert(!frozen[v]);
assert(!isEliminated(v));
assert(value(v) == l_Undef);
if (!ok) return false;
eliminated[v] = true;
setDecisionVar(v, false);
const vec<CRef>& cls = occurs.lookup(v);
vec<Lit>& subst_clause = add_tmp;
for (int i = 0; i < cls.size(); i++){
Clause& c = ca[cls[i]];
subst_clause.clear();
for (int j = 0; j < c.size(); j++){
Lit p = c[j];
subst_clause.push(var(p) == v ? x ^ sign(p) : p);
}
if (!addClause_(subst_clause))
return ok = false;
removeClause(cls[i]);
}
return true;
}
inline void SimpSolver::extendModel()
{
int i, j;
Lit x;
for (i = elimclauses.size()-1; i > 0; i -= j){
for (j = elimclauses[i--]; j > 1; j--, i--)
if (modelValue(toLit(elimclauses[i])) != l_False)
goto next;
x = toLit(elimclauses[i]);
model[var(x)] = lbool(!sign(x));
next:;
}
}
inline bool SimpSolver::eliminate(bool turn_off_elim)
{
if (!simplify())
return false;
else if (!use_simplification)
return true;
// Main simplification loop:
//
int toPerform = 1; clauses.size()<=4800000;
if(!toPerform) {
printf("c Too many clauses... No preprocessing\n");
}
while (toPerform && (n_touched > 0 || bwdsub_assigns < trail.size() || elim_heap.size() > 0)){
gatherTouchedClauses();
// printf(" ## (time = %6.2f s) BWD-SUB: queue = %d, trail = %d\n", cpuTime(), subsumption_queue.size(), trail.size() - bwdsub_assigns);
if ((subsumption_queue.size() > 0 || bwdsub_assigns < trail.size()) &&
!backwardSubsumptionCheck(true)){
ok = false; goto cleanup; }
// Empty elim_heap and return immediately on user-interrupt:
if (asynch_interrupt){
assert(bwdsub_assigns == trail.size());
assert(subsumption_queue.size() == 0);
assert(n_touched == 0);
elim_heap.clear();
goto cleanup; }
// printf(" ## (time = %6.2f s) ELIM: vars = %d\n", cpuTime(), elim_heap.size());
for (int cnt = 0; !elim_heap.empty(); cnt++){
Var elim = elim_heap.removeMin();
if (asynch_interrupt) break;
if (isEliminated(elim) || value(elim) != l_Undef) continue;
if (verbosity >= 2 && cnt % 100 == 0)
printf("elimination left: %10d\r", elim_heap.size());
if (use_asymm){
// Temporarily freeze variable. Otherwise, it would immediately end up on the queue again:
bool was_frozen = frozen[elim];
frozen[elim] = true;
if (!asymmVar(elim)){
ok = false; goto cleanup; }
frozen[elim] = was_frozen; }
// At this point, the variable may have been set by assymetric branching, so check it
// again. Also, don't eliminate frozen variables:
if (use_elim && value(elim) == l_Undef && !frozen[elim] && !eliminateVar(elim)){
ok = false; goto cleanup; }
checkGarbage(simp_garbage_frac);
}
assert(subsumption_queue.size() == 0);
}
cleanup:
// If no more simplification is needed, free all simplification-related data structures:
if (turn_off_elim){
touched .clear(true);
occurs .clear(true);
n_occ .clear(true);
elim_heap.clear(true);
subsumption_queue.clear(true);
use_simplification = false;
remove_satisfied = true;
ca.extra_clause_field = false;
// Force full cleanup (this is safe and desirable since it only happens once):
rebuildOrderHeap();
garbageCollect();
}else{
// Cheaper cleanup:
cleanUpClauses(); // TODO: can we make 'cleanUpClauses()' not be linear in the problem size somehow?
checkGarbage();
}
if (verbosity >= 1 && elimclauses.size() > 0)
printf("c | Eliminated clauses: %10.2f Mb |\n",
double(elimclauses.size() * sizeof(uint32_t)) / (1024*1024));
return ok;
}
inline void SimpSolver::cleanUpClauses()
{
occurs.cleanAll();
int i,j;
for (i = j = 0; i < clauses.size(); i++)
if (ca[clauses[i]].mark() == 0)
clauses[j++] = clauses[i];
clauses.shrink(i - j);
}
//=================================================================================================
// Garbage Collection methods:
inline void SimpSolver::relocAll(ClauseAllocator& to)
{
if (!use_simplification) return;
// All occurs lists:
//
for (int i = 0; i < nVars(); i++){
vec<CRef>& cs = occurs[i];
for (int j = 0; j < cs.size(); j++)
ca.reloc(cs[j], to);
}
// Subsumption queue:
//
for (int i = 0; i < subsumption_queue.size(); i++)
ca.reloc(subsumption_queue[i], to);
// Temporary clause:
//
ca.reloc(bwdsub_tmpunit, to);
}
inline void SimpSolver::garbageCollect()
{
// Initialize the next region to a size corresponding to the estimated utilization degree. This
// is not precise but should avoid some unnecessary reallocations for the new region:
ClauseAllocator to(ca.size() - ca.wasted());
cleanUpClauses();
to.extra_clause_field = ca.extra_clause_field; // NOTE: this is important to keep (or lose) the extra fields.
relocAll(to);
Solver::relocAll(to);
if (verbosity >= 2)
printf("| Garbage collection: %12d bytes => %12d bytes |\n",
ca.size()*ClauseAllocator::Unit_Size, to.size()*ClauseAllocator::Unit_Size);
to.moveTo(ca);
}
}
#undef write_char
#undef var_Undef
#undef DYNAMICNBLEVEL
#undef CONSTANTREMOVECLAUSE
#undef UPDATEVARACTIVITY
#undef RATIOREMOVECLAUSES
#undef LOWER_BOUND_FOR_BLOCKING_RESTART
#undef M
#undef Q
#undef P
#undef B
#undef S
#undef EE
#undef X
| 183,030 | 60,666 |
#include <bits/stdc++.h>
using namespace std;
#define int long long int
void solve() {
string s;
cin >> s;
int n = s.length();
int rep = 0;
int cnt = 1;
for (int i = 1; i < n ; i++) {
if (s[i] == s[i - 1]) {
cnt++;
}
else {
rep = max(rep, cnt);
cnt = 1;
}
}
cout << max(rep, cnt) << "\n";
}
signed main() {
solve();
return 0;
} | 383 | 173 |
#ifndef FALCON_LITERAL_UTILITY_HPP
#define FALCON_LITERAL_UTILITY_HPP
#include <falcon/literal/detail/literal_support.hpp>
#include <type_traits>
#include <limits>
#include <falcon/type_traits/eval_if.hpp>
#include <falcon/type_traits/use.hpp>
namespace falcon {
namespace literal {
template<typename _CharT, _CharT c>
struct is_digit
: std::integral_constant<bool, (_CharT('0') <= c && c <= _CharT('9'))>
{};
template<std::size_t position>
struct check_false
: std::false_type
{ static const std::size_t last_position = position; };
template<std::size_t position>
struct check_true
: std::true_type
{ static const std::size_t last_position = position; };
template<std::size_t position, typename _CharT, _CharT... chars>
struct __is_integral_base_10;
template<std::size_t position, typename _CharT, _CharT c, _CharT... chars>
struct __is_integral_base_10<position, _CharT, c, chars...>
: if_c<
is_digit<_CharT, c>,
__is_integral_base_10<position + 1, _CharT, chars...>,
check_false<position>
>::type
{ static const std::size_t last_position = position; };
template<std::size_t position, typename _CharT>
struct __is_integral_base_10<position, _CharT>
: check_true<position>
{};
template<typename _CharT, _CharT... chars>
struct is_integral
: __is_integral_base_10<0, _CharT, chars...>
{};
template<typename _CharT>
struct is_integral<_CharT>
: check_false<0>
{};
template<std::size_t position, typename _CharT, _CharT... chars>
struct __is_floating_point_base_10;
template<std::size_t position, typename _CharT, _CharT c, _CharT... chars>
struct __is_floating_point_base_10<position, _CharT, c, chars...>
: eval_if<
c == _CharT('.'),
use<__is_integral_base_10<position + 1, _CharT, chars...>>,
if_c<
is_digit<_CharT, c>,
__is_floating_point_base_10<position + 1, _CharT, chars...>,
check_false<position>
>
>::type
{};
template<std::size_t position, typename _CharT>
struct __is_floating_point_base_10<position, _CharT>
: check_true<position>
{};
template<typename _CharT, _CharT... chars>
struct is_floating_point
: __is_floating_point_base_10<0, _CharT, chars...>
{};
template<typename _CharT>
struct is_floating_point<_CharT>
: check_false<0>
{};
template<typename _CharT, _CharT c>
struct is_floating_point<_CharT, c>
: if_<(c == _CharT('.')), check_false<1>, check_true<1>>::type
{};
template<typename _To, typename _CharT, _CharT... chars>
struct __check_convert_integral
{
static_assert(is_integral<_CharT, chars...>::value, "value is not integral");
};
template<typename _To, unsigned long long ullvalue>
struct __to_value
{
static_assert((ullvalue <= static_cast<unsigned long long>(std::numeric_limits<_To>::max())), "overflow in implicit constant conversion");
static const _To __value = static_cast<_To>(ullvalue);
};
template<typename _To, _To value, typename _CharT, _CharT c>
struct __to_value_base_10
: __to_value<_To, value * 10 + (static_cast<_To>(c) - _To('0'))>
{};
template<typename _To, _To value, typename _CharT, _CharT... chars>
struct __convert_to_integral_base_10;
template<typename _To, _To value, typename _CharT, _CharT c, _CharT... chars>
struct __convert_to_integral_base_10<_To, value, _CharT, c, chars...>
: __convert_to_integral_base_10<
_To,
__to_value_base_10<_To, value, _CharT, c>::__value,
_CharT,
chars...
>
{ static_assert(is_digit<_CharT, c>(), "value is not integral"); };
template<typename _To, _To value, typename _CharT>
struct __convert_to_integral_base_10<_To, value, _CharT>
: std::integral_constant<_To, value>
{};
template<typename _To, typename _CharT, _CharT... chars>
struct __convert_to_integral
: __convert_to_integral_base_10<_To, _To(0), _CharT, chars...>
{ static_assert(sizeof...(chars), "value is empty"); };
template<bool, bool, typename _To, typename _CharT, _CharT... chars>
struct __convert_to;
template<typename _To, typename _CharT, _CharT... chars>
struct __convert_to<true, false, _To, _CharT, chars...>
: __convert_to_integral<_To, _CharT, chars...>
{};
// template<typename _To, typename _CharT, _CharT... chars>
// struct __convert_to<false, true, _To, _CharT, chars...>
// : __convert_to_floating_point<_To, _CharT, chars...>
// {};
template<typename _To, typename _CharT, _CharT... chars>
struct basic_convert_to
: __convert_to<
std::is_integral<_To>::value,
std::is_floating_point<_To>::value,
_To, _CharT, chars...>
{};
template<typename _To, char... chars>
using convert_to = basic_convert_to<_To, char, chars...>;
template<char... chars>
using to_short = convert_to<short, chars...>;
template<char... chars>
using to_int = convert_to<int, chars...>;
template<char... chars>
using to_long = convert_to<long, chars...>;
template<char... chars>
using to_long_long = convert_to<long long, chars...>;
template<char... chars>
using to_ushort = convert_to<unsigned short, chars...>;
template<char... chars>
using to_uint = convert_to<unsigned int, chars...>;
template<char... chars>
using to_ulong = convert_to<unsigned long, chars...>;
template<char... chars>
using to_ulong_long = convert_to<unsigned long long, chars...>;
}
}
#endif
| 5,069 | 1,939 |
/******************************************************************************/
/* Mednafen - Multi-system Emulator */
/******************************************************************************/
/* Joystick_XInput.cpp:
** Copyright (C) 2012-2018 Mednafen Team
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation, Inc.,
** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// For future reference: XInputGetState(Ex) is reported to have a very high overhead
// when the controller is disconnected.
#include "main.h"
#include "input.h"
#include "Joystick.h"
#include "Joystick_XInput.h"
#include <windows.h>
#include <windowsx.h>
#include <xinput.h>
struct XInputFuncPointers
{
void WINAPI (*p_XInputEnable)(BOOL) = nullptr;
DWORD WINAPI (*p_XInputSetState)(DWORD, XINPUT_VIBRATION*) = nullptr;
DWORD WINAPI (*p_XInputGetState)(DWORD, XINPUT_STATE*) = nullptr; // Pointer to XInputGetState or XInputGetStateEx(if available).
DWORD WINAPI (*p_XInputGetCapabilities)(DWORD, DWORD, XINPUT_CAPABILITIES*) = nullptr;
};
class Joystick_XInput : public Joystick
{
public:
Joystick_XInput(unsigned index, const XINPUT_CAPABILITIES &caps_in, const XInputFuncPointers* xfps_in);
~Joystick_XInput();
virtual void SetRumble(uint8 weak_intensity, uint8 strong_intensity);
virtual bool IsAxisButton(unsigned axis);
void UpdateInternal(void);
private:
const unsigned joy_index;
const XINPUT_CAPABILITIES caps;
const XInputFuncPointers *xfps;
};
Joystick_XInput::Joystick_XInput(unsigned index, const XINPUT_CAPABILITIES &caps_in, const XInputFuncPointers* xfps_in) : joy_index(index), caps(caps_in), xfps(xfps_in)
{
num_buttons = sizeof(((XINPUT_GAMEPAD*)0)->wButtons) * 8;
num_axes = 6;
num_rel_axes = 0;
button_state.resize(num_buttons);
axis_state.resize(num_axes);
id_09x = (caps.Type << 24) | (caps.SubType << 16); // Don't include the XInput index in the id, it'll just cause problems, especially when multiple different subtypes of controllers are connected. | (index << 8);
// Leave first 8 bytes as 0 to reduce probability of collisions with DirectInput GUIDs?
MDFN_en64msb(&id[0], 0);
id[8] = caps.Type;
id[9] = caps.SubType;
MDFN_en16msb(&id[10], caps.Flags);
MDFN_en16msb(&id[12], caps.Gamepad.wButtons);
MDFN_en16msb(&id[14], 0);
const char* name_cs = "XInput Unknown Controller";
if(caps.Type == XINPUT_DEVTYPE_GAMEPAD)
{
switch(caps.SubType)
{
default: break;
case XINPUT_DEVSUBTYPE_GAMEPAD: name_cs = "XInput Gamepad"; break;
case XINPUT_DEVSUBTYPE_WHEEL: name_cs = "XInput Wheel"; break;
case XINPUT_DEVSUBTYPE_ARCADE_STICK: name_cs = "XInput Arcade Stick"; break;
#ifdef XINPUT_DEVSUBTYPE_FLIGHT_STICK
case XINPUT_DEVSUBTYPE_FLIGHT_STICK: name_cs = "XInput Flight Stick"; break;
#endif
case XINPUT_DEVSUBTYPE_DANCE_PAD: name_cs = "XInput Dance Pad"; break;
#ifdef XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE
case XINPUT_DEVSUBTYPE_GUITAR_ALTERNATE:
#endif
#ifdef XINPUT_DEVSUBTYPE_GUITAR_BASS
case XINPUT_DEVSUBTYPE_GUITAR_BASS:
#endif
case XINPUT_DEVSUBTYPE_GUITAR: name_cs = "XInput Guitar"; break;
case XINPUT_DEVSUBTYPE_DRUM_KIT: name_cs = "XInput Drum Kit"; break;
#ifdef XINPUT_DEVSUBTYPE_ARCADE_PAD
case XINPUT_DEVSUBTYPE_ARCADE_PAD: name_cs = "XInput Arcade Pad"; break;
#endif
}
}
name = name_cs;
}
Joystick_XInput::~Joystick_XInput()
{
}
bool Joystick_XInput::IsAxisButton(unsigned axis)
{
if(axis >= 4)
return(true);
return(false);
}
void Joystick_XInput::UpdateInternal(void)
{
XINPUT_STATE joy_state;
memset(&joy_state, 0, sizeof(XINPUT_STATE));
xfps->p_XInputGetState(joy_index, &joy_state);
for(unsigned b = 0; b < num_buttons; b++)
button_state[b] = (joy_state.Gamepad.wButtons >> b) & 1;
axis_state[0] = std::max<int>(-32767, joy_state.Gamepad.sThumbLX);
axis_state[1] = std::max<int>(-32767, joy_state.Gamepad.sThumbLY);
axis_state[2] = std::max<int>(-32767, joy_state.Gamepad.sThumbRX);
axis_state[3] = std::max<int>(-32767, joy_state.Gamepad.sThumbRY);
axis_state[4] = (((unsigned)joy_state.Gamepad.bLeftTrigger * 32767) + 127) / 255;
axis_state[5] = (((unsigned)joy_state.Gamepad.bRightTrigger * 32767) + 127) / 255;
}
void Joystick_XInput::SetRumble(uint8 weak_intensity, uint8 strong_intensity)
{
XINPUT_VIBRATION vib;
memset(&vib, 0, sizeof(XINPUT_VIBRATION));
vib.wLeftMotorSpeed = (((unsigned int)strong_intensity * 65535) + 127) / 255;
vib.wRightMotorSpeed = (((unsigned int)weak_intensity * 65535) + 127) / 255;
xfps->p_XInputSetState(joy_index, &vib);
}
class JoystickDriver_XInput : public JoystickDriver
{
public:
JoystickDriver_XInput();
virtual ~JoystickDriver_XInput();
virtual unsigned NumJoysticks(); // Cached internally on JoystickDriver instantiation.
virtual Joystick *GetJoystick(unsigned index);
virtual void UpdateJoysticks(void);
private:
Joystick_XInput *joys[XUSER_MAX_COUNT];
unsigned joy_count = 0;
HMODULE dll_handle = nullptr;
XInputFuncPointers xfps;
};
template<typename T>
bool GetXIPA(HMODULE dll_handle, T& pf, const char *name)
{
pf = (T)GetProcAddress(dll_handle, name);
return(pf != NULL);
}
JoystickDriver_XInput::JoystickDriver_XInput()
{
if((dll_handle = LoadLibrary("xinput1_3.dll")) == NULL)
{
if((dll_handle = LoadLibrary("xinput1_4.dll")) == NULL)
{
if((dll_handle = LoadLibrary("xinput9_1_0.dll")) == NULL)
{
return;
}
}
}
// 9.1.0 supposedly lacks XInputEnable()
xfps.p_XInputEnable = NULL;
GetXIPA(dll_handle, xfps.p_XInputEnable, "XInputEnable");
if(!GetXIPA(dll_handle, xfps.p_XInputSetState, "XInputSetState") ||
(!GetXIPA(dll_handle, xfps.p_XInputGetState, (const char *)100/*"XInputGetStateEx"*/) && !GetXIPA(dll_handle, xfps.p_XInputGetState, "XInputGetState")) ||
!GetXIPA(dll_handle, xfps.p_XInputGetCapabilities, "XInputGetCapabilities"))
{
FreeLibrary(dll_handle);
return;
}
if(xfps.p_XInputEnable)
xfps.p_XInputEnable(TRUE);
for(unsigned i = 0; i < XUSER_MAX_COUNT; i++)
{
joys[i] = NULL;
try
{
XINPUT_CAPABILITIES caps;
if(xfps.p_XInputGetCapabilities(i, XINPUT_FLAG_GAMEPAD, &caps) == ERROR_SUCCESS)
{
joys[joy_count] = new Joystick_XInput(i, caps, &xfps);
joy_count++; // joys[joy_count++] would not be exception-safe.
}
}
catch(std::exception &e)
{
MDFND_OutputNotice(MDFN_NOTICE_ERROR, e.what());
}
}
}
JoystickDriver_XInput::~JoystickDriver_XInput()
{
if(xfps.p_XInputEnable)
xfps.p_XInputEnable(FALSE);
for(unsigned i = 0; i < joy_count; i++)
{
if(joys[i])
{
delete joys[i];
joys[i] = NULL;
}
}
joy_count = 0;
if(dll_handle != NULL)
{
FreeLibrary(dll_handle);
dll_handle = NULL;
}
}
unsigned JoystickDriver_XInput::NumJoysticks(void)
{
return joy_count;
}
Joystick *JoystickDriver_XInput::GetJoystick(unsigned index)
{
return joys[index];
}
void JoystickDriver_XInput::UpdateJoysticks(void)
{
for(unsigned i = 0; i < joy_count; i++)
joys[i]->UpdateInternal();
}
JoystickDriver *JoystickDriver_XInput_New(void)
{
JoystickDriver_XInput* jdxi = new JoystickDriver_XInput();
if(!jdxi->NumJoysticks())
{
delete jdxi;
jdxi = NULL;
}
return(jdxi);
}
| 7,783 | 3,120 |
// SPDX-FileCopyrightText: 2014 Erik Garrison
//
// SPDX-License-Identifier: MIT
#include "aligner.hpp"
#include "hash_map.hpp"
//#define debug_print_score_matrices
using namespace vg;
using namespace std;
using namespace vg::io;
static const double quality_scale_factor = 10.0 / log(10.0);
static const double exp_overflow_limit = log(std::numeric_limits<double>::max());
GSSWAligner::~GSSWAligner(void) {
free(nt_table);
free(score_matrix);
}
GSSWAligner::GSSWAligner(const int8_t* _score_matrix,
int8_t _gap_open,
int8_t _gap_extension,
int8_t _full_length_bonus,
double _gc_content) : deletion_aligner(_gap_open, _gap_extension) {
log_base = recover_log_base(_score_matrix, _gc_content, 1e-12);
// TODO: now that everything is in terms of score matrices, having match/mismatch is a bit
// misleading, but a fair amount of code depends on them
match = _score_matrix[0];
mismatch = -_score_matrix[1];
gap_open = _gap_open;
gap_extension = _gap_extension;
full_length_bonus = _full_length_bonus;
// table to translate chars to their integer value
nt_table = gssw_create_nt_table();
}
gssw_graph* GSSWAligner::create_gssw_graph(const HandleGraph& g) const {
vector<handle_t> topological_order = handlealgs::lazier_topological_order(&g);
gssw_graph* graph = gssw_graph_create(g.get_node_count());
unordered_map<int64_t, gssw_node*> nodes;
// compute the topological order
for (const handle_t& handle : topological_order) {
auto cleaned_seq = nonATGCNtoN(g.get_sequence(handle));
gssw_node* node = gssw_node_create(nullptr, // TODO: the ID should be enough, don't need Node* too
g.get_id(handle),
cleaned_seq.c_str(),
nt_table,
score_matrix); // TODO: this arg isn't used, could edit
// in gssw
nodes[node->id] = node;
gssw_graph_add_node(graph, node);
}
g.for_each_edge([&](const edge_t& edge) {
if(!g.get_is_reverse(edge.first) && !g.get_is_reverse(edge.second)) {
// This is a normal end to start edge.
gssw_nodes_add_edge(nodes[g.get_id(edge.first)], nodes[g.get_id(edge.second)]);
}
else if (g.get_is_reverse(edge.first) && g.get_is_reverse(edge.second)) {
// This is a start to end edge, but isn't reversing and can be converted to a normal end to start edge.
// Flip the start and end
gssw_nodes_add_edge(nodes[g.get_id(edge.second)], nodes[g.get_id(edge.first)]);
}
else {
// TODO: It's a reversing edge, which gssw doesn't support yet. What
// we should really do is do a topological sort to break cycles, and
// then flip everything at the lower-rank end of this edge around,
// so we don't have to deal with its reversing-ness. But for now we
// just die so we don't get nonsense into gssw.
#pragma omp critical
{
// We need the critical section so we don't throw uncaught
// exceptions in multiple threads at once, leading to C++ trying
// to run termiante in parallel. This doesn't make it safe, just
// slightly safer.
cerr << "Can't gssw over reversing edge " << g.get_id(edge.first) << (g.get_is_reverse(edge.first) ? "-" : "+") << " -> " << g.get_id(edge.second) << (g.get_is_reverse(edge.second) ? "-" : "+") << endl;
// TODO: there's no safe way to kill the program without a way
// to signal the master to do it, via a shared variable in the
// clause that made us parallel.
}
exit(1);
}
return true;
});
return graph;
}
unordered_set<vg::id_t> GSSWAligner::identify_pinning_points(const HandleGraph& graph) const {
unordered_set<vg::id_t> return_val;
// start at the sink nodes
vector<handle_t> sinks = handlealgs::tail_nodes(&graph);
// walk backwards to find non-empty nodes if necessary
for (const handle_t& handle : sinks) {
vector<handle_t> stack(1, handle);
while (!stack.empty()) {
handle_t here = stack.back();
stack.pop_back();
if (graph.get_length(here) > 0) {
return_val.insert(graph.get_id(here));
}
else {
graph.follow_edges(here, true, [&](const handle_t& prev) {
// TODO: technically this won't filter out all redundant walks, but it should
// handle all cases we're practically interested in and it doesn't require a
// second set object
if (!return_val.count(graph.get_id(prev))) {
stack.push_back(prev);
}
});
}
}
}
return return_val;
}
void GSSWAligner::gssw_mapping_to_alignment(gssw_graph* graph,
gssw_graph_mapping* gm,
Alignment& alignment,
bool pinned,
bool pin_left) const {
alignment.clear_path();
alignment.set_score(gm->score);
alignment.set_query_position(0);
Path* path = alignment.mutable_path();
//alignment.set_cigar(graph_cigar(gm));
gssw_graph_cigar* gc = &gm->cigar;
gssw_node_cigar* ncs = gc->elements;
//cerr << "gm->position " << gm->position << endl;
string& to_seq = *alignment.mutable_sequence();
//cerr << "-------------" << endl;
#ifdef debug_print_score_matrices
gssw_graph_print_score_matrices(graph, to_seq.c_str(), to_seq.size(), stderr);
#endif
int to_pos = 0;
int from_pos = gm->position;
for (int i = 0; i < gc->length; ++i) {
// check that the current alignment has a non-zero length
gssw_cigar* c = ncs[i].cigar;
int l = c->length;
if (l == 0) continue;
gssw_cigar_element* e = c->elements;
gssw_node* node = ncs[i].node;
Mapping* mapping = path->add_mapping();
if (i > 0) {
// reset for each node after the first
from_pos = 0;
}
mapping->mutable_position()->set_node_id(node->id);
mapping->mutable_position()->set_offset(from_pos);
mapping->set_rank(path->mapping_size());
//cerr << node->id << ":" << endl;
for (int j=0; j < l; ++j, ++e) {
int32_t length = e->length;
//cerr << e->length << e->type << endl;
Edit* edit;
switch (e->type) {
case 'M':
case 'X':
case 'N': {
//cerr << "j = " << j << ", type = " << e->type << endl;
// do the sequences match?
// emit a stream of "SNPs" and matches
int h = from_pos;
int last_start = from_pos;
int k = to_pos;
for ( ; h < from_pos + length; ++h, ++k) {
//cerr << h << ":" << k << " " << node->seq[h] << " " << to_seq[k] << endl;
if (node->seq[h] != to_seq[k]) {
// emit the last "match" region
if (h - last_start > 0) {
edit = mapping->add_edit();
edit->set_from_length(h-last_start);
edit->set_to_length(h-last_start);
}
// set up the SNP
edit = mapping->add_edit();
edit->set_from_length(1);
edit->set_to_length(1);
edit->set_sequence(to_seq.substr(k,1));
last_start = h+1;
}
}
// handles the match at the end or the case of no SNP
if (h - last_start > 0) {
edit = mapping->add_edit();
edit->set_from_length(h-last_start);
edit->set_to_length(h-last_start);
}
to_pos += length;
from_pos += length;
} break;
case 'D':
edit = mapping->add_edit();
edit->set_from_length(length);
edit->set_to_length(0);
from_pos += length;
break;
case 'I':
edit = mapping->add_edit();
edit->set_from_length(0);
edit->set_to_length(length);
edit->set_sequence(to_seq.substr(to_pos, length));
to_pos += length;
break;
case 'S':
// note that soft clips and insertions are semantically equivalent
// and can only be differentiated by their position in the read
// with soft clips coming at the start or end
edit = mapping->add_edit();
edit->set_from_length(0);
edit->set_to_length(length);
edit->set_sequence(to_seq.substr(to_pos, length));
to_pos += length;
break;
default:
cerr << "error:[Aligner::gssw_mapping_to_alignment] "
<< "unsupported cigar op type " << e->type << endl;
exit(1);
break;
}
}
}
// compute and set identity
alignment.set_identity(identity(alignment.path()));
}
void GSSWAligner::unreverse_graph(gssw_graph* graph) const {
// this is only for getting correct reference-relative edits, so we can get away with only
// reversing the sequences and not paying attention to the edges
for (size_t i = 0; i < graph->size; i++) {
gssw_node* node = graph->nodes[i];
for (int j = 0, stop = node->len / 2; j < stop; j++) {
std::swap(node->seq[j], node->seq[node->len - j - 1]);
}
}
}
void GSSWAligner::unreverse_graph_mapping(gssw_graph_mapping* gm) const {
gssw_graph_cigar* graph_cigar = &(gm->cigar);
gssw_node_cigar* node_cigars = graph_cigar->elements;
// reverse the order of the node cigars
int32_t num_switching_nodes = graph_cigar->length / 2;
int32_t last_idx = graph_cigar->length - 1;
for (int32_t i = 0; i < num_switching_nodes; i++) {
std::swap(node_cigars[i], node_cigars[last_idx - i]);
}
// reverse the actual cigar string for each node cigar
for (int32_t i = 0; i < graph_cigar->length; i++) {
gssw_cigar* node_cigar = node_cigars[i].cigar;
gssw_cigar_element* elements = node_cigar->elements;
int32_t num_switching_elements = node_cigar->length / 2;
last_idx = node_cigar->length - 1;
for (int32_t j = 0; j < num_switching_elements; j++) {
std::swap(elements[j], elements[last_idx - j]);
}
}
// compute the position in the first node
if (graph_cigar->length > 0) {
gssw_cigar_element* first_node_elements = node_cigars[0].cigar->elements;
int32_t num_first_node_elements = node_cigars[0].cigar->length;
uint32_t num_ref_aligned = 0; // the number of characters on the node sequence that are aligned
for (int32_t i = 0; i < num_first_node_elements; i++) {
switch (first_node_elements[i].type) {
case 'M':
case 'X':
case 'N':
case 'D':
num_ref_aligned += first_node_elements[i].length;
break;
}
}
gm->position = node_cigars[0].node->len - num_ref_aligned - (graph_cigar->length == 1 ? gm->position : 0);
}
else {
gm->position = 0;
}
}
string GSSWAligner::graph_cigar(gssw_graph_mapping* gm) const {
stringstream s;
gssw_graph_cigar* gc = &gm->cigar;
gssw_node_cigar* nc = gc->elements;
int to_pos = 0;
int from_pos = gm->position;
//string& to_seq = *alignment.mutable_sequence();
s << from_pos << '@';
for (int i = 0; i < gc->length; ++i, ++nc) {
if (i > 0) from_pos = 0; // reset for each node after the first
Node* from_node = (Node*) nc->node->data;
s << from_node->id() << ':';
gssw_cigar* c = nc->cigar;
int l = c->length;
gssw_cigar_element* e = c->elements;
for (int j=0; j < l; ++j, ++e) {
s << e->length << e->type;
}
if (i + 1 < gc->length) {
s << ",";
}
}
return s.str();
}
double GSSWAligner::recover_log_base(const int8_t* score_matrix, double gc_content, double tol) const {
// convert gc content into base-wise frequencies
double* nt_freqs = (double*) malloc(sizeof(double) * 4);
nt_freqs[0] = 0.5 * (1 - gc_content);
nt_freqs[1] = 0.5 * gc_content;
nt_freqs[2] = 0.5 * gc_content;
nt_freqs[3] = 0.5 * (1 - gc_content);
if (!verify_valid_log_odds_score_matrix(score_matrix, nt_freqs)) {
cerr << "error:[Aligner] Score matrix is invalid. Must have a negative expected score against random sequence." << endl;
exit(1);
}
// searching for a positive value (because it's a base of a logarithm)
double lower_bound;
double upper_bound;
// arbitrary starting point greater than zero
double lambda = 1.0;
// search for a window containing lambda where total probability is 1
double partition = alignment_score_partition_function(lambda, score_matrix, nt_freqs);
if (partition < 1.0) {
lower_bound = lambda;
while (partition <= 1.0) {
lower_bound = lambda;
lambda *= 2.0;
partition = alignment_score_partition_function(lambda, score_matrix, nt_freqs);
}
upper_bound = lambda;
}
else {
upper_bound = lambda;
while (partition >= 1.0) {
upper_bound = lambda;
lambda /= 2.0;
partition = alignment_score_partition_function(lambda, score_matrix, nt_freqs);
}
lower_bound = lambda;
}
// bisect to find a log base where total probability is 1
while (upper_bound / lower_bound - 1.0 > tol) {
lambda = 0.5 * (lower_bound + upper_bound);
if (alignment_score_partition_function(lambda, score_matrix, nt_freqs) < 1.0) {
lower_bound = lambda;
}
else {
upper_bound = lambda;
}
}
free(nt_freqs);
return 0.5 * (lower_bound + upper_bound);
}
bool GSSWAligner::verify_valid_log_odds_score_matrix(const int8_t* score_matrix, const double* nt_freqs) const {
bool contains_positive_score = false;
for (int i = 0; i < 16; i++) {
if (score_matrix[i] > 0) {
contains_positive_score = 1;
break;
}
}
if (!contains_positive_score) {
return false;
}
double expected_score = 0.0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
expected_score += nt_freqs[i] * nt_freqs[j] * score_matrix[i * 4 + j];
}
}
return expected_score < 0.0;
}
double GSSWAligner::alignment_score_partition_function(double lambda, const int8_t* score_matrix,
const double* nt_freqs) const {
double partition = 0.0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
partition += nt_freqs[i] * nt_freqs[j] * exp(lambda * score_matrix[i * 4 + j]);
}
}
if (isnan(partition)) {
cerr << "error:[Aligner] overflow error in log-odds base recovery subroutine." << endl;
exit(1);
}
return partition;
}
int32_t GSSWAligner::score_gap(size_t gap_length) const {
return gap_length ? -gap_open - (gap_length - 1) * gap_extension : 0;
}
double GSSWAligner::maximum_mapping_quality_exact(const vector<double>& scaled_scores, size_t* max_idx_out,
const vector<double>* multiplicities) {
// work in log transformed values to avoid risk of overflow
double log_sum_exp = numeric_limits<double>::lowest();
double max_score = numeric_limits<double>::lowest();
// go in reverse order because this has fewer numerical problems when the scores are sorted (as usual)
for (int64_t i = scaled_scores.size() - 1; i >= 0; i--) {
// get the value of one copy of the score and check if it's the max
double score = scaled_scores.at(i);
if (score >= max_score) {
// Since we are going in reverse order, make sure to break ties in favor of the earlier item.
*max_idx_out = i;
max_score = score;
}
// add all copies of the score
if (multiplicities && multiplicities->at(i) > 1.0) {
score += log(multiplicities->at(i));
}
// accumulate the sum of all score
log_sum_exp = add_log(log_sum_exp, score);
}
// if necessary, assume a null alignment of 0.0 for comparison since this is local
if (scaled_scores.size() == 1) {
if (multiplicities && multiplicities->at(0) <= 1.0) {
log_sum_exp = add_log(log_sum_exp, 0.0);
}
else if (!multiplicities) {
log_sum_exp = add_log(log_sum_exp, 0.0);
}
}
double direct_mapq = -quality_scale_factor * subtract_log(0.0, max_score - log_sum_exp);
return std::isinf(direct_mapq) ? (double) numeric_limits<int32_t>::max() : direct_mapq;
}
// TODO: this algorithm has numerical problems that would be difficult to solve without increasing the
// time complexity: adding the probability of the maximum likelihood tends to erase the contribution
// of the other terms so that when you subtract them off you get scores of 0 or infinity
//vector<double> Aligner::all_mapping_qualities_exact(vector<double>& scaled_scores) {
//
// double max_score = *max_element(scaled_scores.begin(), scaled_scores.end());
// size_t size = scaled_scores.size();
//
// vector<double> mapping_qualities(size);
//
// if (max_score * size < exp_overflow_limit) {
// // no risk of double overflow, sum exp directly (half as many transcendental function evals)
// vector<double> exp_scaled_scores(size);
// for (size_t i = 0; i < size; i++) {
// exp_scaled_scores[i] = exp(scaled_scores[i]);
// }
// double denom = std::accumulate(exp_scaled_scores.begin(), exp_scaled_scores.end(), 0.0);
// for (size_t i = 0; i < size; i++) {
// mapping_qualities[i] = -10.0 * log10((denom - exp_scaled_scores[i]) / denom);
// }
// }
// else {
// // work in log transformed valued to avoid risk of overflow
// double log_sum_exp = scaled_scores[0];
// for (size_t i = 1; i < size; i++) {
// log_sum_exp = add_log(log_sum_exp, scaled_scores[i]);
// }
// for (size_t i = 0; i < size; i++) {
// mapping_qualities[i] = -10.0 * log10(1.0 - exp(scaled_scores[i] - log_sum_exp));
// }
// }
// return mapping_qualities;
//}
double GSSWAligner::maximum_mapping_quality_approx(const vector<double>& scaled_scores, size_t* max_idx_out,
const vector<double>* multiplicities) {
assert(!scaled_scores.empty());
// determine the maximum score and the count of the next highest score
double max_score = scaled_scores.at(0);
size_t max_idx = 0;
// we start with the possibility of a null score of 0.0
double next_score = 0.0;
double next_count = 1.0;
if (multiplicities) {
if (multiplicities->at(0) > 1.0) {
// there are extra copies of this one, so we'll init with those
next_score = max_score;
next_count = multiplicities->at(0) - 1.0;
}
}
for (int32_t i = 1; i < scaled_scores.size(); ++i) {
double score = scaled_scores.at(i);
if (score > max_score) {
if (multiplicities && multiplicities->at(i) > 1.0) {
// there are extra counts of the new highest score due to multiplicity
next_score = score;
next_count = multiplicities->at(i) - 1.0;
}
else if (next_score == max_score) {
// the next highest was the same score as the old max, so we can
// add its count back in
next_count += 1.0;
}
else {
// the old max score is now the second highest
next_score = max_score;
next_count = multiplicities ? multiplicities->at(max_idx) : 1.0;
}
max_score = score;
max_idx = i;
}
else if (score > next_score) {
// the new score is the second highest
next_score = score;
next_count = multiplicities ? multiplicities->at(i) : 1.0;
}
else if (score == next_score) {
// the new score ties the second highest, so we combine their counts
next_count += multiplicities ? multiplicities->at(i) : 1.0;
}
}
// record the index of the highest score
*max_idx_out = max_idx;
return max(0.0, quality_scale_factor * (max_score - next_score - (next_count > 1.0 ? log(next_count) : 0.0)));
}
double GSSWAligner::group_mapping_quality_exact(const vector<double>& scaled_scores, const vector<size_t>& group,
const vector<double>* multiplicities) const {
// work in log transformed values to avoid risk of overflow
double total_log_sum_exp = numeric_limits<double>::lowest();
double non_group_log_sum_exp = numeric_limits<double>::lowest();
// go in reverse order because this has fewer numerical problems when the scores are sorted (as usual)
int64_t group_idx = group.size() - 1;
for (int64_t i = scaled_scores.size() - 1; i >= 0; i--) {
// the score of one alignment
double score = scaled_scores.at(i);
// the score all the multiples of this score combined
double multiple_score = score;
if (multiplicities && multiplicities->at(i) > 1.0) {
multiple_score += log(multiplicities->at(i));
}
total_log_sum_exp = add_log(total_log_sum_exp, multiple_score);
if (group_idx >= 0 && i == group[group_idx]) {
// this is the next index in the group
group_idx--;
if (multiplicities && multiplicities->at(i) > 1.0) {
// there's some remaining multiples of this score that don't get added into the group
non_group_log_sum_exp = add_log(non_group_log_sum_exp,
score + log(multiplicities->at(i) - 1.0));
}
}
else {
// this index is not part of the group
non_group_log_sum_exp = add_log(non_group_log_sum_exp, multiple_score);
}
}
if (scaled_scores.size() == 1) {
if (multiplicities && multiplicities->at(0) <= 1.0) {
// assume a null alignment of 0.0 for comparison since this is local
non_group_log_sum_exp = add_log(non_group_log_sum_exp, 0.0);
total_log_sum_exp = add_log(total_log_sum_exp, 0.0);
}
else if (!multiplicities) {
//TODO: repetitive, do I need to be this careful to not deref a null?
// assume a null alignment of 0.0 for comparison since this is local
non_group_log_sum_exp = add_log(non_group_log_sum_exp, 0.0);
total_log_sum_exp = add_log(total_log_sum_exp, 0.0);
}
}
double direct_mapq = quality_scale_factor * (total_log_sum_exp - non_group_log_sum_exp);
return (std::isinf(direct_mapq) || direct_mapq > numeric_limits<int32_t>::max()) ?
(double) numeric_limits<int32_t>::max() : direct_mapq;
}
void GSSWAligner::compute_mapping_quality(vector<Alignment>& alignments,
int max_mapping_quality,
bool fast_approximation,
double cluster_mq,
bool use_cluster_mq,
int overlap_count,
double mq_estimate,
double maybe_mq_threshold,
double identity_weight) const {
assert(log_base > 0.0);
if (alignments.empty()) {
return;
}
vector<double> scaled_scores(alignments.size());
for (size_t i = 0; i < alignments.size(); i++) {
scaled_scores[i] = log_base * alignments[i].score();
}
double mapping_quality;
size_t max_idx;
if (!fast_approximation) {
mapping_quality = maximum_mapping_quality_exact(scaled_scores, &max_idx);
}
else {
mapping_quality = maximum_mapping_quality_approx(scaled_scores, &max_idx);
}
if (use_cluster_mq) {
mapping_quality = prob_to_phred(sqrt(phred_to_prob(cluster_mq + mapping_quality)));
}
if (overlap_count) {
mapping_quality -= quality_scale_factor * log(overlap_count);
}
auto& max_aln = alignments.at(max_idx);
int l = max(alignment_to_length(max_aln), alignment_from_length(max_aln));
double identity = 1. - (double)(l * match - max_aln.score()) / (match + mismatch) / l;
mapping_quality /= 2;
mapping_quality *= pow(identity, identity_weight);
if (mq_estimate < maybe_mq_threshold && mq_estimate < mapping_quality) {
mapping_quality = prob_to_phred(sqrt(phred_to_prob(mq_estimate + mapping_quality)));
}
if (mapping_quality > max_mapping_quality) {
mapping_quality = max_mapping_quality;
}
if (alignments[max_idx].score() == 0) {
mapping_quality = 0;
}
alignments[max_idx].set_mapping_quality(max(0, (int32_t) round(mapping_quality)));
for (int i = 1; i < alignments.size(); ++i) {
alignments[0].add_secondary_score(alignments[i].score());
}
}
int32_t GSSWAligner::compute_mapping_quality(const vector<double>& scores, bool fast_approximation,
const vector<double>* multiplicities) const {
vector<double> scaled_scores(scores.size());
for (size_t i = 0; i < scores.size(); i++) {
scaled_scores[i] = log_base * scores[i];
}
size_t idx;
return (int32_t) (fast_approximation ? maximum_mapping_quality_approx(scaled_scores, &idx, multiplicities)
: maximum_mapping_quality_exact(scaled_scores, &idx, multiplicities));
}
int32_t GSSWAligner::compute_group_mapping_quality(const vector<double>& scores, const vector<size_t>& group,
const vector<double>* multiplicities) const {
// make a non-const local version in case we need to sort it
vector<size_t> non_const_group;
const vector<size_t>* grp_ptr = &group;
// ensure that group is in sorted order as following function expects
if (!is_sorted(group.begin(), group.end())) {
non_const_group = group;
sort(non_const_group.begin(), non_const_group.end());
grp_ptr = &non_const_group;
}
vector<double> scaled_scores(scores.size(), 0.0);
for (size_t i = 0; i < scores.size(); i++) {
scaled_scores[i] = log_base * scores[i];
}
return group_mapping_quality_exact(scaled_scores, *grp_ptr, multiplicities);
}
void GSSWAligner::compute_paired_mapping_quality(pair<vector<Alignment>, vector<Alignment>>& alignment_pairs,
const vector<double>& frag_weights,
int max_mapping_quality1,
int max_mapping_quality2,
bool fast_approximation,
double cluster_mq,
bool use_cluster_mq,
int overlap_count1,
int overlap_count2,
double mq_estimate1,
double mq_estimate2,
double maybe_mq_threshold,
double identity_weight) const {
assert(log_base > 0.0);
size_t size = min(alignment_pairs.first.size(),
alignment_pairs.second.size());
if (size == 0) {
return;
}
vector<double> scaled_scores(size);
for (size_t i = 0; i < size; i++) {
auto& aln1 = alignment_pairs.first[i];
auto& aln2 = alignment_pairs.second[i];
scaled_scores[i] = log_base * (aln1.score() + aln2.score());
// + frag_weights[i]);
// ^^^ we could also incorporate the fragment weights, but this does not seem to help performance in the current form
}
size_t max_idx;
double mapping_quality;
if (!fast_approximation) {
mapping_quality = maximum_mapping_quality_exact(scaled_scores, &max_idx);
}
else {
mapping_quality = maximum_mapping_quality_approx(scaled_scores, &max_idx);
}
if (use_cluster_mq) {
mapping_quality = prob_to_phred(sqrt(phred_to_prob(cluster_mq + mapping_quality)));
}
double mapping_quality1 = mapping_quality;
double mapping_quality2 = mapping_quality;
if (overlap_count1) {
mapping_quality1 -= quality_scale_factor * log(overlap_count1);
}
if (overlap_count2) {
mapping_quality2 -= quality_scale_factor * log(overlap_count2);
}
auto& max_aln1 = alignment_pairs.first.at(max_idx);
int len1 = max(alignment_to_length(max_aln1), alignment_from_length(max_aln1));
double identity1 = 1. - (double)(len1 * match - max_aln1.score()) / (match + mismatch) / len1;
auto& max_aln2 = alignment_pairs.second.at(max_idx);
int len2 = max(alignment_to_length(max_aln2), alignment_from_length(max_aln2));
double identity2 = 1. - (double)(len2 * match - max_aln2.score()) / (match + mismatch) / len2;
mapping_quality1 /= 2;
mapping_quality2 /= 2;
mapping_quality1 *= pow(identity1, identity_weight);
mapping_quality2 *= pow(identity2, identity_weight);
double mq_estimate = min(mq_estimate1, mq_estimate2);
if (mq_estimate < maybe_mq_threshold && mq_estimate < mapping_quality1) {
mapping_quality1 = prob_to_phred(sqrt(phred_to_prob(mq_estimate + mapping_quality1)));
}
if (mq_estimate < maybe_mq_threshold && mq_estimate < mapping_quality2) {
mapping_quality2 = prob_to_phred(sqrt(phred_to_prob(mq_estimate + mapping_quality2)));
}
if (mapping_quality1 > max_mapping_quality1) {
mapping_quality1 = max_mapping_quality1;
}
if (mapping_quality2 > max_mapping_quality2) {
mapping_quality2 = max_mapping_quality2;
}
if (alignment_pairs.first[max_idx].score() == 0) {
mapping_quality1 = 0;
}
if (alignment_pairs.second[max_idx].score() == 0) {
mapping_quality2 = 0;
}
mapping_quality = max(0, (int32_t)round(min(mapping_quality1, mapping_quality2)));
alignment_pairs.first[max_idx].set_mapping_quality(mapping_quality);
alignment_pairs.second[max_idx].set_mapping_quality(mapping_quality);
for (int i = 1; i < alignment_pairs.first.size(); ++i) {
alignment_pairs.first[0].add_secondary_score(alignment_pairs.first[i].score());
}
for (int i = 1; i < alignment_pairs.second.size(); ++i) {
alignment_pairs.second[0].add_secondary_score(alignment_pairs.second[i].score());
}
}
double GSSWAligner::mapping_quality_score_diff(double mapping_quality) const {
return mapping_quality / (quality_scale_factor * log_base);
}
double GSSWAligner::estimate_next_best_score(int length, double min_diffs) const {
return ((length - min_diffs) * match - min_diffs * mismatch);
}
double GSSWAligner::max_possible_mapping_quality(int length) const {
double max_score = log_base * length * match;
vector<double> v = { max_score };
size_t max_idx;
return maximum_mapping_quality_approx(v, &max_idx);
}
double GSSWAligner::estimate_max_possible_mapping_quality(int length, double min_diffs, double next_min_diffs) const {
double max_score = log_base * ((length - min_diffs) * match - min_diffs * mismatch);
double next_max_score = log_base * ((length - next_min_diffs) * match - next_min_diffs * mismatch);
vector<double> v = { max_score, next_max_score };
size_t max_idx;
return maximum_mapping_quality_approx(v, &max_idx);
}
double GSSWAligner::score_to_unnormalized_likelihood_ln(double score) const {
// Log base needs to be set, or this can't work.
assert(log_base != 0);
// Likelihood is proportional to e^(lambda * score), so ln is just the exponent.
return log_base * score;
}
size_t GSSWAligner::longest_detectable_gap(const Alignment& alignment, const string::const_iterator& read_pos) const {
return longest_detectable_gap(alignment.sequence().size(), read_pos - alignment.sequence().begin());
}
size_t GSSWAligner::longest_detectable_gap(size_t read_length, size_t read_pos) const {
// algebraic solution for when score is > 0 assuming perfect match other than gap
assert(read_length >= read_pos);
int64_t overhang_length = min(read_pos, read_length - read_pos);
int64_t numer = match * overhang_length + full_length_bonus;
int64_t gap_length = (numer - gap_open) / gap_extension + 1;
return gap_length >= 0 && overhang_length > 0 ? gap_length : 0;
}
size_t GSSWAligner::longest_detectable_gap(const Alignment& alignment) const {
// longest detectable gap across entire read is in the middle
return longest_detectable_gap(alignment.sequence().size(), alignment.sequence().size() / 2);
}
size_t GSSWAligner::longest_detectable_gap(size_t read_length) const {
return longest_detectable_gap(read_length, read_length / 2);
}
int32_t GSSWAligner::score_discontiguous_alignment(const Alignment& aln, const function<size_t(pos_t, pos_t, size_t)>& estimate_distance,
bool strip_bonuses) const {
int score = 0;
int read_offset = 0;
auto& path = aln.path();
// We keep track of whether the last edit was a deletion for coalescing
// adjacent deletions across node boundaries
bool last_was_deletion = false;
for (int i = 0; i < path.mapping_size(); ++i) {
// For each mapping
auto& mapping = path.mapping(i);
for (int j = 0; j < mapping.edit_size(); ++j) {
// For each edit in the mapping
auto& edit = mapping.edit(j);
// Score the edit according to its type
if (edit_is_match(edit)) {
score += score_exact_match(aln, read_offset, edit.to_length());
last_was_deletion = false;
} else if (edit_is_sub(edit)) {
score += score_mismatch(aln.sequence().begin() + read_offset,
aln.sequence().begin() + read_offset + edit.to_length(),
aln.quality().begin() + read_offset);
last_was_deletion = false;
} else if (edit_is_deletion(edit)) {
if (last_was_deletion) {
// No need to charge a gap open
score -= edit.from_length() * gap_extension;
} else {
// We need a gap open
score -= edit.from_length() ? gap_open + (edit.from_length() - 1) * gap_extension : 0;
}
if (edit.from_length()) {
// We already charged a gap open
last_was_deletion = true;
}
// If there's a 0-length deletion, leave the last_was_deletion flag unchanged.
} else if (edit_is_insertion(edit) && !((i == 0 && j == 0) ||
(i == path.mapping_size()-1 && j == mapping.edit_size()-1))) {
// todo how do we score this qual adjusted?
score -= edit.to_length() ? gap_open + (edit.to_length() - 1) * gap_extension : 0;
last_was_deletion = false;
// No need to track if the last edit was an insertion because
// insertions will be all together in a single edit at a point.
} else {
// Edit has no score effect. Probably a softclip.
last_was_deletion = false;
}
read_offset += edit.to_length();
}
// score any intervening gaps in mappings using approximate distances
if (i+1 < path.mapping_size()) {
// what is the distance between the last position of this mapping
// and the first of the next
Position last_pos = mapping.position();
last_pos.set_offset(last_pos.offset() + mapping_from_length(mapping));
Position next_pos = path.mapping(i+1).position();
// Estimate the distance
int dist = estimate_distance(make_pos_t(last_pos), make_pos_t(next_pos), aln.sequence().size());
if (dist > 0) {
// If it's nonzero, score it as a deletion gap
score -= gap_open + (dist - 1) * gap_extension;
}
}
}
if (!strip_bonuses) {
// We should report any bonuses used in the DP in the final score
if (!softclip_start(aln)) {
score += score_full_length_bonus(true, aln);
}
if (!softclip_end(aln)) {
score += score_full_length_bonus(false, aln);
}
}
return score;
}
int32_t GSSWAligner::score_contiguous_alignment(const Alignment& aln, bool strip_bonuses) const {
return score_discontiguous_alignment(aln, [](pos_t, pos_t, size_t){return (size_t) 0;}, strip_bonuses);
}
int32_t GSSWAligner::remove_bonuses(const Alignment& aln, bool pinned, bool pin_left) const {
int32_t score = aln.score();
if (softclip_start(aln) == 0 && !(pinned && pin_left)) {
// No softclip at the start, and a left end bonus was applied.
score -= score_full_length_bonus(true, aln);
}
if (softclip_end(aln) == 0 && !(pinned && !pin_left)) {
// No softclip at the end, and a right end bonus was applied.
score -= score_full_length_bonus(false, aln);
}
return score;
}
Aligner::Aligner(const int8_t* _score_matrix,
int8_t _gap_open,
int8_t _gap_extension,
int8_t _full_length_bonus,
double _gc_content)
: GSSWAligner(_score_matrix, _gap_open, _gap_extension, _full_length_bonus, _gc_content)
{
// add in the 5th row and column of 0s for N matches like GSSW wants
score_matrix = (int8_t*) malloc(sizeof(int8_t) * 25);
for (size_t i = 0, j = 0; i < 25; ++i) {
if (i % 5 == 4 || i / 5 == 4) {
score_matrix[i] = 0;
}
else {
score_matrix[i] = _score_matrix[j];
++j;
}
}
// make an XdropAligner for each thread
int num_threads = get_thread_count();
xdrops.reserve(num_threads);
for (size_t i = 0; i < num_threads; ++i) {
xdrops.emplace_back(_score_matrix, _gap_open, _gap_extension);
}
}
void Aligner::align_internal(Alignment& alignment, vector<Alignment>* multi_alignments, const HandleGraph& g,
bool pinned, bool pin_left,int32_t max_alt_alns, bool traceback_aln) const {
// bench_start(bench);
// check input integrity
if (pin_left && !pinned) {
cerr << "error:[Aligner] cannot choose pinned end in non-pinned alignment" << endl;
exit(EXIT_FAILURE);
}
if (multi_alignments && !pinned) {
cerr << "error:[Aligner] multiple traceback is not implemented in local alignment, only pinned and global" << endl;
exit(EXIT_FAILURE);
}
if (!multi_alignments && max_alt_alns != 1) {
cerr << "error:[Aligner] cannot specify maximum number of alignments in single alignment" << endl;
exit(EXIT_FAILURE);
}
if (max_alt_alns <= 0) {
cerr << "error:[Aligner] cannot do less than 1 alignment" << endl;
exit(EXIT_FAILURE);
}
// alignment pinning algorithm is based on pinning in bottom right corner, if pinning in top
// left we need to reverse all the sequences first and translate the alignment back later
// make a place to reverse the graph and sequence if necessary
ReverseGraph reversed_graph(&g, false);
string reversed_sequence;
// choose forward or reversed objects
const HandleGraph* oriented_graph = &g;
const string* align_sequence = &alignment.sequence();
if (pin_left) {
// choose the reversed graph
oriented_graph = &reversed_graph;
// make and assign the reversed sequence
reversed_sequence.resize(align_sequence->size());
reverse_copy(align_sequence->begin(), align_sequence->end(), reversed_sequence.begin());
align_sequence = &reversed_sequence;
}
// to save compute, we won't make these unless we're doing pinning
unordered_set<vg::id_t> pinning_ids;
NullMaskingGraph* null_masked_graph = nullptr;
const HandleGraph* align_graph = oriented_graph;
if (pinned) {
pinning_ids = identify_pinning_points(*oriented_graph);
null_masked_graph = new NullMaskingGraph(oriented_graph);
align_graph = null_masked_graph;
}
// convert into gssw graph
gssw_graph* graph = create_gssw_graph(*align_graph);
// perform dynamic programming
gssw_graph_fill_pinned(graph, align_sequence->c_str(),
nt_table, score_matrix,
gap_open, gap_extension, full_length_bonus,
pinned ? 0 : full_length_bonus, 15, 2, traceback_aln);
// traceback either from pinned position or optimal local alignment
if (traceback_aln) {
if (pinned) {
// we can only run gssw's DP on non-empty graphs, but we may have masked the entire graph
// if it consists of only empty nodes, so don't both with the DP in that case
gssw_graph_mapping** gms = nullptr;
if (align_graph->get_node_count() > 0) {
gssw_node** pinning_nodes = (gssw_node**) malloc(pinning_ids.size() * sizeof(gssw_node*));
size_t j = 0;
for (size_t i = 0; i < graph->size; i++) {
gssw_node* node = graph->nodes[i];
if (pinning_ids.count(node->id)) {
pinning_nodes[j] = node;
j++;
}
}
// trace back pinned alignment
gms = gssw_graph_trace_back_pinned_multi (graph,
max_alt_alns,
true,
align_sequence->c_str(),
align_sequence->size(),
pinning_nodes,
pinning_ids.size(),
nt_table,
score_matrix,
gap_open,
gap_extension,
full_length_bonus,
0);
free(pinning_nodes);
}
// did we both 1) do DP (i.e. the graph is non-empty), and 2) find a traceback with positive score?
if (gms ? gms[0]->score > 0 : false) {
if (pin_left) {
// translate nodes and mappings into original sequence so that the cigars come out right
unreverse_graph(graph);
for (int32_t i = 0; i < max_alt_alns; i++) {
unreverse_graph_mapping(gms[i]);
}
}
// have a mapping, can just convert normally
gssw_mapping_to_alignment(graph, gms[0], alignment, pinned, pin_left);
if (multi_alignments) {
// determine how many non-null alignments were returned
int32_t num_non_null = max_alt_alns;
for (int32_t i = 1; i < max_alt_alns; i++) {
if (gms[i]->score <= 0) {
num_non_null = i;
break;
}
}
// reserve to avoid illegal access errors that occur when the vector reallocates
multi_alignments->reserve(num_non_null);
// copy the primary alignment
multi_alignments->emplace_back(alignment);
// convert the alternate alignments and store them at the back of the vector (this will not
// execute if we are doing single alignment)
for (int32_t i = 1; i < num_non_null; i++) {
// make new alignment object
multi_alignments->emplace_back();
Alignment& next_alignment = multi_alignments->back();
// copy over sequence information from the primary alignment
next_alignment.set_sequence(alignment.sequence());
next_alignment.set_quality(alignment.quality());
// get path of the alternate alignment
gssw_mapping_to_alignment(graph, gms[i], next_alignment, pinned, pin_left);
}
}
}
else if (g.get_node_count() > 0) {
// we didn't get any alignments either because the graph was empty and we couldn't run
// gssw DP or because they had score 0 and gssw didn't want to do traceback. however,
// we can infer the location of softclips based on the pinning nodes, so we'll just make
// those manually
// find the sink nodes of the oriented graph, which may be empty
auto pinning_points = handlealgs::tail_nodes(oriented_graph);
// impose a consistent ordering for machine independent behavior
sort(pinning_points.begin(), pinning_points.end(), [&](const handle_t& h1, const handle_t& h2) {
return oriented_graph->get_id(h1) < oriented_graph->get_id(h2);
});
for (size_t i = 0; i < max_alt_alns && i < pinning_points.size(); i++) {
// make a record in the multi alignments if we're using them
if (multi_alignments) {
multi_alignments->emplace_back();
}
// choose an alignment object to construct the path in
Alignment& softclip_alignment = i == 0 ? alignment : multi_alignments->back();
handle_t& pinning_point = pinning_points[i];
Mapping* mapping = alignment.mutable_path()->add_mapping();
mapping->set_rank(1);
// locate at the beginning or end of the node
Position* position = mapping->mutable_position();
position->set_node_id(oriented_graph->get_id(pinning_point));
position->set_offset(pin_left ? 0 : oriented_graph->get_length(pinning_point));
// soft clip
Edit* edit = mapping->add_edit();
edit->set_to_length(alignment.sequence().length());
edit->set_sequence(alignment.sequence());
// we want to also have the first alignment in the multi-alignment vector
if (i == 0 && multi_alignments) {
multi_alignments->back() = alignment;
}
}
}
if (gms) {
for (int32_t i = 0; i < max_alt_alns; i++) {
gssw_graph_mapping_destroy(gms[i]);
}
free(gms);
}
}
else {
// trace back local alignment
gssw_graph_mapping* gm = gssw_graph_trace_back (graph,
align_sequence->c_str(),
align_sequence->size(),
nt_table,
score_matrix,
gap_open,
gap_extension,
full_length_bonus,
full_length_bonus);
gssw_mapping_to_alignment(graph, gm, alignment, pinned, pin_left);
gssw_graph_mapping_destroy(gm);
}
} else {
// get the alignment position and score
alignment.set_score(graph->max_node->alignment->score1);
Mapping* m = alignment.mutable_path()->add_mapping();
Position* p = m->mutable_position();
p->set_node_id(graph->max_node->id);
p->set_offset(graph->max_node->alignment->ref_end1); // mark end position; for de-duplication
}
// this might be null if we're not doing pinned alignment, but delete doesn't care
delete null_masked_graph;
gssw_graph_destroy(graph);
// bench_end(bench);
}
void Aligner::align(Alignment& alignment, const HandleGraph& g, bool traceback_aln) const {
align_internal(alignment, nullptr, g, false, false, 1, traceback_aln);
}
void Aligner::align(Alignment& alignment, const HandleGraph& g,
const std::vector<handle_t>& topological_order) const {
// Create a gssw_graph and a mapping from handles to nodes.
gssw_graph* graph = gssw_graph_create(topological_order.size());
hash_map<handle_t, gssw_node*> nodes;
nodes.reserve(topological_order.size());
// Create the nodes. Use offsets in the topological order as node ids.
for (size_t i = 0; i < topological_order.size(); i++) {
handle_t handle = topological_order[i];
auto cleaned_seq = nonATGCNtoN(g.get_sequence(handle));
gssw_node* node = gssw_node_create(nullptr,
i,
cleaned_seq.c_str(),
nt_table,
score_matrix);
nodes[handle] = node;
gssw_graph_add_node(graph, node);
}
// Create the edges.
for (const handle_t& from : topological_order) {
gssw_node* from_node = nodes[from];
g.follow_edges(from, false, [&](const handle_t& to) {
auto iter = nodes.find(to);
if (iter != nodes.end()) {
gssw_nodes_add_edge(from_node, iter->second);
}
});
}
// Align the read to the subgraph.
gssw_graph_fill_pinned(graph, alignment.sequence().c_str(),
nt_table, score_matrix,
gap_open, gap_extension, full_length_bonus, full_length_bonus,
15, 2, true);
gssw_graph_mapping* gm = gssw_graph_trace_back(graph,
alignment.sequence().c_str(), alignment.sequence().length(),
nt_table, score_matrix,
gap_open, gap_extension, full_length_bonus, full_length_bonus);
// Convert the mapping to Alignment.
this->gssw_mapping_to_alignment(graph, gm, alignment, false, false);
Path& path = *(alignment.mutable_path());
for (size_t i = 0; i < path.mapping_size(); i++) {
Position& pos = *(path.mutable_mapping(i)->mutable_position());
handle_t handle = topological_order[pos.node_id()];
pos.set_node_id(g.get_id(handle));
pos.set_is_reverse(g.get_is_reverse(handle));
}
// Destroy the temporary objects.
gssw_graph_mapping_destroy(gm);
gssw_graph_destroy(graph);
}
void Aligner::align_pinned(Alignment& alignment, const HandleGraph& g, bool pin_left, bool xdrop,
uint16_t xdrop_max_gap_length) const {
if (xdrop) {
// XdropAligner manages its own stack, so it can never be threadsafe without be recreated
// for every alignment, which meshes poorly with its stack implementation. We achieve
// thread-safety by having one per thread, which makes this method const-ish.
XdropAligner& xdrop = const_cast<XdropAligner&>(xdrops[omp_get_thread_num()]);
// dozeu declines to produce an alignment when the gap is set to 0
xdrop_max_gap_length = max<uint16_t>(xdrop_max_gap_length, 1);
// wrap the graph so that empty pinning points are handled correctly
DozeuPinningOverlay overlay(&g, !pin_left);
if (overlay.get_node_count() == 0 && g.get_node_count() > 0) {
// the only nodes in the graph are empty nodes for pinning, which got masked.
// we can still infer a pinned alignment based purely on the pinning point but
// dozeu won't handle this correctly
g.for_each_handle([&](const handle_t& handle) {
bool can_pin = g.follow_edges(handle, pin_left, [&](const handle_t& next) {return false;});
if (can_pin) {
// manually make the softclip
Mapping* mapping = alignment.mutable_path()->add_mapping();
Position* pos = mapping->mutable_position();
pos->set_node_id(g.get_id(handle));
pos->set_is_reverse(false);
pos->set_offset(pin_left ? 0 : g.get_length(handle));
mapping->set_rank(1);
Edit* edit = mapping->add_edit();
edit->set_from_length(0);
edit->set_to_length(alignment.sequence().size());
edit->set_sequence(alignment.sequence());
alignment.set_score(0);
return false;
}
return true;
});
}
else {
// do the alignment
xdrop.align_pinned(alignment, overlay, pin_left, full_length_bonus, xdrop_max_gap_length);
if (overlay.performed_duplications()) {
// the overlay is not a strict subset of the underlying graph, so we may
// need to translate some node IDs
translate_oriented_node_ids(*alignment.mutable_path(), [&](id_t node_id) {
handle_t under = overlay.get_underlying_handle(overlay.get_handle(node_id));
return make_pair(g.get_id(under), g.get_is_reverse(under));
});
}
}
}
else {
align_internal(alignment, nullptr, g, true, pin_left, 1, true);
}
}
void Aligner::align_pinned_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g,
bool pin_left, int32_t max_alt_alns) const {
if (alt_alignments.size() != 0) {
cerr << "error:[Aligner::align_pinned_multi] output vector must be empty for pinned multi-aligning" << endl;
exit(EXIT_FAILURE);
}
align_internal(alignment, &alt_alignments, g, true, pin_left, max_alt_alns, true);
}
void Aligner::align_global_banded(Alignment& alignment, const HandleGraph& g,
int32_t band_padding, bool permissive_banding) const {
if (alignment.sequence().empty()) {
// we can save time by using a specialized deletion aligner for empty strings
deletion_aligner.align(alignment, g);
return;
}
// We need to figure out what size ints we need to use.
// Get upper and lower bounds on the scores. TODO: if these overflow int64 we're out of luck
int64_t best_score = alignment.sequence().size() * match;
size_t total_bases = 0;
g.for_each_handle([&](const handle_t& handle) {
total_bases += g.get_length(handle);
});
int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension);
// TODO: put this all into another template somehow?
if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) {
// We'll fit in int8
BandedGlobalAligner<int8_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) {
// We'll fit in int16
BandedGlobalAligner<int16_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) {
// We'll fit in int32
BandedGlobalAligner<int32_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else {
// Fall back to int64
BandedGlobalAligner<int64_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
}
}
void Aligner::align_global_banded_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g,
int32_t max_alt_alns, int32_t band_padding, bool permissive_banding) const {
if (alignment.sequence().empty()) {
// we can save time by using a specialized deletion aligner for empty strings
deletion_aligner.align_multi(alignment, alt_alignments, g, max_alt_alns);
return;
}
// We need to figure out what size ints we need to use.
// Get upper and lower bounds on the scores. TODO: if these overflow int64 we're out of luck
int64_t best_score = alignment.sequence().size() * match;
size_t total_bases = 0;
g.for_each_handle([&](const handle_t& handle) {
total_bases += g.get_length(handle);
});
int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension);
if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) {
// We'll fit in int8
BandedGlobalAligner<int8_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) {
// We'll fit in int16
BandedGlobalAligner<int16_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) {
// We'll fit in int32
BandedGlobalAligner<int32_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else {
// Fall back to int64
BandedGlobalAligner<int64_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
false);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
}
}
void Aligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<MaximalExactMatch>& mems,
bool reverse_complemented, uint16_t max_gap_length) const
{
align_xdrop(alignment, g, handlealgs::lazier_topological_order(&g), mems, reverse_complemented,
max_gap_length);
}
void Aligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<handle_t>& order,
const vector<MaximalExactMatch>& mems, bool reverse_complemented, uint16_t max_gap_length) const
{
// XdropAligner manages its own stack, so it can never be threadsafe without be recreated
// for every alignment, which meshes poorly with its stack implementation. We achieve
// thread-safety by having one per thread, which makes this method const-ish.
XdropAligner& xdrop = const_cast<XdropAligner&>(xdrops[omp_get_thread_num()]);
xdrop.align(alignment, g, order, mems, reverse_complemented, full_length_bonus, max_gap_length);
if (!alignment.has_path() && mems.empty()) {
// dozeu couldn't find an alignment, probably because it's seeding heuristic failed
// we'll just fall back on GSSW
// TODO: This is a bit inconsistent. GSSW gives a full-length bonus at both ends, while
// dozeu only gives it once.
align(alignment, g, order);
}
}
// Scoring an exact match is very simple in an ordinary Aligner
int32_t Aligner::score_exact_match(const Alignment& aln, size_t read_offset, size_t length) const {
return match * length;
}
int32_t Aligner::score_exact_match(const string& sequence) const {
return match * sequence.length();
}
int32_t Aligner::score_exact_match(string::const_iterator seq_begin, string::const_iterator seq_end) const {
return match * (seq_end - seq_begin);
}
int32_t Aligner::score_exact_match(const string& sequence, const string& base_quality) const {
return score_exact_match(sequence);
}
int32_t Aligner::score_exact_match(string::const_iterator seq_begin, string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
return score_exact_match(seq_begin, seq_end);
}
int32_t Aligner::score_mismatch(string::const_iterator seq_begin, string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
return -mismatch * (seq_end - seq_begin);
}
int32_t Aligner::score_mismatch(size_t length) const {
return -match * length;
}
int32_t Aligner::score_full_length_bonus(bool left_side, string::const_iterator seq_begin,
string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
return full_length_bonus;
}
int32_t Aligner::score_full_length_bonus(bool left_side, const Alignment& alignment) const {
return full_length_bonus;
}
int32_t Aligner::score_partial_alignment(const Alignment& alignment, const HandleGraph& graph, const Path& path,
string::const_iterator seq_begin, bool no_read_end_scoring) const {
int32_t score = 0;
string::const_iterator read_pos = seq_begin;
bool in_deletion = false;
for (size_t i = 0; i < path.mapping_size(); i++) {
const Mapping& mapping = path.mapping(i);
for (size_t j = 0; j < mapping.edit_size(); j++) {
const Edit& edit = mapping.edit(j);
if (edit.from_length() > 0) {
if (edit.to_length() > 0) {
if (edit.sequence().empty()) {
// match
score += match * edit.from_length();
}
else {
// mismatch
score -= mismatch * edit.from_length();
}
// apply full length bonus
if (read_pos == alignment.sequence().begin() && !no_read_end_scoring) {
score += score_full_length_bonus(true, alignment);
}
if (read_pos + edit.to_length() == alignment.sequence().end()
&& !no_read_end_scoring) {
score += score_full_length_bonus(false, alignment);
}
in_deletion = false;
}
else if (in_deletion) {
score -= edit.from_length() * gap_extension;
}
else {
// deletion
score -= gap_open + (edit.from_length() - 1) * gap_extension;
in_deletion = true;
}
}
else if (edit.to_length() > 0) {
// don't score soft clips if scoring read ends
if (no_read_end_scoring ||
(read_pos != alignment.sequence().begin() &&
read_pos + edit.to_length() != alignment.sequence().end())) {
// insert
score -= gap_open + (edit.to_length() - 1) * gap_extension;
}
in_deletion = false;
}
read_pos += edit.to_length();
}
}
return score;
}
QualAdjAligner::QualAdjAligner(const int8_t* _score_matrix,
int8_t _gap_open,
int8_t _gap_extension,
int8_t _full_length_bonus,
double _gc_content)
: GSSWAligner(_score_matrix, _gap_open, _gap_extension, _full_length_bonus, _gc_content)
{
// TODO: this interface could really be improved in GSSW, oh well though
// find the quality-adjusted scores
uint32_t max_base_qual = 255;
// add in the 0s to the 5-th row and column for Ns
score_matrix = qual_adjusted_matrix(_score_matrix, _gc_content, max_base_qual);
// compute the quality adjusted full length bonuses
qual_adj_full_length_bonuses = qual_adjusted_bonuses(_full_length_bonus, max_base_qual);
// make a QualAdjXdropAligner for each thread
int num_threads = get_thread_count();
xdrops.reserve(num_threads);
for (size_t i = 0; i < num_threads; ++i) {
xdrops.emplace_back(_score_matrix, score_matrix, _gap_open, _gap_extension);
}
}
QualAdjAligner::~QualAdjAligner() {
free(qual_adj_full_length_bonuses);
}
int8_t* QualAdjAligner::qual_adjusted_matrix(const int8_t* _score_matrix, double gc_content, uint32_t max_qual) const {
// TODO: duplicative with GSSWAligner()
double* nt_freqs = (double*) malloc(sizeof(double) * 4);
nt_freqs[0] = 0.5 * (1 - gc_content);
nt_freqs[1] = 0.5 * gc_content;
nt_freqs[2] = 0.5 * gc_content;
nt_freqs[3] = 0.5 * (1 - gc_content);
// recover the emission probabilities of the align state of the HMM
double* align_prob = (double*) malloc(sizeof(double) * 16);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
align_prob[i * 4 + j] = (exp(log_base * _score_matrix[i * 4 + j])
* nt_freqs[i] * nt_freqs[j]);
}
}
// compute the sum of the emission probabilities under a base error
double* align_complement_prob = (double*) malloc(sizeof(double) * 16);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
align_complement_prob[i * 4 + j] = 0.0;
for (int k = 0; k < 4; k++) {
if (k != j) {
align_complement_prob[i * 4 + j] += align_prob[i * 4 + k];
}
}
}
}
// quality score of random guessing
int lowest_meaningful_qual = ceil(-10.0 * log10(0.75));
// compute the adjusted alignment scores for each quality level
int8_t* qual_adj_mat = (int8_t*) malloc(25 * (max_qual + 1) * sizeof(int8_t));
for (int q = 0; q <= max_qual; q++) {
double err = pow(10.0, -q / 10.0);
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
int8_t score;
if (i == 4 || j == 4 || q < lowest_meaningful_qual) {
score = 0;
}
else {
score = round(log(((1.0 - err) * align_prob[i * 4 + j] + (err / 3.0) * align_complement_prob[i * 4 + j])
/ (nt_freqs[i] * ((1.0 - err) * nt_freqs[j] + (err / 3.0) * (1.0 - nt_freqs[j])))) / log_base);
}
qual_adj_mat[q * 25 + i * 5 + j] = round(score);
}
}
}
free(align_complement_prob);
free(align_prob);
free(nt_freqs);
return qual_adj_mat;
}
int8_t* QualAdjAligner::qual_adjusted_bonuses(int8_t _full_length_bonus, uint32_t max_qual) const {
double p_full_len = exp(log_base * _full_length_bonus) / (1.0 + exp(log_base * _full_length_bonus));
int8_t* qual_adj_bonuses = (int8_t*) calloc(max_qual + 1, sizeof(int8_t));
int lowest_meaningful_qual = ceil(-10.0 * log10(0.75));
// hack because i want the minimum qual value from illumina (2) to have zero score, but phred
// values are spaced out in a way to approximate this singularity well
++lowest_meaningful_qual;
for (int q = lowest_meaningful_qual; q <= max_qual; ++q) {
double err = pow(10.0, -q / 10.0);
double score = log(((1.0 - err * 4.0 / 3.0) * p_full_len + (err * 4.0 / 3.0) * (1.0 - p_full_len)) / (1.0 - p_full_len)) / log_base;
qual_adj_bonuses[q] = round(score);
}
return qual_adj_bonuses;
}
void QualAdjAligner::align_internal(Alignment& alignment, vector<Alignment>* multi_alignments, const HandleGraph& g,
bool pinned, bool pin_left, int32_t max_alt_alns, bool traceback_aln) const {
// check input integrity
if (pin_left && !pinned) {
cerr << "error:[Aligner] cannot choose pinned end in non-pinned alignment" << endl;
exit(EXIT_FAILURE);
}
if (multi_alignments && !pinned) {
cerr << "error:[Aligner] multiple traceback is not implemented in local alignment, only pinned and global" << endl;
exit(EXIT_FAILURE);
}
if (!multi_alignments && max_alt_alns != 1) {
cerr << "error:[Aligner] cannot specify maximum number of alignments in single alignment" << endl;
exit(EXIT_FAILURE);
}
if (max_alt_alns <= 0) {
cerr << "error:[Aligner] cannot do less than 1 alignment" << endl;
exit(EXIT_FAILURE);
}
// alignment pinning algorithm is based on pinning in bottom right corner, if pinning in top
// left we need to reverse all the sequences first and translate the alignment back later
// make a place to reverse the graph and sequence if necessary
ReverseGraph reversed_graph(&g, false);
string reversed_sequence;
string reversed_quality;
// choose forward or reversed objects
const HandleGraph* oriented_graph = &g;
const string* align_sequence = &alignment.sequence();
const string* align_quality = &alignment.quality();
if (pin_left) {
// choose the reversed graph
oriented_graph = &reversed_graph;
// make and assign the reversed sequence
reversed_sequence.resize(align_sequence->size());
reverse_copy(align_sequence->begin(), align_sequence->end(), reversed_sequence.begin());
align_sequence = &reversed_sequence;
// make and assign the reversed quality
reversed_quality.resize(align_quality->size());
reverse_copy(align_quality->begin(), align_quality->end(), reversed_quality.begin());
align_quality = &reversed_quality;
}
if (align_quality->size() != align_sequence->size()) {
cerr << "error:[QualAdjAligner] Read " << alignment.name() << " has sequence and quality strings with different lengths. Cannot perform base quality adjusted alignment. Consider toggling off base quality adjusted alignment at the command line." << endl;
exit(EXIT_FAILURE);
}
// to save compute, we won't make these unless we're doing pinning
unordered_set<vg::id_t> pinning_ids;
NullMaskingGraph* null_masked_graph = nullptr;
const HandleGraph* align_graph = oriented_graph;
if (pinned) {
pinning_ids = identify_pinning_points(*oriented_graph);
null_masked_graph = new NullMaskingGraph(oriented_graph);
align_graph = null_masked_graph;
}
// convert into gssw graph
gssw_graph* graph = create_gssw_graph(*align_graph);
int8_t front_full_length_bonus = qual_adj_full_length_bonuses[align_quality->front()];
int8_t back_full_length_bonus = qual_adj_full_length_bonuses[align_quality->back()];
// perform dynamic programming
// offer a full length bonus on each end, or only on the left if the right end is pinned.
gssw_graph_fill_pinned_qual_adj(graph, align_sequence->c_str(), align_quality->c_str(),
nt_table, score_matrix,
gap_open, gap_extension,
front_full_length_bonus,
pinned ? 0 : back_full_length_bonus,
15, 2, traceback_aln);
// traceback either from pinned position or optimal local alignment
if (traceback_aln) {
if (pinned) {
gssw_graph_mapping** gms = nullptr;
if (align_graph->get_node_count() > 0) {
gssw_node** pinning_nodes = (gssw_node**) malloc(pinning_ids.size() * sizeof(gssw_node*));
size_t j = 0;
for (size_t i = 0; i < graph->size; i++) {
gssw_node* node = graph->nodes[i];
if (pinning_ids.count(node->id)) {
pinning_nodes[j] = node;
j++;
}
}
// trace back pinned alignment
gms = gssw_graph_trace_back_pinned_qual_adj_multi (graph,
max_alt_alns,
true,
align_sequence->c_str(),
align_quality->c_str(),
align_sequence->size(),
pinning_nodes,
pinning_ids.size(),
nt_table,
score_matrix,
gap_open,
gap_extension,
front_full_length_bonus,
0);
free(pinning_nodes);
}
// did we both 1) do DP (i.e. the graph is non-empty), and 2) find a traceback with positive score?
if (gms && gms[0]->score > 0) {
if (pin_left) {
// translate graph and mappings into original node space
unreverse_graph(graph);
for (int32_t i = 0; i < max_alt_alns; i++) {
unreverse_graph_mapping(gms[i]);
}
}
// have a mapping, can just convert normally
gssw_mapping_to_alignment(graph, gms[0], alignment, pinned, pin_left);
if (multi_alignments) {
// determine how many non-null alignments were returned
int32_t num_non_null = max_alt_alns;
for (int32_t i = 1; i < max_alt_alns; i++) {
if (gms[i]->score <= 0) {
num_non_null = i;
break;
}
}
// reserve to avoid illegal access errors that occur when the vector reallocates
multi_alignments->reserve(num_non_null);
// copy the primary alignment
multi_alignments->emplace_back(alignment);
// convert the alternate alignments and store them at the back of the vector (this will not
// execute if we are doing single alignment)
for (int32_t i = 1; i < num_non_null; i++) {
// make new alignment object
multi_alignments->emplace_back();
Alignment& next_alignment = multi_alignments->back();
// copy over sequence information from the primary alignment
next_alignment.set_sequence(alignment.sequence());
next_alignment.set_quality(alignment.quality());
// get path of the alternate alignment
gssw_mapping_to_alignment(graph, gms[i], next_alignment, pinned, pin_left);
}
}
}
else if (g.get_node_count() > 0) {
/// we didn't get any alignments either because the graph was empty and we couldn't run
// gssw DP or because they had score 0 and gssw didn't want to do traceback. however,
// we can infer the location of softclips based on the pinning nodes, so we'll just make
// those manually
// find the sink nodes of the oriented graph, which may be empty
auto pinning_points = handlealgs::tail_nodes(oriented_graph);
// impose a consistent ordering for machine independent behavior
sort(pinning_points.begin(), pinning_points.end(), [&](const handle_t& h1, const handle_t& h2) {
return oriented_graph->get_id(h1) < oriented_graph->get_id(h2);
});
for (size_t i = 0; i < max_alt_alns && i < pinning_points.size(); i++) {
// make a record in the multi alignments if we're using them
if (multi_alignments) {
multi_alignments->emplace_back();
}
// choose an alignment object to construct the path in
Alignment& softclip_alignment = i == 0 ? alignment : multi_alignments->back();
handle_t& pinning_point = pinning_points[i];
Mapping* mapping = alignment.mutable_path()->add_mapping();
mapping->set_rank(1);
// locate at the beginning or end of the node
Position* position = mapping->mutable_position();
position->set_node_id(oriented_graph->get_id(pinning_point));
position->set_offset(pin_left ? 0 : oriented_graph->get_length(pinning_point));
// soft clip
Edit* edit = mapping->add_edit();
edit->set_to_length(alignment.sequence().length());
edit->set_sequence(alignment.sequence());
// we want to also have the first alignment in the multi-alignment vector
if (i == 0 && multi_alignments) {
multi_alignments->back() = alignment;
}
}
}
if (gms) {
for (int32_t i = 0; i < max_alt_alns; i++) {
gssw_graph_mapping_destroy(gms[i]);
}
free(gms);
}
}
else {
// trace back local alignment
gssw_graph_mapping* gm = gssw_graph_trace_back_qual_adj (graph,
align_sequence->c_str(),
align_quality->c_str(),
align_sequence->size(),
nt_table,
score_matrix,
gap_open,
gap_extension,
front_full_length_bonus,
back_full_length_bonus);
gssw_mapping_to_alignment(graph, gm, alignment, pinned, pin_left);
gssw_graph_mapping_destroy(gm);
}
} else {
// get the alignment position and score
alignment.set_score(graph->max_node->alignment->score1);
Mapping* m = alignment.mutable_path()->add_mapping();
Position* p = m->mutable_position();
p->set_node_id(graph->max_node->id);
p->set_offset(graph->max_node->alignment->ref_end1); // mark end position; for de-duplication
}
// this might be null if we're not doing pinned alignment, but delete doesn't care
delete null_masked_graph;
gssw_graph_destroy(graph);
}
void QualAdjAligner::align(Alignment& alignment, const HandleGraph& g, bool traceback_aln) const {
align_internal(alignment, nullptr, g, false, false, 1, traceback_aln);
}
void QualAdjAligner::align_pinned(Alignment& alignment, const HandleGraph& g, bool pin_left, bool xdrop,
uint16_t xdrop_max_gap_length) const {
if (xdrop) {
// QualAdjXdropAligner manages its own stack, so it can never be threadsafe without be recreated
// for every alignment, which meshes poorly with its stack implementation. We achieve
// thread-safety by having one per thread, which makes this method const-ish.
QualAdjXdropAligner& xdrop = const_cast<QualAdjXdropAligner&>(xdrops[omp_get_thread_num()]);
// wrap the graph so that empty pinning points are handled correctly
DozeuPinningOverlay overlay(&g, !pin_left);
if (overlay.get_node_count() == 0 && g.get_node_count() > 0) {
// the only nodes in the graph are empty nodes for pinning, which got masked.
// we can still infer a pinned alignment based purely on the pinning point but
// dozeu won't handle this correctly
g.for_each_handle([&](const handle_t& handle) {
bool can_pin = g.follow_edges(handle, pin_left, [&](const handle_t& next) {return false;});
if (can_pin) {
// manually make the softclip
Mapping* mapping = alignment.mutable_path()->add_mapping();
Position* pos = mapping->mutable_position();
pos->set_node_id(g.get_id(handle));
pos->set_is_reverse(false);
pos->set_offset(pin_left ? 0 : g.get_length(handle));
mapping->set_rank(1);
Edit* edit = mapping->add_edit();
edit->set_from_length(0);
edit->set_to_length(alignment.sequence().size());
edit->set_sequence(alignment.sequence());
alignment.set_score(0);
return false;
}
return true;
});
}
else {
// dozeu declines to produce an alignment when the gap is set to 0
xdrop_max_gap_length = max<uint16_t>(xdrop_max_gap_length, 1);
// get the quality adjusted bonus
int8_t bonus = qual_adj_full_length_bonuses[pin_left ? alignment.quality().back() : alignment.quality().front()];
xdrop.align_pinned(alignment, overlay, pin_left, bonus, xdrop_max_gap_length);
if (overlay.performed_duplications()) {
// the overlay is not a strict subset of the underlying graph, so we may
// need to translate some node IDs
translate_oriented_node_ids(*alignment.mutable_path(), [&](id_t node_id) {
handle_t under = overlay.get_underlying_handle(overlay.get_handle(node_id));
return make_pair(g.get_id(under), g.get_is_reverse(under));
});
}
}
}
else {
align_internal(alignment, nullptr, g, true, pin_left, 1, true);
}
}
void QualAdjAligner::align_pinned_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g,
bool pin_left, int32_t max_alt_alns) const {
align_internal(alignment, &alt_alignments, g, true, pin_left, max_alt_alns, true);
}
void QualAdjAligner::align_global_banded(Alignment& alignment, const HandleGraph& g,
int32_t band_padding, bool permissive_banding) const {
if (alignment.sequence().empty()) {
// we can save time by using a specialized deletion aligner for empty strings
deletion_aligner.align(alignment, g);
return;
}
int64_t best_score = alignment.sequence().size() * match;
size_t total_bases = 0;
g.for_each_handle([&](const handle_t& handle) {
total_bases += g.get_length(handle);
});
int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension);
// TODO: put this all into another template somehow?
if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) {
// We'll fit in int8
BandedGlobalAligner<int8_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) {
// We'll fit in int16
BandedGlobalAligner<int16_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) {
// We'll fit in int32
BandedGlobalAligner<int32_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else {
// Fall back to int64
BandedGlobalAligner<int64_t> band_graph(alignment,
g,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
}
}
void QualAdjAligner::align_global_banded_multi(Alignment& alignment, vector<Alignment>& alt_alignments, const HandleGraph& g,
int32_t max_alt_alns, int32_t band_padding, bool permissive_banding) const {
if (alignment.sequence().empty()) {
// we can save time by using a specialized deletion aligner for empty strings
deletion_aligner.align_multi(alignment, alt_alignments, g, max_alt_alns);
return;
}
// We need to figure out what size ints we need to use.
// Get upper and lower bounds on the scores. TODO: if these overflow int64 we're out of luck
int64_t best_score = alignment.sequence().size() * match;
size_t total_bases = 0;
g.for_each_handle([&](const handle_t& handle) {
total_bases += g.get_length(handle);
});
int64_t worst_score = (alignment.sequence().size() + total_bases) * -max(max(mismatch, gap_open), gap_extension);
if (best_score <= numeric_limits<int8_t>::max() && worst_score >= numeric_limits<int8_t>::min()) {
// We'll fit in int8
BandedGlobalAligner<int8_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int16_t>::max() && worst_score >= numeric_limits<int16_t>::min()) {
// We'll fit in int16
BandedGlobalAligner<int16_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else if (best_score <= numeric_limits<int32_t>::max() && worst_score >= numeric_limits<int32_t>::min()) {
// We'll fit in int32
BandedGlobalAligner<int32_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
} else {
// Fall back to int64
BandedGlobalAligner<int64_t> band_graph(alignment,
g,
alt_alignments,
max_alt_alns,
band_padding,
permissive_banding,
true);
band_graph.align(score_matrix, nt_table, gap_open, gap_extension);
}
}
void QualAdjAligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<MaximalExactMatch>& mems,
bool reverse_complemented, uint16_t max_gap_length) const
{
align_xdrop(alignment, g, handlealgs::lazier_topological_order(&g), mems, reverse_complemented, max_gap_length);
}
void QualAdjAligner::align_xdrop(Alignment& alignment, const HandleGraph& g, const vector<handle_t>& order,
const vector<MaximalExactMatch>& mems, bool reverse_complemented,
uint16_t max_gap_length) const
{
// QualAdjXdropAligner manages its own stack, so it can never be threadsafe without being recreated
// for every alignment, which meshes poorly with its stack implementation. We achieve
// thread-safety by having one per thread, which makes this method const-ish.
QualAdjXdropAligner& xdrop = const_cast<QualAdjXdropAligner&>(xdrops[omp_get_thread_num()]);
// get the quality adjusted bonus
int8_t bonus = qual_adj_full_length_bonuses[reverse_complemented ? alignment.quality().front() : alignment.quality().back()];
xdrop.align(alignment, g, order, mems, reverse_complemented, bonus, max_gap_length);
if (!alignment.has_path() && mems.empty()) {
// dozeu couldn't find an alignment, probably because it's seeding heuristic failed
// we'll just fall back on GSSW
// TODO: This is a bit inconsistent. GSSW gives a full-length bonus at both ends, while
// dozeu only gives it once.
align(alignment, g, true);
}
}
int32_t QualAdjAligner::score_exact_match(const Alignment& aln, size_t read_offset, size_t length) const {
auto& sequence = aln.sequence();
auto& base_quality = aln.quality();
int32_t score = 0;
for (int32_t i = 0; i < length; i++) {
// index 5 x 5 score matrices (ACGTN)
// always have match so that row and column index are same and can combine algebraically
score += score_matrix[25 * base_quality[read_offset + i] + 6 * nt_table[sequence[read_offset + i]]];
}
return score;
}
int32_t QualAdjAligner::score_exact_match(const string& sequence, const string& base_quality) const {
int32_t score = 0;
for (int32_t i = 0; i < sequence.length(); i++) {
// index 5 x 5 score matrices (ACGTN)
// always have match so that row and column index are same and can combine algebraically
score += score_matrix[25 * base_quality[i] + 6 * nt_table[sequence[i]]];
}
return score;
}
int32_t QualAdjAligner::score_exact_match(string::const_iterator seq_begin, string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
int32_t score = 0;
for (auto seq_iter = seq_begin, qual_iter = base_qual_begin; seq_iter != seq_end; seq_iter++) {
// index 5 x 5 score matrices (ACGTN)
// always have match so that row and column index are same and can combine algebraically
score += score_matrix[25 * (*qual_iter) + 6 * nt_table[*seq_iter]];
qual_iter++;
}
return score;
}
int32_t QualAdjAligner::score_mismatch(string::const_iterator seq_begin, string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
int32_t score = 0;
for (auto seq_iter = seq_begin, qual_iter = base_qual_begin; seq_iter != seq_end; seq_iter++) {
// index 5 x 5 score matrices (ACGTN)
// always have match so that row and column index are same and can combine algebraically
score += score_matrix[25 * (*qual_iter) + 1];
qual_iter++;
}
return score;
}
int32_t QualAdjAligner::score_full_length_bonus(bool left_side, string::const_iterator seq_begin,
string::const_iterator seq_end,
string::const_iterator base_qual_begin) const {
if (seq_begin != seq_end) {
return qual_adj_full_length_bonuses[left_side ? *base_qual_begin : *(base_qual_begin + (seq_end - seq_begin) - 1)];
}
else {
return 0;
}
}
int32_t QualAdjAligner::score_full_length_bonus(bool left_side, const Alignment& alignment) const {
return score_full_length_bonus(left_side, alignment.sequence().begin(), alignment.sequence().end(),
alignment.quality().begin());
}
int32_t QualAdjAligner::score_partial_alignment(const Alignment& alignment, const HandleGraph& graph, const Path& path,
string::const_iterator seq_begin, bool no_read_end_scoring) const {
int32_t score = 0;
string::const_iterator read_pos = seq_begin;
string::const_iterator qual_pos = alignment.quality().begin() + (seq_begin - alignment.sequence().begin());
bool in_deletion = false;
for (size_t i = 0; i < path.mapping_size(); i++) {
const Mapping& mapping = path.mapping(i);
// get the sequence of this node on the proper strand
string node_seq = graph.get_sequence(graph.get_handle(mapping.position().node_id(),
mapping.position().is_reverse()));
string::const_iterator ref_pos = node_seq.begin() + mapping.position().offset();
for (size_t j = 0; j < mapping.edit_size(); j++) {
const Edit& edit = mapping.edit(j);
if (edit.from_length() > 0) {
if (edit.to_length() > 0) {
for (auto siter = read_pos, riter = ref_pos, qiter = qual_pos;
siter != read_pos + edit.to_length(); siter++, qiter++, riter++) {
score += score_matrix[25 * (*qiter) + 5 * nt_table[*riter] + nt_table[*siter]];
}
// apply full length bonus
if (read_pos == alignment.sequence().begin() && !no_read_end_scoring) {
score += score_full_length_bonus(true, alignment);
}
if (read_pos + edit.to_length() == alignment.sequence().end()
&& !no_read_end_scoring) {
score += score_full_length_bonus(false, alignment);
}
in_deletion = false;
}
else if (in_deletion) {
score -= edit.from_length() * gap_extension;
}
else {
// deletion
score -= gap_open + (edit.from_length() - 1) * gap_extension;
in_deletion = true;
}
}
else if (edit.to_length() > 0) {
// don't score soft clips if read end scoring
if (no_read_end_scoring ||
(read_pos != alignment.sequence().begin() &&
read_pos + edit.to_length() != alignment.sequence().end())) {
// insert
score -= gap_open + (edit.to_length() - 1) * gap_extension;
}
in_deletion = false;
}
read_pos += edit.to_length();
qual_pos += edit.to_length();
ref_pos += edit.from_length();
}
}
return score;
}
AlignerClient::AlignerClient(double gc_content_estimate) : gc_content_estimate(gc_content_estimate) {
// Adopt the default scoring parameters and make the aligners
set_alignment_scores(default_score_matrix,
default_gap_open, default_gap_extension,
default_full_length_bonus);
}
const GSSWAligner* AlignerClient::get_aligner(bool have_qualities) const {
return (have_qualities && adjust_alignments_for_base_quality) ?
(GSSWAligner*) get_qual_adj_aligner() :
(GSSWAligner*) get_regular_aligner();
}
const QualAdjAligner* AlignerClient::get_qual_adj_aligner() const {
assert(qual_adj_aligner.get() != nullptr);
return qual_adj_aligner.get();
}
const Aligner* AlignerClient::get_regular_aligner() const {
assert(regular_aligner.get() != nullptr);
return regular_aligner.get();
}
int8_t* AlignerClient::parse_matrix(istream& matrix_stream) {
int8_t* matrix = (int8_t*) malloc(16 * sizeof(int8_t));
for (size_t i = 0; i < 16; i++) {
if (!matrix_stream.good()) {
std::cerr << "error: vg Aligner::parse_matrix requires a 4x4 whitespace separated integer matrix\n";
throw "";
}
int score;
matrix_stream >> score;
if (score > 127 || score < -127) {
std::cerr << "error: vg Aligner::parse_matrix requires values in the range [-127,127]\n";
throw "";
}
matrix[i] = score;
}
return matrix;
}
void AlignerClient::set_alignment_scores(int8_t match, int8_t mismatch, int8_t gap_open, int8_t gap_extend,
int8_t full_length_bonus) {
int8_t* matrix = (int8_t*) malloc(sizeof(int8_t) * 16);
for (size_t i = 0; i < 16; ++i) {
if (i % 5 == 0) {
matrix[i] = match;
}
else {
matrix[i] = -mismatch;
}
}
qual_adj_aligner = unique_ptr<QualAdjAligner>(new QualAdjAligner(matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
regular_aligner = unique_ptr<Aligner>(new Aligner(matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
free(matrix);
}
void AlignerClient::set_alignment_scores(const int8_t* score_matrix, int8_t gap_open, int8_t gap_extend, int8_t full_length_bonus) {
qual_adj_aligner = unique_ptr<QualAdjAligner>(new QualAdjAligner(score_matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
regular_aligner = unique_ptr<Aligner>(new Aligner(score_matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
}
void AlignerClient::set_alignment_scores(std::istream& matrix_stream, int8_t gap_open, int8_t gap_extend, int8_t full_length_bonus) {
int8_t* score_matrix = parse_matrix(matrix_stream);
qual_adj_aligner = unique_ptr<QualAdjAligner>(new QualAdjAligner(score_matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
regular_aligner = unique_ptr<Aligner>(new Aligner(score_matrix, gap_open, gap_extend,
full_length_bonus, gc_content_estimate));
free(score_matrix);
}
| 107,053 | 31,252 |
#include <memory>
#include "FWCore/Framework/interface/Frameworkfwd.h"
#include "FWCore/Framework/interface/stream/EDProducer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/StreamID.h"
#include "L1Trigger/Phase2L1GMT/interface/L1TPhase2GMTEndcapStubProcessor.h"
#include "L1Trigger/Phase2L1GMT/interface/L1TPhase2GMTBarrelStubProcessor.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/Framework/interface/ConsumesCollector.h"
#include "FWCore/Framework/interface/ESProducts.h"
#include "FWCore/Utilities/interface/ESGetToken.h"
//
// class declaration
//
class Phase2L1TGMTStubProducer : public edm::stream::EDProducer<> {
public:
explicit Phase2L1TGMTStubProducer(const edm::ParameterSet&);
~Phase2L1TGMTStubProducer() override;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
private:
void beginStream(edm::StreamID) override;
void produce(edm::Event&, const edm::EventSetup&) override;
void endStream() override;
edm::EDGetTokenT<MuonDigiCollection<CSCDetId, CSCCorrelatedLCTDigi>> srcCSC_;
edm::EDGetTokenT<L1Phase2MuDTPhContainer> srcDT_;
edm::EDGetTokenT<L1MuDTChambThContainer> srcDTTheta_;
edm::EDGetTokenT<RPCDigiCollection> srcRPC_;
L1TPhase2GMTEndcapStubProcessor* procEndcap_;
L1TPhase2GMTBarrelStubProcessor* procBarrel_;
L1TMuon::GeometryTranslator* translator_;
int verbose_;
};
Phase2L1TGMTStubProducer::Phase2L1TGMTStubProducer(const edm::ParameterSet& iConfig)
: srcCSC_(
consumes<MuonDigiCollection<CSCDetId, CSCCorrelatedLCTDigi>>(iConfig.getParameter<edm::InputTag>("srcCSC"))),
srcDT_(consumes<L1Phase2MuDTPhContainer>(iConfig.getParameter<edm::InputTag>("srcDT"))),
srcDTTheta_(consumes<L1MuDTChambThContainer>(iConfig.getParameter<edm::InputTag>("srcDTTheta"))),
srcRPC_(consumes<RPCDigiCollection>(iConfig.getParameter<edm::InputTag>("srcRPC"))),
procEndcap_(new L1TPhase2GMTEndcapStubProcessor(iConfig.getParameter<edm::ParameterSet>("Endcap"))),
procBarrel_(new L1TPhase2GMTBarrelStubProcessor(iConfig.getParameter<edm::ParameterSet>("Barrel"))),
verbose_(iConfig.getParameter<int>("verbose")) {
produces<l1t::MuonStubCollection>();
edm::ConsumesCollector consumesColl(consumesCollector());
translator_ = new L1TMuon::GeometryTranslator(consumesColl);
}
Phase2L1TGMTStubProducer::~Phase2L1TGMTStubProducer() {
// do anything here that needs to be done at destruction time
// (e.g. close files, deallocate resources etc.)
if (procEndcap_ != nullptr)
delete procEndcap_;
if (procBarrel_ != nullptr)
delete procBarrel_;
if (translator_ != nullptr)
delete translator_;
}
//
// member functions
//
// ------------ method called to produce the data ------------
void Phase2L1TGMTStubProducer::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) {
using namespace edm;
translator_->checkAndUpdateGeometry(iSetup);
Handle<MuonDigiCollection<CSCDetId, CSCCorrelatedLCTDigi>> cscDigis;
iEvent.getByToken(srcCSC_, cscDigis);
Handle<RPCDigiCollection> rpcDigis;
iEvent.getByToken(srcRPC_, rpcDigis);
Handle<L1Phase2MuDTPhContainer> dtDigis;
iEvent.getByToken(srcDT_, dtDigis);
Handle<L1MuDTChambThContainer> dtThetaDigis;
iEvent.getByToken(srcDTTheta_, dtThetaDigis);
//Generate a unique stub ID
l1t::MuonStubCollection stubs;
uint count0 = 0;
uint count1 = 0;
uint count2 = 0;
uint count3 = 0;
uint count4 = 0;
l1t::MuonStubCollection stubsEndcap = procEndcap_->makeStubs(*cscDigis, *rpcDigis, translator_, iSetup);
for (auto& stub : stubsEndcap) {
if (stub.tfLayer() == 0) {
stub.setID(count0);
count0++;
} else if (stub.tfLayer() == 1) {
stub.setID(count1);
count1++;
} else if (stub.tfLayer() == 2) {
stub.setID(count2);
count2++;
} else if (stub.tfLayer() == 3) {
stub.setID(count3);
count3++;
} else {
stub.setID(count4);
count4++;
}
stubs.push_back(stub);
}
l1t::MuonStubCollection stubsBarrel = procBarrel_->makeStubs(dtDigis.product(), dtThetaDigis.product());
for (auto& stub : stubsBarrel) {
if (stub.tfLayer() == 0) {
stub.setID(count0);
count0++;
} else if (stub.tfLayer() == 1) {
stub.setID(count1);
count1++;
} else if (stub.tfLayer() == 2) {
stub.setID(count2);
count2++;
} else if (stub.tfLayer() == 3) {
stub.setID(count3);
count3++;
} else {
stub.setID(count4);
count4++;
}
stubs.push_back(stub);
}
iEvent.put(std::make_unique<l1t::MuonStubCollection>(stubs));
}
// ------------ method called once each stream before processing any runs, lumis or events ------------
void Phase2L1TGMTStubProducer::beginStream(edm::StreamID) {}
// ------------ method called once each stream after processing all runs, lumis and events ------------
void Phase2L1TGMTStubProducer::endStream() {}
void Phase2L1TGMTStubProducer::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
// gmtStubs
edm::ParameterSetDescription desc;
desc.add<int>("verbose", 0);
desc.add<edm::InputTag>("srcCSC", edm::InputTag("simCscTriggerPrimitiveDigis"));
desc.add<edm::InputTag>("srcDT", edm::InputTag("dtTriggerPhase2PrimitiveDigis"));
desc.add<edm::InputTag>("srcDTTheta", edm::InputTag("simDtTriggerPrimitiveDigis"));
desc.add<edm::InputTag>("srcRPC", edm::InputTag("simMuonRPCDigis"));
{
edm::ParameterSetDescription psd0;
psd0.add<unsigned int>("verbose", 0);
psd0.add<int>("minBX", 0);
psd0.add<int>("maxBX", 0);
psd0.add<double>("coord1LSB", 0.02453124992);
psd0.add<double>("eta1LSB", 0.024586688);
psd0.add<double>("coord2LSB", 0.02453124992);
psd0.add<double>("eta2LSB", 0.024586688);
psd0.add<double>("phiMatch", 0.05);
psd0.add<double>("etaMatch", 0.1);
desc.add<edm::ParameterSetDescription>("Endcap", psd0);
}
{
edm::ParameterSetDescription psd0;
psd0.add<int>("verbose", 0);
psd0.add<int>("minPhiQuality", 0);
psd0.add<int>("minThetaQuality", 0);
psd0.add<int>("minBX", 0);
psd0.add<int>("maxBX", 0);
psd0.add<double>("phiLSB", 0.02453124992);
psd0.add<int>("phiBDivider", 16);
psd0.add<double>("etaLSB", 0.024586688);
psd0.add<std::vector<int>>(
"eta_1",
{
-46, -45, -43, -41, -39, -37, -35, -30, -28, -26, -23, -20, -18, -15, -9, -6, -3, -1,
1, 3, 6, 9, 15, 18, 20, 23, 26, 28, 30, 35, 37, 39, 41, 43, 45, 1503,
});
psd0.add<std::vector<int>>(
"eta_2",
{
-41, -39, -38, -36, -34, -32, -30, -26, -24, -22, -20, -18, -15, -13, -8, -5, -3, -1,
1, 3, 5, 8, 13, 15, 18, 20, 22, 24, 26, 30, 32, 34, 36, 38, 39, 1334,
});
psd0.add<std::vector<int>>(
"eta_3",
{
-35, -34, -32, -31, -29, -27, -26, -22, -20, -19, -17, -15, -13, -11, -6, -4, -2, -1,
1, 2, 4, 6, 11, 13, 15, 17, 19, 20, 22, 26, 27, 29, 31, 32, 34, 1148,
});
psd0.add<std::vector<int>>("coarseEta_1",
{
0,
23,
41,
});
psd0.add<std::vector<int>>("coarseEta_2",
{
0,
20,
36,
});
psd0.add<std::vector<int>>("coarseEta_3",
{
0,
17,
31,
});
psd0.add<std::vector<int>>("coarseEta_4",
{
0,
14,
27,
});
psd0.add<std::vector<int>>("phiOffset",
{
1,
0,
0,
0,
});
desc.add<edm::ParameterSetDescription>("Barrel", psd0);
}
descriptions.add("gmtStubs", desc);
}
//define this as a plug-in
DEFINE_FWK_MODULE(Phase2L1TGMTStubProducer);
| 8,573 | 3,383 |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tsf/v20180326/model/CreateLaneRuleRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Tsf::V20180326::Model;
using namespace std;
CreateLaneRuleRequest::CreateLaneRuleRequest() :
m_ruleNameHasBeenSet(false),
m_remarkHasBeenSet(false),
m_ruleTagListHasBeenSet(false),
m_ruleTagRelationshipHasBeenSet(false),
m_laneIdHasBeenSet(false),
m_programIdListHasBeenSet(false)
{
}
string CreateLaneRuleRequest::ToJsonString() const
{
rapidjson::Document d;
d.SetObject();
rapidjson::Document::AllocatorType& allocator = d.GetAllocator();
if (m_ruleNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RuleName";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_ruleName.c_str(), allocator).Move(), allocator);
}
if (m_remarkHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Remark";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_remark.c_str(), allocator).Move(), allocator);
}
if (m_ruleTagListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RuleTagList";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_ruleTagList.begin(); itr != m_ruleTagList.end(); ++itr, ++i)
{
d[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(d[key.c_str()][i], allocator);
}
}
if (m_ruleTagRelationshipHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RuleTagRelationship";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_ruleTagRelationship.c_str(), allocator).Move(), allocator);
}
if (m_laneIdHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "LaneId";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(m_laneId.c_str(), allocator).Move(), allocator);
}
if (m_programIdListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ProgramIdList";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_programIdList.begin(); itr != m_programIdList.end(); ++itr)
{
d[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
string CreateLaneRuleRequest::GetRuleName() const
{
return m_ruleName;
}
void CreateLaneRuleRequest::SetRuleName(const string& _ruleName)
{
m_ruleName = _ruleName;
m_ruleNameHasBeenSet = true;
}
bool CreateLaneRuleRequest::RuleNameHasBeenSet() const
{
return m_ruleNameHasBeenSet;
}
string CreateLaneRuleRequest::GetRemark() const
{
return m_remark;
}
void CreateLaneRuleRequest::SetRemark(const string& _remark)
{
m_remark = _remark;
m_remarkHasBeenSet = true;
}
bool CreateLaneRuleRequest::RemarkHasBeenSet() const
{
return m_remarkHasBeenSet;
}
vector<LaneRuleTag> CreateLaneRuleRequest::GetRuleTagList() const
{
return m_ruleTagList;
}
void CreateLaneRuleRequest::SetRuleTagList(const vector<LaneRuleTag>& _ruleTagList)
{
m_ruleTagList = _ruleTagList;
m_ruleTagListHasBeenSet = true;
}
bool CreateLaneRuleRequest::RuleTagListHasBeenSet() const
{
return m_ruleTagListHasBeenSet;
}
string CreateLaneRuleRequest::GetRuleTagRelationship() const
{
return m_ruleTagRelationship;
}
void CreateLaneRuleRequest::SetRuleTagRelationship(const string& _ruleTagRelationship)
{
m_ruleTagRelationship = _ruleTagRelationship;
m_ruleTagRelationshipHasBeenSet = true;
}
bool CreateLaneRuleRequest::RuleTagRelationshipHasBeenSet() const
{
return m_ruleTagRelationshipHasBeenSet;
}
string CreateLaneRuleRequest::GetLaneId() const
{
return m_laneId;
}
void CreateLaneRuleRequest::SetLaneId(const string& _laneId)
{
m_laneId = _laneId;
m_laneIdHasBeenSet = true;
}
bool CreateLaneRuleRequest::LaneIdHasBeenSet() const
{
return m_laneIdHasBeenSet;
}
vector<string> CreateLaneRuleRequest::GetProgramIdList() const
{
return m_programIdList;
}
void CreateLaneRuleRequest::SetProgramIdList(const vector<string>& _programIdList)
{
m_programIdList = _programIdList;
m_programIdListHasBeenSet = true;
}
bool CreateLaneRuleRequest::ProgramIdListHasBeenSet() const
{
return m_programIdListHasBeenSet;
}
| 5,703 | 1,974 |
#include "GenericPagingTable.h"
#include "MemoryManager.h"
namespace kernel {
#ifdef ULTRA_64
Address GenericPagingTable::accessible_address_of(size_t index)
{
return MemoryManager::physical_memory_base + entry_at(index).physical_address();
}
#endif
}
| 258 | 90 |
// Copyright 2021 The Abseil Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "absl/strings/internal/cord_rep_btree_reader.h"
#include <iostream>
#include <random>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/base/config.h"
#include "absl/base/internal/raw_logging.h"
#include "absl/strings/cord.h"
#include "absl/strings/internal/cord_internal.h"
#include "absl/strings/internal/cord_rep_btree.h"
#include "absl/strings/internal/cord_rep_test_util.h"
#include "absl/strings/string_view.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace cord_internal {
namespace {
using ::testing::Eq;
using ::testing::IsEmpty;
using ::testing::Ne;
using ::testing::Not;
using ::absl::cordrep_testing::CordRepBtreeFromFlats;
using ::absl::cordrep_testing::MakeFlat;
using ::absl::cordrep_testing::CordToString;
using ::absl::cordrep_testing::CreateFlatsFromString;
using ::absl::cordrep_testing::CreateRandomString;
using ReadResult = CordRepBtreeReader::ReadResult;
TEST(CordRepBtreeReaderTest, Next) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
int counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17};
for (int count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
CordRepBtreeReader reader;
absl::string_view chunk = reader.Init(node);
EXPECT_THAT(chunk, Eq(data.substr(0, chunk.length())));
size_t consumed = chunk.length();
EXPECT_THAT(reader.consumed(), Eq(consumed));
while (consumed < data.length()) {
chunk = reader.Next();
EXPECT_THAT(chunk, Eq(data.substr(consumed, chunk.length())));
consumed += chunk.length();
EXPECT_THAT(reader.consumed(), Eq(consumed));
}
EXPECT_THAT(consumed, Eq(data.length()));
EXPECT_THAT(reader.consumed(), Eq(data.length()));
CordRep::Unref(node);
}
}
TEST(CordRepBtreeReaderTest, Skip) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
int counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17};
for (int count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
for (size_t skip1 = 0; skip1 < data.length() - kChars; ++skip1) {
for (size_t skip2 = 0; skip2 < data.length() - kChars; ++skip2) {
CordRepBtreeReader reader;
absl::string_view chunk = reader.Init(node);
size_t consumed = chunk.length();
chunk = reader.Skip(skip1);
ASSERT_THAT(chunk, Eq(data.substr(consumed + skip1, chunk.length())));
consumed += chunk.length() + skip1;
ASSERT_THAT(reader.consumed(), Eq(consumed));
if (consumed >= data.length()) continue;
size_t skip = std::min(data.length() - consumed - 1, skip2);
chunk = reader.Skip(skip);
ASSERT_THAT(chunk, Eq(data.substr(consumed + skip, chunk.length())));
}
}
CordRep::Unref(node);
}
}
TEST(CordRepBtreeReaderTest, SkipBeyondLength) {
CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc"));
tree = CordRepBtree::Append(tree, MakeFlat("def"));
CordRepBtreeReader reader;
reader.Init(tree);
EXPECT_THAT(reader.Skip(100), IsEmpty());
EXPECT_THAT(reader.consumed(), Eq(6));
CordRep::Unref(tree);
}
TEST(CordRepBtreeReaderTest, Seek) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
int counts[] = {1, 2, cap, cap * cap, cap * cap + 1, cap * cap * 2 + 17};
for (int count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
for (size_t seek = 0; seek < data.length() - 1; ++seek) {
CordRepBtreeReader reader;
reader.Init(node);
absl::string_view chunk = reader.Seek(seek);
ASSERT_THAT(chunk, Not(IsEmpty()));
ASSERT_THAT(chunk, Eq(data.substr(seek, chunk.length())));
ASSERT_THAT(reader.consumed(), Eq(seek + chunk.length()));
}
CordRep::Unref(node);
}
}
TEST(CordRepBtreeReaderTest, SeekBeyondLength) {
CordRepBtree* tree = CordRepBtree::Create(MakeFlat("abc"));
tree = CordRepBtree::Append(tree, MakeFlat("def"));
CordRepBtreeReader reader;
reader.Init(tree);
EXPECT_THAT(reader.Seek(6), IsEmpty());
EXPECT_THAT(reader.consumed(), Eq(6));
EXPECT_THAT(reader.Seek(100), IsEmpty());
EXPECT_THAT(reader.consumed(), Eq(6));
CordRep::Unref(tree);
}
TEST(CordRepBtreeReaderTest, Read) {
std::string data = "abcdefghijklmno";
std::vector<CordRep*> flats = CreateFlatsFromString(data, 5);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
CordRep* tree;
CordRepBtreeReader reader;
absl::string_view chunk;
// Read zero bytes
chunk = reader.Init(node);
chunk = reader.Read(0, chunk.length(), tree);
EXPECT_THAT(tree, Eq(nullptr));
EXPECT_THAT(chunk, Eq("abcde"));
EXPECT_THAT(reader.consumed(), Eq(5));
EXPECT_THAT(reader.Next(), Eq("fghij"));
// Read in full
chunk = reader.Init(node);
chunk = reader.Read(15, chunk.length(), tree);
EXPECT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("abcdefghijklmno"));
EXPECT_THAT(chunk, Eq(""));
EXPECT_THAT(reader.consumed(), Eq(15));
CordRep::Unref(tree);
// Read < chunk bytes
chunk = reader.Init(node);
chunk = reader.Read(3, chunk.length(), tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("abc"));
EXPECT_THAT(chunk, Eq("de"));
EXPECT_THAT(reader.consumed(), Eq(5));
EXPECT_THAT(reader.Next(), Eq("fghij"));
CordRep::Unref(tree);
// Read < chunk bytes at offset
chunk = reader.Init(node);
chunk = reader.Read(2, chunk.length() - 2, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("cd"));
EXPECT_THAT(chunk, Eq("e"));
EXPECT_THAT(reader.consumed(), Eq(5));
EXPECT_THAT(reader.Next(), Eq("fghij"));
CordRep::Unref(tree);
// Read from consumed chunk
chunk = reader.Init(node);
chunk = reader.Read(3, 0, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("fgh"));
EXPECT_THAT(chunk, Eq("ij"));
EXPECT_THAT(reader.consumed(), Eq(10));
EXPECT_THAT(reader.Next(), Eq("klmno"));
CordRep::Unref(tree);
// Read across chunks
chunk = reader.Init(node);
chunk = reader.Read(12, chunk.length() - 2, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("cdefghijklmn"));
EXPECT_THAT(chunk, Eq("o"));
EXPECT_THAT(reader.consumed(), Eq(15));
CordRep::Unref(tree);
// Read across chunks landing on exact edge boundary
chunk = reader.Init(node);
chunk = reader.Read(10 - 2, chunk.length() - 2, tree);
ASSERT_THAT(tree, Ne(nullptr));
EXPECT_THAT(CordToString(tree), Eq("cdefghij"));
EXPECT_THAT(chunk, Eq("klmno"));
EXPECT_THAT(reader.consumed(), Eq(15));
CordRep::Unref(tree);
CordRep::Unref(node);
}
TEST(CordRepBtreeReaderTest, ReadExhaustive) {
constexpr size_t kChars = 3;
const size_t cap = CordRepBtree::kMaxCapacity;
int counts[] = {1, 2, cap, cap * cap + 1, cap * cap * cap * 2 + 17};
for (int count : counts) {
std::string data = CreateRandomString(count * kChars);
std::vector<CordRep*> flats = CreateFlatsFromString(data, kChars);
CordRepBtree* node = CordRepBtreeFromFlats(flats);
for (size_t read_size : {kChars - 1, kChars, kChars + 7, cap * cap}) {
CordRepBtreeReader reader;
absl::string_view chunk = reader.Init(node);
// `consumed` tracks the end of last consumed chunk which is the start of
// the next chunk: we always read with `chunk_size = chunk.length()`.
size_t consumed = 0;
size_t remaining = data.length();
while (remaining > 0) {
CordRep* tree;
size_t n = (std::min)(remaining, read_size);
chunk = reader.Read(n, chunk.length(), tree);
EXPECT_THAT(tree, Ne(nullptr));
if (tree) {
EXPECT_THAT(CordToString(tree), Eq(data.substr(consumed, n)));
CordRep::Unref(tree);
}
consumed += n;
remaining -= n;
EXPECT_THAT(reader.consumed(), Eq(consumed + chunk.length()));
if (remaining > 0) {
ASSERT_FALSE(chunk.empty());
ASSERT_THAT(chunk, Eq(data.substr(consumed, chunk.length())));
} else {
ASSERT_TRUE(chunk.empty()) << chunk;
}
}
}
CordRep::Unref(node);
}
}
} // namespace
} // namespace cord_internal
ABSL_NAMESPACE_END
} // namespace absl
| 9,280 | 3,463 |
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "vertex_components.h"
#include "adjacency_matrix.h"
#include <queue>
#include <vector>
template <typename DerivedA, typename DerivedC, typename Derivedcounts>
IGL_INLINE void igl::vertex_components(
const Eigen::SparseCompressedBase<DerivedA> & A,
Eigen::PlainObjectBase<DerivedC> & C,
Eigen::PlainObjectBase<Derivedcounts> & counts)
{
using namespace Eigen;
using namespace std;
assert(A.rows() == A.cols() && "A should be square.");
const size_t n = A.rows();
Array<bool,Dynamic,1> seen = Array<bool,Dynamic,1>::Zero(n,1);
C.resize(n,1);
typename DerivedC::Scalar id = 0;
vector<typename Derivedcounts::Scalar> vcounts;
// breadth first search
for(int k=0; k<A.outerSize(); ++k)
{
if(seen(k))
{
continue;
}
queue<int> Q;
Q.push(k);
vcounts.push_back(0);
while(!Q.empty())
{
const int f = Q.front();
Q.pop();
if(seen(f))
{
continue;
}
seen(f) = true;
C(f,0) = id;
vcounts[id]++;
// Iterate over inside
for(typename DerivedA::InnerIterator it (A,f); it; ++it)
{
const int g = it.index();
if(!seen(g) && it.value())
{
Q.push(g);
}
}
}
id++;
}
assert((size_t) id == vcounts.size());
const size_t ncc = vcounts.size();
assert((size_t)C.maxCoeff()+1 == ncc);
counts.resize(ncc,1);
for(size_t i = 0;i<ncc;i++)
{
counts(i) = vcounts[i];
}
}
template <typename DerivedA, typename DerivedC>
IGL_INLINE void igl::vertex_components(
const Eigen::SparseCompressedBase<DerivedA> & A,
Eigen::PlainObjectBase<DerivedC> & C)
{
Eigen::VectorXi counts;
return vertex_components(A,C,counts);
}
template <typename DerivedF, typename DerivedC>
IGL_INLINE void igl::vertex_components(
const Eigen::MatrixBase<DerivedF> & F,
Eigen::PlainObjectBase<DerivedC> & C)
{
Eigen::SparseMatrix<typename DerivedC::Scalar> A;
adjacency_matrix(F,A);
return vertex_components(A,C);
}
#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
// generated by autoexplicit.sh
template void igl::vertex_components<Eigen::SparseMatrix<bool, 0, int>, Eigen::Array<int, -1, 1, 0, -1, 1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<bool, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Array<int, -1, 1, 0, -1, 1> >&);
template void igl::vertex_components<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::vertex_components<Eigen::SparseMatrix<int, 0, int>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<int, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&);
template void igl::vertex_components<Eigen::SparseMatrix<int, 0, int>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<int, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
template void igl::vertex_components<Eigen::SparseMatrix<double, 0, int>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::SparseCompressedBase<Eigen::SparseMatrix<double, 0, int>> const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
template void igl::vertex_components<Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1> >(Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&);
#endif
| 4,020 | 1,654 |
// Copyright 2016 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.
//
// This file is auto-generated from
// ui/gl/generate_bindings.py
// It's formatted by clang-format using chromium coding style:
// clang-format -i -style=chromium filename
// DO NOT EDIT!
#include <string>
#include "base/trace_event/trace_event.h"
#include "ui/gl/gl_bindings.h"
#include "ui/gl/gl_context.h"
#include "ui/gl/gl_enums.h"
#include "ui/gl/gl_glx_api_implementation.h"
#include "ui/gl/gl_implementation.h"
#include "ui/gl/gl_version_info.h"
namespace gl {
DriverGLX g_driver_glx; // Exists in .bss
void DriverGLX::InitializeStaticBindings() {
// Ensure struct has been zero-initialized.
char* this_bytes = reinterpret_cast<char*>(this);
DCHECK(this_bytes[0] == 0);
DCHECK(memcmp(this_bytes, this_bytes + 1, sizeof(*this) - 1) == 0);
fn.glXChooseFBConfigFn = reinterpret_cast<glXChooseFBConfigProc>(
GetGLProcAddress("glXChooseFBConfig"));
fn.glXChooseVisualFn = reinterpret_cast<glXChooseVisualProc>(
GetGLProcAddress("glXChooseVisual"));
fn.glXCopyContextFn =
reinterpret_cast<glXCopyContextProc>(GetGLProcAddress("glXCopyContext"));
fn.glXCreateContextFn = reinterpret_cast<glXCreateContextProc>(
GetGLProcAddress("glXCreateContext"));
fn.glXCreateGLXPixmapFn = reinterpret_cast<glXCreateGLXPixmapProc>(
GetGLProcAddress("glXCreateGLXPixmap"));
fn.glXCreateNewContextFn = reinterpret_cast<glXCreateNewContextProc>(
GetGLProcAddress("glXCreateNewContext"));
fn.glXCreatePbufferFn = reinterpret_cast<glXCreatePbufferProc>(
GetGLProcAddress("glXCreatePbuffer"));
fn.glXCreatePixmapFn = reinterpret_cast<glXCreatePixmapProc>(
GetGLProcAddress("glXCreatePixmap"));
fn.glXCreateWindowFn = reinterpret_cast<glXCreateWindowProc>(
GetGLProcAddress("glXCreateWindow"));
fn.glXDestroyContextFn = reinterpret_cast<glXDestroyContextProc>(
GetGLProcAddress("glXDestroyContext"));
fn.glXDestroyGLXPixmapFn = reinterpret_cast<glXDestroyGLXPixmapProc>(
GetGLProcAddress("glXDestroyGLXPixmap"));
fn.glXDestroyPbufferFn = reinterpret_cast<glXDestroyPbufferProc>(
GetGLProcAddress("glXDestroyPbuffer"));
fn.glXDestroyPixmapFn = reinterpret_cast<glXDestroyPixmapProc>(
GetGLProcAddress("glXDestroyPixmap"));
fn.glXDestroyWindowFn = reinterpret_cast<glXDestroyWindowProc>(
GetGLProcAddress("glXDestroyWindow"));
fn.glXGetClientStringFn = reinterpret_cast<glXGetClientStringProc>(
GetGLProcAddress("glXGetClientString"));
fn.glXGetConfigFn =
reinterpret_cast<glXGetConfigProc>(GetGLProcAddress("glXGetConfig"));
fn.glXGetCurrentContextFn = reinterpret_cast<glXGetCurrentContextProc>(
GetGLProcAddress("glXGetCurrentContext"));
fn.glXGetCurrentDisplayFn = reinterpret_cast<glXGetCurrentDisplayProc>(
GetGLProcAddress("glXGetCurrentDisplay"));
fn.glXGetCurrentDrawableFn = reinterpret_cast<glXGetCurrentDrawableProc>(
GetGLProcAddress("glXGetCurrentDrawable"));
fn.glXGetCurrentReadDrawableFn =
reinterpret_cast<glXGetCurrentReadDrawableProc>(
GetGLProcAddress("glXGetCurrentReadDrawable"));
fn.glXGetFBConfigAttribFn = reinterpret_cast<glXGetFBConfigAttribProc>(
GetGLProcAddress("glXGetFBConfigAttrib"));
fn.glXGetFBConfigsFn = reinterpret_cast<glXGetFBConfigsProc>(
GetGLProcAddress("glXGetFBConfigs"));
fn.glXGetSelectedEventFn = reinterpret_cast<glXGetSelectedEventProc>(
GetGLProcAddress("glXGetSelectedEvent"));
fn.glXGetVisualFromFBConfigFn =
reinterpret_cast<glXGetVisualFromFBConfigProc>(
GetGLProcAddress("glXGetVisualFromFBConfig"));
fn.glXIsDirectFn =
reinterpret_cast<glXIsDirectProc>(GetGLProcAddress("glXIsDirect"));
fn.glXMakeContextCurrentFn = reinterpret_cast<glXMakeContextCurrentProc>(
GetGLProcAddress("glXMakeContextCurrent"));
fn.glXMakeCurrentFn =
reinterpret_cast<glXMakeCurrentProc>(GetGLProcAddress("glXMakeCurrent"));
fn.glXQueryContextFn = reinterpret_cast<glXQueryContextProc>(
GetGLProcAddress("glXQueryContext"));
fn.glXQueryDrawableFn = reinterpret_cast<glXQueryDrawableProc>(
GetGLProcAddress("glXQueryDrawable"));
fn.glXQueryExtensionFn = reinterpret_cast<glXQueryExtensionProc>(
GetGLProcAddress("glXQueryExtension"));
fn.glXQueryExtensionsStringFn =
reinterpret_cast<glXQueryExtensionsStringProc>(
GetGLProcAddress("glXQueryExtensionsString"));
fn.glXQueryServerStringFn = reinterpret_cast<glXQueryServerStringProc>(
GetGLProcAddress("glXQueryServerString"));
fn.glXQueryVersionFn = reinterpret_cast<glXQueryVersionProc>(
GetGLProcAddress("glXQueryVersion"));
fn.glXSelectEventFn =
reinterpret_cast<glXSelectEventProc>(GetGLProcAddress("glXSelectEvent"));
fn.glXSwapBuffersFn =
reinterpret_cast<glXSwapBuffersProc>(GetGLProcAddress("glXSwapBuffers"));
fn.glXUseXFontFn =
reinterpret_cast<glXUseXFontProc>(GetGLProcAddress("glXUseXFont"));
fn.glXWaitGLFn =
reinterpret_cast<glXWaitGLProc>(GetGLProcAddress("glXWaitGL"));
fn.glXWaitXFn = reinterpret_cast<glXWaitXProc>(GetGLProcAddress("glXWaitX"));
}
void DriverGLX::InitializeExtensionBindings() {
std::string platform_extensions(GetPlatformExtensions());
ExtensionSet extensions(MakeExtensionSet(platform_extensions));
ALLOW_UNUSED_LOCAL(extensions);
ext.b_GLX_ARB_create_context =
HasExtension(extensions, "GLX_ARB_create_context");
ext.b_GLX_EXT_swap_control = HasExtension(extensions, "GLX_EXT_swap_control");
ext.b_GLX_EXT_texture_from_pixmap =
HasExtension(extensions, "GLX_EXT_texture_from_pixmap");
ext.b_GLX_MESA_copy_sub_buffer =
HasExtension(extensions, "GLX_MESA_copy_sub_buffer");
ext.b_GLX_MESA_swap_control =
HasExtension(extensions, "GLX_MESA_swap_control");
ext.b_GLX_OML_sync_control = HasExtension(extensions, "GLX_OML_sync_control");
ext.b_GLX_SGIX_fbconfig = HasExtension(extensions, "GLX_SGIX_fbconfig");
ext.b_GLX_SGI_video_sync = HasExtension(extensions, "GLX_SGI_video_sync");
if (ext.b_GLX_EXT_texture_from_pixmap) {
fn.glXBindTexImageEXTFn = reinterpret_cast<glXBindTexImageEXTProc>(
GetGLProcAddress("glXBindTexImageEXT"));
}
if (ext.b_GLX_MESA_copy_sub_buffer) {
fn.glXCopySubBufferMESAFn = reinterpret_cast<glXCopySubBufferMESAProc>(
GetGLProcAddress("glXCopySubBufferMESA"));
}
if (ext.b_GLX_ARB_create_context) {
fn.glXCreateContextAttribsARBFn =
reinterpret_cast<glXCreateContextAttribsARBProc>(
GetGLProcAddress("glXCreateContextAttribsARB"));
}
if (ext.b_GLX_SGIX_fbconfig) {
fn.glXGetFBConfigFromVisualSGIXFn =
reinterpret_cast<glXGetFBConfigFromVisualSGIXProc>(
GetGLProcAddress("glXGetFBConfigFromVisualSGIX"));
}
if (ext.b_GLX_OML_sync_control) {
fn.glXGetMscRateOMLFn = reinterpret_cast<glXGetMscRateOMLProc>(
GetGLProcAddress("glXGetMscRateOML"));
}
if (ext.b_GLX_OML_sync_control) {
fn.glXGetSyncValuesOMLFn = reinterpret_cast<glXGetSyncValuesOMLProc>(
GetGLProcAddress("glXGetSyncValuesOML"));
}
if (ext.b_GLX_EXT_texture_from_pixmap) {
fn.glXReleaseTexImageEXTFn = reinterpret_cast<glXReleaseTexImageEXTProc>(
GetGLProcAddress("glXReleaseTexImageEXT"));
}
if (ext.b_GLX_EXT_swap_control) {
fn.glXSwapIntervalEXTFn = reinterpret_cast<glXSwapIntervalEXTProc>(
GetGLProcAddress("glXSwapIntervalEXT"));
}
if (ext.b_GLX_MESA_swap_control) {
fn.glXSwapIntervalMESAFn = reinterpret_cast<glXSwapIntervalMESAProc>(
GetGLProcAddress("glXSwapIntervalMESA"));
}
if (ext.b_GLX_SGI_video_sync) {
fn.glXWaitVideoSyncSGIFn = reinterpret_cast<glXWaitVideoSyncSGIProc>(
GetGLProcAddress("glXWaitVideoSyncSGI"));
}
}
void DriverGLX::ClearBindings() {
memset(this, 0, sizeof(*this));
}
void GLXApiBase::glXBindTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer,
int* attribList) {
driver_->fn.glXBindTexImageEXTFn(dpy, drawable, buffer, attribList);
}
GLXFBConfig* GLXApiBase::glXChooseFBConfigFn(Display* dpy,
int screen,
const int* attribList,
int* nitems) {
return driver_->fn.glXChooseFBConfigFn(dpy, screen, attribList, nitems);
}
XVisualInfo* GLXApiBase::glXChooseVisualFn(Display* dpy,
int screen,
int* attribList) {
return driver_->fn.glXChooseVisualFn(dpy, screen, attribList);
}
void GLXApiBase::glXCopyContextFn(Display* dpy,
GLXContext src,
GLXContext dst,
unsigned long mask) {
driver_->fn.glXCopyContextFn(dpy, src, dst, mask);
}
void GLXApiBase::glXCopySubBufferMESAFn(Display* dpy,
GLXDrawable drawable,
int x,
int y,
int width,
int height) {
driver_->fn.glXCopySubBufferMESAFn(dpy, drawable, x, y, width, height);
}
GLXContext GLXApiBase::glXCreateContextFn(Display* dpy,
XVisualInfo* vis,
GLXContext shareList,
int direct) {
return driver_->fn.glXCreateContextFn(dpy, vis, shareList, direct);
}
GLXContext GLXApiBase::glXCreateContextAttribsARBFn(Display* dpy,
GLXFBConfig config,
GLXContext share_context,
int direct,
const int* attrib_list) {
return driver_->fn.glXCreateContextAttribsARBFn(dpy, config, share_context,
direct, attrib_list);
}
GLXPixmap GLXApiBase::glXCreateGLXPixmapFn(Display* dpy,
XVisualInfo* visual,
Pixmap pixmap) {
return driver_->fn.glXCreateGLXPixmapFn(dpy, visual, pixmap);
}
GLXContext GLXApiBase::glXCreateNewContextFn(Display* dpy,
GLXFBConfig config,
int renderType,
GLXContext shareList,
int direct) {
return driver_->fn.glXCreateNewContextFn(dpy, config, renderType, shareList,
direct);
}
GLXPbuffer GLXApiBase::glXCreatePbufferFn(Display* dpy,
GLXFBConfig config,
const int* attribList) {
return driver_->fn.glXCreatePbufferFn(dpy, config, attribList);
}
GLXPixmap GLXApiBase::glXCreatePixmapFn(Display* dpy,
GLXFBConfig config,
Pixmap pixmap,
const int* attribList) {
return driver_->fn.glXCreatePixmapFn(dpy, config, pixmap, attribList);
}
GLXWindow GLXApiBase::glXCreateWindowFn(Display* dpy,
GLXFBConfig config,
Window win,
const int* attribList) {
return driver_->fn.glXCreateWindowFn(dpy, config, win, attribList);
}
void GLXApiBase::glXDestroyContextFn(Display* dpy, GLXContext ctx) {
driver_->fn.glXDestroyContextFn(dpy, ctx);
}
void GLXApiBase::glXDestroyGLXPixmapFn(Display* dpy, GLXPixmap pixmap) {
driver_->fn.glXDestroyGLXPixmapFn(dpy, pixmap);
}
void GLXApiBase::glXDestroyPbufferFn(Display* dpy, GLXPbuffer pbuf) {
driver_->fn.glXDestroyPbufferFn(dpy, pbuf);
}
void GLXApiBase::glXDestroyPixmapFn(Display* dpy, GLXPixmap pixmap) {
driver_->fn.glXDestroyPixmapFn(dpy, pixmap);
}
void GLXApiBase::glXDestroyWindowFn(Display* dpy, GLXWindow window) {
driver_->fn.glXDestroyWindowFn(dpy, window);
}
const char* GLXApiBase::glXGetClientStringFn(Display* dpy, int name) {
return driver_->fn.glXGetClientStringFn(dpy, name);
}
int GLXApiBase::glXGetConfigFn(Display* dpy,
XVisualInfo* visual,
int attrib,
int* value) {
return driver_->fn.glXGetConfigFn(dpy, visual, attrib, value);
}
GLXContext GLXApiBase::glXGetCurrentContextFn(void) {
return driver_->fn.glXGetCurrentContextFn();
}
Display* GLXApiBase::glXGetCurrentDisplayFn(void) {
return driver_->fn.glXGetCurrentDisplayFn();
}
GLXDrawable GLXApiBase::glXGetCurrentDrawableFn(void) {
return driver_->fn.glXGetCurrentDrawableFn();
}
GLXDrawable GLXApiBase::glXGetCurrentReadDrawableFn(void) {
return driver_->fn.glXGetCurrentReadDrawableFn();
}
int GLXApiBase::glXGetFBConfigAttribFn(Display* dpy,
GLXFBConfig config,
int attribute,
int* value) {
return driver_->fn.glXGetFBConfigAttribFn(dpy, config, attribute, value);
}
GLXFBConfig GLXApiBase::glXGetFBConfigFromVisualSGIXFn(
Display* dpy,
XVisualInfo* visualInfo) {
return driver_->fn.glXGetFBConfigFromVisualSGIXFn(dpy, visualInfo);
}
GLXFBConfig* GLXApiBase::glXGetFBConfigsFn(Display* dpy,
int screen,
int* nelements) {
return driver_->fn.glXGetFBConfigsFn(dpy, screen, nelements);
}
bool GLXApiBase::glXGetMscRateOMLFn(Display* dpy,
GLXDrawable drawable,
int32_t* numerator,
int32_t* denominator) {
return driver_->fn.glXGetMscRateOMLFn(dpy, drawable, numerator, denominator);
}
void GLXApiBase::glXGetSelectedEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long* mask) {
driver_->fn.glXGetSelectedEventFn(dpy, drawable, mask);
}
bool GLXApiBase::glXGetSyncValuesOMLFn(Display* dpy,
GLXDrawable drawable,
int64_t* ust,
int64_t* msc,
int64_t* sbc) {
return driver_->fn.glXGetSyncValuesOMLFn(dpy, drawable, ust, msc, sbc);
}
XVisualInfo* GLXApiBase::glXGetVisualFromFBConfigFn(Display* dpy,
GLXFBConfig config) {
return driver_->fn.glXGetVisualFromFBConfigFn(dpy, config);
}
int GLXApiBase::glXIsDirectFn(Display* dpy, GLXContext ctx) {
return driver_->fn.glXIsDirectFn(dpy, ctx);
}
int GLXApiBase::glXMakeContextCurrentFn(Display* dpy,
GLXDrawable draw,
GLXDrawable read,
GLXContext ctx) {
return driver_->fn.glXMakeContextCurrentFn(dpy, draw, read, ctx);
}
int GLXApiBase::glXMakeCurrentFn(Display* dpy,
GLXDrawable drawable,
GLXContext ctx) {
return driver_->fn.glXMakeCurrentFn(dpy, drawable, ctx);
}
int GLXApiBase::glXQueryContextFn(Display* dpy,
GLXContext ctx,
int attribute,
int* value) {
return driver_->fn.glXQueryContextFn(dpy, ctx, attribute, value);
}
void GLXApiBase::glXQueryDrawableFn(Display* dpy,
GLXDrawable draw,
int attribute,
unsigned int* value) {
driver_->fn.glXQueryDrawableFn(dpy, draw, attribute, value);
}
int GLXApiBase::glXQueryExtensionFn(Display* dpy, int* errorb, int* event) {
return driver_->fn.glXQueryExtensionFn(dpy, errorb, event);
}
const char* GLXApiBase::glXQueryExtensionsStringFn(Display* dpy, int screen) {
return driver_->fn.glXQueryExtensionsStringFn(dpy, screen);
}
const char* GLXApiBase::glXQueryServerStringFn(Display* dpy,
int screen,
int name) {
return driver_->fn.glXQueryServerStringFn(dpy, screen, name);
}
int GLXApiBase::glXQueryVersionFn(Display* dpy, int* maj, int* min) {
return driver_->fn.glXQueryVersionFn(dpy, maj, min);
}
void GLXApiBase::glXReleaseTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer) {
driver_->fn.glXReleaseTexImageEXTFn(dpy, drawable, buffer);
}
void GLXApiBase::glXSelectEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long mask) {
driver_->fn.glXSelectEventFn(dpy, drawable, mask);
}
void GLXApiBase::glXSwapBuffersFn(Display* dpy, GLXDrawable drawable) {
driver_->fn.glXSwapBuffersFn(dpy, drawable);
}
void GLXApiBase::glXSwapIntervalEXTFn(Display* dpy,
GLXDrawable drawable,
int interval) {
driver_->fn.glXSwapIntervalEXTFn(dpy, drawable, interval);
}
void GLXApiBase::glXSwapIntervalMESAFn(unsigned int interval) {
driver_->fn.glXSwapIntervalMESAFn(interval);
}
void GLXApiBase::glXUseXFontFn(Font font, int first, int count, int list) {
driver_->fn.glXUseXFontFn(font, first, count, list);
}
void GLXApiBase::glXWaitGLFn(void) {
driver_->fn.glXWaitGLFn();
}
int GLXApiBase::glXWaitVideoSyncSGIFn(int divisor,
int remainder,
unsigned int* count) {
return driver_->fn.glXWaitVideoSyncSGIFn(divisor, remainder, count);
}
void GLXApiBase::glXWaitXFn(void) {
driver_->fn.glXWaitXFn();
}
void TraceGLXApi::glXBindTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer,
int* attribList) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXBindTexImageEXT")
glx_api_->glXBindTexImageEXTFn(dpy, drawable, buffer, attribList);
}
GLXFBConfig* TraceGLXApi::glXChooseFBConfigFn(Display* dpy,
int screen,
const int* attribList,
int* nitems) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXChooseFBConfig")
return glx_api_->glXChooseFBConfigFn(dpy, screen, attribList, nitems);
}
XVisualInfo* TraceGLXApi::glXChooseVisualFn(Display* dpy,
int screen,
int* attribList) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXChooseVisual")
return glx_api_->glXChooseVisualFn(dpy, screen, attribList);
}
void TraceGLXApi::glXCopyContextFn(Display* dpy,
GLXContext src,
GLXContext dst,
unsigned long mask) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCopyContext")
glx_api_->glXCopyContextFn(dpy, src, dst, mask);
}
void TraceGLXApi::glXCopySubBufferMESAFn(Display* dpy,
GLXDrawable drawable,
int x,
int y,
int width,
int height) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCopySubBufferMESA")
glx_api_->glXCopySubBufferMESAFn(dpy, drawable, x, y, width, height);
}
GLXContext TraceGLXApi::glXCreateContextFn(Display* dpy,
XVisualInfo* vis,
GLXContext shareList,
int direct) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreateContext")
return glx_api_->glXCreateContextFn(dpy, vis, shareList, direct);
}
GLXContext TraceGLXApi::glXCreateContextAttribsARBFn(Display* dpy,
GLXFBConfig config,
GLXContext share_context,
int direct,
const int* attrib_list) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreateContextAttribsARB")
return glx_api_->glXCreateContextAttribsARBFn(dpy, config, share_context,
direct, attrib_list);
}
GLXPixmap TraceGLXApi::glXCreateGLXPixmapFn(Display* dpy,
XVisualInfo* visual,
Pixmap pixmap) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreateGLXPixmap")
return glx_api_->glXCreateGLXPixmapFn(dpy, visual, pixmap);
}
GLXContext TraceGLXApi::glXCreateNewContextFn(Display* dpy,
GLXFBConfig config,
int renderType,
GLXContext shareList,
int direct) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreateNewContext")
return glx_api_->glXCreateNewContextFn(dpy, config, renderType, shareList,
direct);
}
GLXPbuffer TraceGLXApi::glXCreatePbufferFn(Display* dpy,
GLXFBConfig config,
const int* attribList) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreatePbuffer")
return glx_api_->glXCreatePbufferFn(dpy, config, attribList);
}
GLXPixmap TraceGLXApi::glXCreatePixmapFn(Display* dpy,
GLXFBConfig config,
Pixmap pixmap,
const int* attribList) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreatePixmap")
return glx_api_->glXCreatePixmapFn(dpy, config, pixmap, attribList);
}
GLXWindow TraceGLXApi::glXCreateWindowFn(Display* dpy,
GLXFBConfig config,
Window win,
const int* attribList) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXCreateWindow")
return glx_api_->glXCreateWindowFn(dpy, config, win, attribList);
}
void TraceGLXApi::glXDestroyContextFn(Display* dpy, GLXContext ctx) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXDestroyContext")
glx_api_->glXDestroyContextFn(dpy, ctx);
}
void TraceGLXApi::glXDestroyGLXPixmapFn(Display* dpy, GLXPixmap pixmap) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXDestroyGLXPixmap")
glx_api_->glXDestroyGLXPixmapFn(dpy, pixmap);
}
void TraceGLXApi::glXDestroyPbufferFn(Display* dpy, GLXPbuffer pbuf) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXDestroyPbuffer")
glx_api_->glXDestroyPbufferFn(dpy, pbuf);
}
void TraceGLXApi::glXDestroyPixmapFn(Display* dpy, GLXPixmap pixmap) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXDestroyPixmap")
glx_api_->glXDestroyPixmapFn(dpy, pixmap);
}
void TraceGLXApi::glXDestroyWindowFn(Display* dpy, GLXWindow window) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXDestroyWindow")
glx_api_->glXDestroyWindowFn(dpy, window);
}
const char* TraceGLXApi::glXGetClientStringFn(Display* dpy, int name) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetClientString")
return glx_api_->glXGetClientStringFn(dpy, name);
}
int TraceGLXApi::glXGetConfigFn(Display* dpy,
XVisualInfo* visual,
int attrib,
int* value) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetConfig")
return glx_api_->glXGetConfigFn(dpy, visual, attrib, value);
}
GLXContext TraceGLXApi::glXGetCurrentContextFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetCurrentContext")
return glx_api_->glXGetCurrentContextFn();
}
Display* TraceGLXApi::glXGetCurrentDisplayFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetCurrentDisplay")
return glx_api_->glXGetCurrentDisplayFn();
}
GLXDrawable TraceGLXApi::glXGetCurrentDrawableFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetCurrentDrawable")
return glx_api_->glXGetCurrentDrawableFn();
}
GLXDrawable TraceGLXApi::glXGetCurrentReadDrawableFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetCurrentReadDrawable")
return glx_api_->glXGetCurrentReadDrawableFn();
}
int TraceGLXApi::glXGetFBConfigAttribFn(Display* dpy,
GLXFBConfig config,
int attribute,
int* value) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetFBConfigAttrib")
return glx_api_->glXGetFBConfigAttribFn(dpy, config, attribute, value);
}
GLXFBConfig TraceGLXApi::glXGetFBConfigFromVisualSGIXFn(
Display* dpy,
XVisualInfo* visualInfo) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu",
"TraceGLAPI::glXGetFBConfigFromVisualSGIX")
return glx_api_->glXGetFBConfigFromVisualSGIXFn(dpy, visualInfo);
}
GLXFBConfig* TraceGLXApi::glXGetFBConfigsFn(Display* dpy,
int screen,
int* nelements) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetFBConfigs")
return glx_api_->glXGetFBConfigsFn(dpy, screen, nelements);
}
bool TraceGLXApi::glXGetMscRateOMLFn(Display* dpy,
GLXDrawable drawable,
int32_t* numerator,
int32_t* denominator) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetMscRateOML")
return glx_api_->glXGetMscRateOMLFn(dpy, drawable, numerator, denominator);
}
void TraceGLXApi::glXGetSelectedEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long* mask) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetSelectedEvent")
glx_api_->glXGetSelectedEventFn(dpy, drawable, mask);
}
bool TraceGLXApi::glXGetSyncValuesOMLFn(Display* dpy,
GLXDrawable drawable,
int64_t* ust,
int64_t* msc,
int64_t* sbc) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetSyncValuesOML")
return glx_api_->glXGetSyncValuesOMLFn(dpy, drawable, ust, msc, sbc);
}
XVisualInfo* TraceGLXApi::glXGetVisualFromFBConfigFn(Display* dpy,
GLXFBConfig config) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXGetVisualFromFBConfig")
return glx_api_->glXGetVisualFromFBConfigFn(dpy, config);
}
int TraceGLXApi::glXIsDirectFn(Display* dpy, GLXContext ctx) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXIsDirect")
return glx_api_->glXIsDirectFn(dpy, ctx);
}
int TraceGLXApi::glXMakeContextCurrentFn(Display* dpy,
GLXDrawable draw,
GLXDrawable read,
GLXContext ctx) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXMakeContextCurrent")
return glx_api_->glXMakeContextCurrentFn(dpy, draw, read, ctx);
}
int TraceGLXApi::glXMakeCurrentFn(Display* dpy,
GLXDrawable drawable,
GLXContext ctx) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXMakeCurrent")
return glx_api_->glXMakeCurrentFn(dpy, drawable, ctx);
}
int TraceGLXApi::glXQueryContextFn(Display* dpy,
GLXContext ctx,
int attribute,
int* value) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryContext")
return glx_api_->glXQueryContextFn(dpy, ctx, attribute, value);
}
void TraceGLXApi::glXQueryDrawableFn(Display* dpy,
GLXDrawable draw,
int attribute,
unsigned int* value) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryDrawable")
glx_api_->glXQueryDrawableFn(dpy, draw, attribute, value);
}
int TraceGLXApi::glXQueryExtensionFn(Display* dpy, int* errorb, int* event) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryExtension")
return glx_api_->glXQueryExtensionFn(dpy, errorb, event);
}
const char* TraceGLXApi::glXQueryExtensionsStringFn(Display* dpy, int screen) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryExtensionsString")
return glx_api_->glXQueryExtensionsStringFn(dpy, screen);
}
const char* TraceGLXApi::glXQueryServerStringFn(Display* dpy,
int screen,
int name) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryServerString")
return glx_api_->glXQueryServerStringFn(dpy, screen, name);
}
int TraceGLXApi::glXQueryVersionFn(Display* dpy, int* maj, int* min) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXQueryVersion")
return glx_api_->glXQueryVersionFn(dpy, maj, min);
}
void TraceGLXApi::glXReleaseTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXReleaseTexImageEXT")
glx_api_->glXReleaseTexImageEXTFn(dpy, drawable, buffer);
}
void TraceGLXApi::glXSelectEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long mask) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXSelectEvent")
glx_api_->glXSelectEventFn(dpy, drawable, mask);
}
void TraceGLXApi::glXSwapBuffersFn(Display* dpy, GLXDrawable drawable) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXSwapBuffers")
glx_api_->glXSwapBuffersFn(dpy, drawable);
}
void TraceGLXApi::glXSwapIntervalEXTFn(Display* dpy,
GLXDrawable drawable,
int interval) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXSwapIntervalEXT")
glx_api_->glXSwapIntervalEXTFn(dpy, drawable, interval);
}
void TraceGLXApi::glXSwapIntervalMESAFn(unsigned int interval) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXSwapIntervalMESA")
glx_api_->glXSwapIntervalMESAFn(interval);
}
void TraceGLXApi::glXUseXFontFn(Font font, int first, int count, int list) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXUseXFont")
glx_api_->glXUseXFontFn(font, first, count, list);
}
void TraceGLXApi::glXWaitGLFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXWaitGL")
glx_api_->glXWaitGLFn();
}
int TraceGLXApi::glXWaitVideoSyncSGIFn(int divisor,
int remainder,
unsigned int* count) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXWaitVideoSyncSGI")
return glx_api_->glXWaitVideoSyncSGIFn(divisor, remainder, count);
}
void TraceGLXApi::glXWaitXFn(void) {
TRACE_EVENT_BINARY_EFFICIENT0("gpu", "TraceGLAPI::glXWaitX")
glx_api_->glXWaitXFn();
}
void DebugGLXApi::glXBindTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer,
int* attribList) {
GL_SERVICE_LOG("glXBindTexImageEXT"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << buffer << ", "
<< static_cast<const void*>(attribList) << ")");
glx_api_->glXBindTexImageEXTFn(dpy, drawable, buffer, attribList);
}
GLXFBConfig* DebugGLXApi::glXChooseFBConfigFn(Display* dpy,
int screen,
const int* attribList,
int* nitems) {
GL_SERVICE_LOG("glXChooseFBConfig"
<< "(" << static_cast<const void*>(dpy) << ", " << screen
<< ", " << static_cast<const void*>(attribList) << ", "
<< static_cast<const void*>(nitems) << ")");
GLXFBConfig* result =
glx_api_->glXChooseFBConfigFn(dpy, screen, attribList, nitems);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
XVisualInfo* DebugGLXApi::glXChooseVisualFn(Display* dpy,
int screen,
int* attribList) {
GL_SERVICE_LOG("glXChooseVisual"
<< "(" << static_cast<const void*>(dpy) << ", " << screen
<< ", " << static_cast<const void*>(attribList) << ")");
XVisualInfo* result = glx_api_->glXChooseVisualFn(dpy, screen, attribList);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXCopyContextFn(Display* dpy,
GLXContext src,
GLXContext dst,
unsigned long mask) {
GL_SERVICE_LOG("glXCopyContext"
<< "(" << static_cast<const void*>(dpy) << ", " << src << ", "
<< dst << ", " << mask << ")");
glx_api_->glXCopyContextFn(dpy, src, dst, mask);
}
void DebugGLXApi::glXCopySubBufferMESAFn(Display* dpy,
GLXDrawable drawable,
int x,
int y,
int width,
int height) {
GL_SERVICE_LOG("glXCopySubBufferMESA"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << x << ", " << y << ", " << width << ", " << height
<< ")");
glx_api_->glXCopySubBufferMESAFn(dpy, drawable, x, y, width, height);
}
GLXContext DebugGLXApi::glXCreateContextFn(Display* dpy,
XVisualInfo* vis,
GLXContext shareList,
int direct) {
GL_SERVICE_LOG("glXCreateContext"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(vis) << ", " << shareList << ", "
<< direct << ")");
GLXContext result = glx_api_->glXCreateContextFn(dpy, vis, shareList, direct);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXContext DebugGLXApi::glXCreateContextAttribsARBFn(Display* dpy,
GLXFBConfig config,
GLXContext share_context,
int direct,
const int* attrib_list) {
GL_SERVICE_LOG("glXCreateContextAttribsARB"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << share_context << ", " << direct << ", "
<< static_cast<const void*>(attrib_list) << ")");
GLXContext result = glx_api_->glXCreateContextAttribsARBFn(
dpy, config, share_context, direct, attrib_list);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXPixmap DebugGLXApi::glXCreateGLXPixmapFn(Display* dpy,
XVisualInfo* visual,
Pixmap pixmap) {
GL_SERVICE_LOG("glXCreateGLXPixmap"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(visual) << ", " << pixmap << ")");
GLXPixmap result = glx_api_->glXCreateGLXPixmapFn(dpy, visual, pixmap);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXContext DebugGLXApi::glXCreateNewContextFn(Display* dpy,
GLXFBConfig config,
int renderType,
GLXContext shareList,
int direct) {
GL_SERVICE_LOG("glXCreateNewContext"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << renderType << ", " << shareList << ", " << direct
<< ")");
GLXContext result = glx_api_->glXCreateNewContextFn(dpy, config, renderType,
shareList, direct);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXPbuffer DebugGLXApi::glXCreatePbufferFn(Display* dpy,
GLXFBConfig config,
const int* attribList) {
GL_SERVICE_LOG("glXCreatePbuffer"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << static_cast<const void*>(attribList) << ")");
GLXPbuffer result = glx_api_->glXCreatePbufferFn(dpy, config, attribList);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXPixmap DebugGLXApi::glXCreatePixmapFn(Display* dpy,
GLXFBConfig config,
Pixmap pixmap,
const int* attribList) {
GL_SERVICE_LOG("glXCreatePixmap"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << pixmap << ", "
<< static_cast<const void*>(attribList) << ")");
GLXPixmap result =
glx_api_->glXCreatePixmapFn(dpy, config, pixmap, attribList);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXWindow DebugGLXApi::glXCreateWindowFn(Display* dpy,
GLXFBConfig config,
Window win,
const int* attribList) {
GL_SERVICE_LOG("glXCreateWindow"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << win << ", " << static_cast<const void*>(attribList)
<< ")");
GLXWindow result = glx_api_->glXCreateWindowFn(dpy, config, win, attribList);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXDestroyContextFn(Display* dpy, GLXContext ctx) {
GL_SERVICE_LOG("glXDestroyContext"
<< "(" << static_cast<const void*>(dpy) << ", " << ctx << ")");
glx_api_->glXDestroyContextFn(dpy, ctx);
}
void DebugGLXApi::glXDestroyGLXPixmapFn(Display* dpy, GLXPixmap pixmap) {
GL_SERVICE_LOG("glXDestroyGLXPixmap"
<< "(" << static_cast<const void*>(dpy) << ", " << pixmap
<< ")");
glx_api_->glXDestroyGLXPixmapFn(dpy, pixmap);
}
void DebugGLXApi::glXDestroyPbufferFn(Display* dpy, GLXPbuffer pbuf) {
GL_SERVICE_LOG("glXDestroyPbuffer"
<< "(" << static_cast<const void*>(dpy) << ", " << pbuf
<< ")");
glx_api_->glXDestroyPbufferFn(dpy, pbuf);
}
void DebugGLXApi::glXDestroyPixmapFn(Display* dpy, GLXPixmap pixmap) {
GL_SERVICE_LOG("glXDestroyPixmap"
<< "(" << static_cast<const void*>(dpy) << ", " << pixmap
<< ")");
glx_api_->glXDestroyPixmapFn(dpy, pixmap);
}
void DebugGLXApi::glXDestroyWindowFn(Display* dpy, GLXWindow window) {
GL_SERVICE_LOG("glXDestroyWindow"
<< "(" << static_cast<const void*>(dpy) << ", " << window
<< ")");
glx_api_->glXDestroyWindowFn(dpy, window);
}
const char* DebugGLXApi::glXGetClientStringFn(Display* dpy, int name) {
GL_SERVICE_LOG("glXGetClientString"
<< "(" << static_cast<const void*>(dpy) << ", " << name
<< ")");
const char* result = glx_api_->glXGetClientStringFn(dpy, name);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXGetConfigFn(Display* dpy,
XVisualInfo* visual,
int attrib,
int* value) {
GL_SERVICE_LOG("glXGetConfig"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(visual) << ", " << attrib << ", "
<< static_cast<const void*>(value) << ")");
int result = glx_api_->glXGetConfigFn(dpy, visual, attrib, value);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXContext DebugGLXApi::glXGetCurrentContextFn(void) {
GL_SERVICE_LOG("glXGetCurrentContext"
<< "("
<< ")");
GLXContext result = glx_api_->glXGetCurrentContextFn();
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
Display* DebugGLXApi::glXGetCurrentDisplayFn(void) {
GL_SERVICE_LOG("glXGetCurrentDisplay"
<< "("
<< ")");
Display* result = glx_api_->glXGetCurrentDisplayFn();
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXDrawable DebugGLXApi::glXGetCurrentDrawableFn(void) {
GL_SERVICE_LOG("glXGetCurrentDrawable"
<< "("
<< ")");
GLXDrawable result = glx_api_->glXGetCurrentDrawableFn();
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXDrawable DebugGLXApi::glXGetCurrentReadDrawableFn(void) {
GL_SERVICE_LOG("glXGetCurrentReadDrawable"
<< "("
<< ")");
GLXDrawable result = glx_api_->glXGetCurrentReadDrawableFn();
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXGetFBConfigAttribFn(Display* dpy,
GLXFBConfig config,
int attribute,
int* value) {
GL_SERVICE_LOG("glXGetFBConfigAttrib"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ", " << attribute << ", " << static_cast<const void*>(value)
<< ")");
int result = glx_api_->glXGetFBConfigAttribFn(dpy, config, attribute, value);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXFBConfig DebugGLXApi::glXGetFBConfigFromVisualSGIXFn(
Display* dpy,
XVisualInfo* visualInfo) {
GL_SERVICE_LOG("glXGetFBConfigFromVisualSGIX"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(visualInfo) << ")");
GLXFBConfig result =
glx_api_->glXGetFBConfigFromVisualSGIXFn(dpy, visualInfo);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
GLXFBConfig* DebugGLXApi::glXGetFBConfigsFn(Display* dpy,
int screen,
int* nelements) {
GL_SERVICE_LOG("glXGetFBConfigs"
<< "(" << static_cast<const void*>(dpy) << ", " << screen
<< ", " << static_cast<const void*>(nelements) << ")");
GLXFBConfig* result = glx_api_->glXGetFBConfigsFn(dpy, screen, nelements);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
bool DebugGLXApi::glXGetMscRateOMLFn(Display* dpy,
GLXDrawable drawable,
int32_t* numerator,
int32_t* denominator) {
GL_SERVICE_LOG("glXGetMscRateOML"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << static_cast<const void*>(numerator) << ", "
<< static_cast<const void*>(denominator) << ")");
bool result =
glx_api_->glXGetMscRateOMLFn(dpy, drawable, numerator, denominator);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXGetSelectedEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long* mask) {
GL_SERVICE_LOG("glXGetSelectedEvent"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << static_cast<const void*>(mask) << ")");
glx_api_->glXGetSelectedEventFn(dpy, drawable, mask);
}
bool DebugGLXApi::glXGetSyncValuesOMLFn(Display* dpy,
GLXDrawable drawable,
int64_t* ust,
int64_t* msc,
int64_t* sbc) {
GL_SERVICE_LOG("glXGetSyncValuesOML"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << static_cast<const void*>(ust) << ", "
<< static_cast<const void*>(msc) << ", "
<< static_cast<const void*>(sbc) << ")");
bool result = glx_api_->glXGetSyncValuesOMLFn(dpy, drawable, ust, msc, sbc);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
XVisualInfo* DebugGLXApi::glXGetVisualFromFBConfigFn(Display* dpy,
GLXFBConfig config) {
GL_SERVICE_LOG("glXGetVisualFromFBConfig"
<< "(" << static_cast<const void*>(dpy) << ", " << config
<< ")");
XVisualInfo* result = glx_api_->glXGetVisualFromFBConfigFn(dpy, config);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXIsDirectFn(Display* dpy, GLXContext ctx) {
GL_SERVICE_LOG("glXIsDirect"
<< "(" << static_cast<const void*>(dpy) << ", " << ctx << ")");
int result = glx_api_->glXIsDirectFn(dpy, ctx);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXMakeContextCurrentFn(Display* dpy,
GLXDrawable draw,
GLXDrawable read,
GLXContext ctx) {
GL_SERVICE_LOG("glXMakeContextCurrent"
<< "(" << static_cast<const void*>(dpy) << ", " << draw << ", "
<< read << ", " << ctx << ")");
int result = glx_api_->glXMakeContextCurrentFn(dpy, draw, read, ctx);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXMakeCurrentFn(Display* dpy,
GLXDrawable drawable,
GLXContext ctx) {
GL_SERVICE_LOG("glXMakeCurrent"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << ctx << ")");
int result = glx_api_->glXMakeCurrentFn(dpy, drawable, ctx);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXQueryContextFn(Display* dpy,
GLXContext ctx,
int attribute,
int* value) {
GL_SERVICE_LOG("glXQueryContext"
<< "(" << static_cast<const void*>(dpy) << ", " << ctx << ", "
<< attribute << ", " << static_cast<const void*>(value)
<< ")");
int result = glx_api_->glXQueryContextFn(dpy, ctx, attribute, value);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXQueryDrawableFn(Display* dpy,
GLXDrawable draw,
int attribute,
unsigned int* value) {
GL_SERVICE_LOG("glXQueryDrawable"
<< "(" << static_cast<const void*>(dpy) << ", " << draw << ", "
<< attribute << ", " << static_cast<const void*>(value)
<< ")");
glx_api_->glXQueryDrawableFn(dpy, draw, attribute, value);
}
int DebugGLXApi::glXQueryExtensionFn(Display* dpy, int* errorb, int* event) {
GL_SERVICE_LOG("glXQueryExtension"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(errorb) << ", "
<< static_cast<const void*>(event) << ")");
int result = glx_api_->glXQueryExtensionFn(dpy, errorb, event);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
const char* DebugGLXApi::glXQueryExtensionsStringFn(Display* dpy, int screen) {
GL_SERVICE_LOG("glXQueryExtensionsString"
<< "(" << static_cast<const void*>(dpy) << ", " << screen
<< ")");
const char* result = glx_api_->glXQueryExtensionsStringFn(dpy, screen);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
const char* DebugGLXApi::glXQueryServerStringFn(Display* dpy,
int screen,
int name) {
GL_SERVICE_LOG("glXQueryServerString"
<< "(" << static_cast<const void*>(dpy) << ", " << screen
<< ", " << name << ")");
const char* result = glx_api_->glXQueryServerStringFn(dpy, screen, name);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
int DebugGLXApi::glXQueryVersionFn(Display* dpy, int* maj, int* min) {
GL_SERVICE_LOG("glXQueryVersion"
<< "(" << static_cast<const void*>(dpy) << ", "
<< static_cast<const void*>(maj) << ", "
<< static_cast<const void*>(min) << ")");
int result = glx_api_->glXQueryVersionFn(dpy, maj, min);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXReleaseTexImageEXTFn(Display* dpy,
GLXDrawable drawable,
int buffer) {
GL_SERVICE_LOG("glXReleaseTexImageEXT"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << buffer << ")");
glx_api_->glXReleaseTexImageEXTFn(dpy, drawable, buffer);
}
void DebugGLXApi::glXSelectEventFn(Display* dpy,
GLXDrawable drawable,
unsigned long mask) {
GL_SERVICE_LOG("glXSelectEvent"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << mask << ")");
glx_api_->glXSelectEventFn(dpy, drawable, mask);
}
void DebugGLXApi::glXSwapBuffersFn(Display* dpy, GLXDrawable drawable) {
GL_SERVICE_LOG("glXSwapBuffers"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ")");
glx_api_->glXSwapBuffersFn(dpy, drawable);
}
void DebugGLXApi::glXSwapIntervalEXTFn(Display* dpy,
GLXDrawable drawable,
int interval) {
GL_SERVICE_LOG("glXSwapIntervalEXT"
<< "(" << static_cast<const void*>(dpy) << ", " << drawable
<< ", " << interval << ")");
glx_api_->glXSwapIntervalEXTFn(dpy, drawable, interval);
}
void DebugGLXApi::glXSwapIntervalMESAFn(unsigned int interval) {
GL_SERVICE_LOG("glXSwapIntervalMESA"
<< "(" << interval << ")");
glx_api_->glXSwapIntervalMESAFn(interval);
}
void DebugGLXApi::glXUseXFontFn(Font font, int first, int count, int list) {
GL_SERVICE_LOG("glXUseXFont"
<< "(" << font << ", " << first << ", " << count << ", "
<< list << ")");
glx_api_->glXUseXFontFn(font, first, count, list);
}
void DebugGLXApi::glXWaitGLFn(void) {
GL_SERVICE_LOG("glXWaitGL"
<< "("
<< ")");
glx_api_->glXWaitGLFn();
}
int DebugGLXApi::glXWaitVideoSyncSGIFn(int divisor,
int remainder,
unsigned int* count) {
GL_SERVICE_LOG("glXWaitVideoSyncSGI"
<< "(" << divisor << ", " << remainder << ", "
<< static_cast<const void*>(count) << ")");
int result = glx_api_->glXWaitVideoSyncSGIFn(divisor, remainder, count);
GL_SERVICE_LOG("GL_RESULT: " << result);
return result;
}
void DebugGLXApi::glXWaitXFn(void) {
GL_SERVICE_LOG("glXWaitX"
<< "("
<< ")");
glx_api_->glXWaitXFn();
}
} // namespace gl
| 52,948 | 17,060 |
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// GraphControl.cpp : implementation file
//
#include "stdafx.h"
#include "vmpi_browser_job_watch.h"
#include "GraphControl.h"
#include "mathlib/mathlib.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CGraphControl
CGraphControl::CGraphControl()
{
}
CGraphControl::~CGraphControl()
{
}
BEGIN_MESSAGE_MAP(CGraphControl, CWnd)
//{{AFX_MSG_MAP(CGraphControl)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
void CGraphControl::Clear()
{
CRect rcClient;
GetClientRect( rcClient );
CDC *pDC = GetDC();
CBrush brush( RGB( 0, 0, 0 ) );
CBrush *pOldBrush = pDC->SelectObject( &brush );
pDC->Rectangle( 0, 0, rcClient.Width(), rcClient.Height() );
pDC->SelectObject( pOldBrush );
ReleaseDC( pDC );
}
void CGraphControl::Render( CDC *pDC )
{
// Clear the background.
CRect rcClient;
GetClientRect( rcClient );
CBrush brush( RGB( 0, 0, 0 ) );
CBrush *pOldBrush = pDC->SelectObject( &brush );
pDC->Rectangle( 0, 0, rcClient.Width(), rcClient.Height() );
pDC->SelectObject( pOldBrush );
// Work backwards from the right side to the left.
int nIntervals = rcClient.Width();
DWORD intervalMS = 500; // one interval per pixel
DWORD startTime = 0xFFFFFFFF, endTime = 0;
// First, find which order of magnitude to use on the vertical scale by finding the maximum value.
for ( int iEntry=0; iEntry < m_Entries.Count(); iEntry++ )
{
DWORD msTime = m_Entries[iEntry].m_msTime;
startTime = min( startTime, msTime );
endTime = max( endTime, msTime );
}
int curTime = (int)endTime - nIntervals*intervalMS;
CGraphEntry prevEntry, curEntry;
prevEntry.m_msTime = curEntry.m_msTime = -1;
CUtlVector<POINT> sentPoints;
CUtlVector<POINT> receivedPoints;
int iCurEntry = -1;
int nMaxBytesSent = -1, nMaxBytesReceived = -1;
for ( int x=0; x < nIntervals; x++ )
{
if ( curTime >= 0 )
{
// Now find the graph_entry for the time we're at.
while ( prevEntry.m_msTime == -1 || curTime > curEntry.m_msTime )
{
++iCurEntry;
if ( iCurEntry >= m_Entries.Count() )
goto ENDLOOP;
prevEntry = curEntry;
curEntry = m_Entries[iCurEntry];
}
if ( curTime >= prevEntry.m_msTime && curTime <= curEntry.m_msTime )
{
// Interpolate the bytes sent.
int nBytesSent = (int)RemapVal(
curTime,
prevEntry.m_msTime, curEntry.m_msTime,
prevEntry.m_nBytesSent, curEntry.m_nBytesSent );
POINT sentPoint = { x, nBytesSent };
sentPoints.AddToTail( sentPoint );
nMaxBytesSent = max( nMaxBytesSent, nBytesSent );
int nBytesReceived = (int)RemapVal(
curTime,
prevEntry.m_msTime, curEntry.m_msTime,
prevEntry.m_nBytesReceived, curEntry.m_nBytesReceived );
POINT receivedPoint = { x, nBytesReceived };
receivedPoints.AddToTail( receivedPoint );
nMaxBytesReceived = max( nMaxBytesReceived, nBytesReceived );
}
}
curTime += intervalMS;
}
ENDLOOP:;
// Now normalize all the values.
int largest = max( nMaxBytesSent, nMaxBytesReceived );
int topValue = (largest*11) / 10;
/*
DWORD nZeros;
for( nZeros = 1; nZeros < 20; nZeros++ )
{
if ( largest < pow( 10, nZeros ) )
break;
}
// Now find the value at the top of the graph. We choose the smallest enclosing tenth of the
// order of magnitude we're at (so if we were at 1,000,000, and our max value was 350,000, we'd choose 400,000).
int iTenth;
int topValue;
for ( iTenth=1; iTenth <= 10; iTenth++ )
{
topValue = (DWORD)( pow( 10, nZeros-1 ) * iTenth );
if ( topValue >= largest )
break;
}
*/
for ( int iSample=0; iSample < sentPoints.Count(); iSample++ )
{
double flHeight;
flHeight = ((double)sentPoints[iSample].y / topValue) * (rcClient.Height() - 1);
sentPoints[iSample].y = (int)( rcClient.Height() - flHeight );
flHeight = ((double)receivedPoints[iSample].y / topValue) * (rcClient.Height() - 1);
receivedPoints[iSample].y = (int)( rcClient.Height() - flHeight );
}
// Draw some horizontal lines dividing the space.
int nLines = 10;
for ( int iLine=0; iLine <= nLines; iLine++ )
{
CPen penLine;
COLORREF color;
if ( iLine == 0 || iLine == nLines/2 )
color = RGB( 0, 220, 0 );
else
color = RGB( 0, 100, 0 );
penLine.CreatePen( PS_SOLID, 1, color );
CPen *pOldPen = pDC->SelectObject( &penLine );
int y = (iLine * rcClient.Height()) / nLines;
pDC->MoveTo( 0, y );
pDC->LineTo( rcClient.Width(), y );
pDC->SelectObject( pOldPen );
}
// Now draw the lines for the data.
CPen penSent( PS_SOLID, 1, RGB( 0, 255, 0 ) );
CPen *pOldPen = pDC->SelectObject( &penSent );
pDC->Polyline( sentPoints.Base(), sentPoints.Count() );
pDC->SelectObject( pOldPen );
CPen penReceived( PS_SOLID, 1, RGB( 255, 255, 0 ) );
pOldPen = pDC->SelectObject( &penReceived );
pDC->Polyline( receivedPoints.Base(), receivedPoints.Count() );
pDC->SelectObject( pOldPen );
// Draw text labels.
pDC->SetTextColor( RGB( 200, 200, 200 ) );
pDC->SetBkColor( 0 );
CString str;
str.Format( "%dk", (topValue+511) / 1024 );
pDC->ExtTextOut( 0, 1, 0, NULL, str, NULL );
str.Format( "%dk", (topValue+511) / 1024 / 2 );
pDC->ExtTextOut( 0, rcClient.Height()/2 + 1, 0, NULL, str, NULL );
}
void CGraphControl::Fill( CUtlVector<CGraphEntry> &entries )
{
CDC *pDC = GetDC();
if ( !pDC )
return;
m_Entries = entries;
Render( pDC );
ReleaseDC( pDC );
}
/////////////////////////////////////////////////////////////////////////////
// CGraphControl message handlers
void CGraphControl::OnPaint()
{
CPaintDC dc(this); // device context for painting
Render( &dc );
}
| 5,868 | 2,472 |
#include "testing/testing.hpp"
#include "coding/string_utf8_multilang.hpp"
#include "coding/transliteration.hpp"
#include "platform/platform.hpp"
namespace
{
void TestTransliteration(Transliteration const & translit, std::string const & locale,
std::string const & original, std::string const & expected)
{
std::string out;
translit.Transliterate(original, StringUtf8Multilang::GetLangIndex(locale), out);
TEST_EQUAL(expected, out, ());
}
} // namespace
// This test is inside of the map_tests because it uses Platform for obtaining the resource directory.
UNIT_TEST(Transliteration_CompareSamples)
{
Transliteration & translit = Transliteration::Instance();
translit.Init(GetPlatform().ResourcesDir());
TestTransliteration(translit, "ar", "العربية", "alrbyt");
TestTransliteration(translit, "ru", "Русский", "Russkiy");
TestTransliteration(translit, "zh", "中文", "zhong wen");
TestTransliteration(translit, "be", "Беларуская", "Byelaruskaya");
TestTransliteration(translit, "ka", "ქართული", "kartuli");
TestTransliteration(translit, "ko", "한국어", "hangug-eo");
TestTransliteration(translit, "he", "עברית", "bryt");
TestTransliteration(translit, "el", "Ελληνικά", "Ellenika");
TestTransliteration(translit, "zh_pinyin", "拼音", "pin yin");
TestTransliteration(translit, "th", "ไทย", ""); // Thai-Latin transliteration is off.
TestTransliteration(translit, "sr", "Српски", "Srpski");
TestTransliteration(translit, "uk", "Українська", "Ukrayinska");
TestTransliteration(translit, "fa", "فارسی", "farsy");
TestTransliteration(translit, "hy", "Հայերէն", "Hayeren");
TestTransliteration(translit, "kn", "ಕನ್ನಡ", "kannada");
TestTransliteration(translit, "am", "አማርኛ", "amarinya");
TestTransliteration(translit, "ja_kana", "カタカナ", "katakana");
TestTransliteration(translit, "bg", "Български", "Bulgarski");
TestTransliteration(translit, "kk", "Қазақ", "Qazaq");
TestTransliteration(translit, "mn", "Монгол хэл", "Mongol hel");
TestTransliteration(translit, "mk", "Македонски", "Makedonski");
TestTransliteration(translit, "hi", "हिन्दी", "hindi");
}
| 2,125 | 815 |
// Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/memory/allocation/thread_local_allocator.h"
namespace paddle {
namespace memory {
namespace allocation {
ThreadLocalAllocatorImpl::ThreadLocalAllocatorImpl(const platform::Place& p)
: place_(p) {
if (platform::is_gpu_place(place_)) {
buddy_allocator_.reset(new memory::detail::BuddyAllocator(
std::unique_ptr<memory::detail::SystemAllocator>(
new memory::detail::GPUAllocator(
BOOST_GET_CONST(platform::CUDAPlace, place_).device)),
platform::GpuMinChunkSize(), platform::GpuMaxChunkSize()));
} else {
LOG(FATAL) << "Thread local allocator only supports CUDAPlace now.";
}
}
std::shared_ptr<ThreadLocalAllocatorImpl> ThreadLocalCUDAAllocatorPool::Get(
int gpu_id) {
auto pos = std::distance(devices_.begin(),
std::find(devices_.begin(), devices_.end(), gpu_id));
PADDLE_ENFORCE_LT(
pos, devices_.size(),
platform::errors::InvalidArgument(
"The position of device should be less than the size of devices."));
std::call_once(*init_flags_[pos], [this, pos, gpu_id] {
platform::SetDeviceId(devices_[pos]);
allocators_[pos].reset(
new ThreadLocalAllocatorImpl(platform::CUDAPlace(gpu_id)));
});
return allocators_[pos];
}
ThreadLocalCUDAAllocatorPool::ThreadLocalCUDAAllocatorPool()
: devices_(platform::GetSelectedDevices()) {
auto gpu_num = devices_.size();
allocators_.resize(gpu_num);
init_flags_.reserve(gpu_num);
for (size_t i = 0; i < gpu_num; ++i) {
init_flags_.emplace_back(new std::once_flag());
}
}
ThreadLocalAllocation* ThreadLocalAllocatorImpl::AllocateImpl(size_t size) {
VLOG(10) << "ThreadLocalAllocatorImpl::AllocateImpl " << size;
void* ptr = buddy_allocator_->Alloc(size);
auto* tl_allocation = new ThreadLocalAllocation(ptr, size, place_);
tl_allocation->SetThreadLocalAllocatorImpl(shared_from_this());
return tl_allocation;
}
void ThreadLocalAllocatorImpl::FreeImpl(ThreadLocalAllocation* allocation) {
VLOG(10) << "ThreadLocalAllocatorImpl::FreeImpl " << allocation;
buddy_allocator_->Free(allocation->ptr());
delete allocation;
}
} // namespace allocation
} // namespace memory
} // namespace paddle
| 2,851 | 927 |
// PX2Event.cpp
#include "PX2Event.hpp"
#include "PX2Assert.hpp"
using namespace PX2;
Event::Event ()
:
mEventType(0),
mSender(0),
mReceiver(0),
mDelayTime(0.0f),
mDelayTiming(0.0f),
mIsDoDelay(false)
{
mEventChannel.FillUserChannel();
}
//----------------------------------------------------------------------------
Event::Event (const Event& event)
{
Initlize(event);
}
//----------------------------------------------------------------------------
Event::~Event ()
{
mSender = 0;
mReceiver = 0;
}
//----------------------------------------------------------------------------
Event& Event::operator= (const Event& event)
{
Initlize(event);
return (*this);
}
//----------------------------------------------------------------------------
void Event::SetEventType (EventType eventType)
{
mEventType = eventType;
}
//----------------------------------------------------------------------------
Event::EventType Event::GetEventType ()
{
return mEventType;
}
//----------------------------------------------------------------------------
void Event::SetChannel (const EventChannel& eventChannel)
{
if (eventChannel.IsEmpty())
{
assertion(false, "input eventChannel must not be empty.");
}
mEventChannel = eventChannel;
}
//----------------------------------------------------------------------------
const EventChannel& Event::GetChannel ()
{
return mEventChannel;
}
//----------------------------------------------------------------------------
void Event::SetTimeDelay (float timeDelay)
{
mDelayTime = timeDelay;
mDelayTiming = timeDelay;
if (mDelayTiming > 0.0f)
mIsDoDelay = true;
}
//----------------------------------------------------------------------------
void Event::SetSender (EventHandler *handler)
{
mSender = handler;
}
//----------------------------------------------------------------------------
EventHandler* Event::GetSender ()
{
return mSender;
}
//----------------------------------------------------------------------------
void Event::SetReceiver (EventHandler *handler)
{
mReceiver = handler;
}
//----------------------------------------------------------------------------
EventHandler* Event::GetReceiver ()
{
return mReceiver;
}
//----------------------------------------------------------------------------
bool Event::IsSystemEvent () const
{
return mEventChannel.IsEmpty();
}
//----------------------------------------------------------------------------
void Event::SetBeSystemEvent ()
{
mEventChannel.Clear();
}
//----------------------------------------------------------------------------
void Event::Initlize (const Event &event)
{
mEventChannel = event.mEventChannel;
mEventType = event.mEventType;
mEventData = event.mEventData;
mSender = event.mSender;
mReceiver = event.mReceiver;
}
//----------------------------------------------------------------------------
void Event::Update (float timeDetail)
{
if (mIsDoDelay)
{
mDelayTiming -= timeDetail;
if (mDelayTiming < 0.0f)
mDelayTiming = 0.0f;
}
}
//----------------------------------------------------------------------------
bool Event::IsDelayActted ()
{
if (mIsDoDelay && 0.0f==mDelayTiming)
{
return true;
}
return false;
}
//---------------------------------------------------------------------------- | 3,248 | 828 |
/* lorina: C++ parsing library
* Copyright (C) 2018-2021 EPFL
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
\file genlib.hpp
\brief Implements GENLIB parser
\author Heinz Riener
\author Shubham Rai
\author Alessandro Tempia Calvino
*/
#pragma once
#include "common.hpp"
#include "detail/utils.hpp"
#include "diagnostics.hpp"
#include <fstream>
#include <istream>
#include <optional>
#include <sstream>
#include <string>
namespace lorina
{
enum class phase_type : uint8_t
{
INV = 0,
NONINV = 1,
UNKNOWN = 2,
};
// PIN <pin-name> <phase> <input-load> <max-load> <rise-block-delay> <rise-fanout-delay> <fall-block-delay> <fall-fanout-delay>
struct pin_spec
{
std::string name;
phase_type phase;
double input_load;
double max_load;
double rise_block_delay;
double rise_fanout_delay;
double fall_block_delay;
double fall_fanout_delay;
}; /* pin_spec */
/*! \brief A reader visitor for a GENLIB format.
*
* Callbacks for the GENLIB format.
*/
class genlib_reader
{
public:
virtual void on_gate( std::string const& name, std::string const& expression, uint32_t num_vars, double area, std::vector<pin_spec> const& pins ) const
{
(void)name;
(void)expression;
(void)num_vars;
(void)area;
(void)pins;
}
}; /* genlib_reader */
/*! \brief Parse for the GENLIB format.
*
*/
class genlib_parser
{
public:
explicit genlib_parser( std::istream& in, genlib_reader const& reader, diagnostic_engine* diag )
: in( in )
, reader( reader )
, diag( diag )
{}
public:
bool run()
{
std::string line;
while ( std::getline( in, line ) )
{
/* remove whitespaces */
detail::trim( line );
/* skip comments and empty lines */
if ( line[0] == '#' || line.empty() )
{
continue;
}
if ( !parse_gate_definition( line ) )
{
return false;
}
}
return true;
}
private:
bool parse_gate_definition( std::string const& line )
{
std::stringstream ss( line );
std::string const deliminators{" \t\r\n"};
std::string token;
std::vector<std::string> tokens;
while ( std::getline( ss, token ) )
{
std::size_t prev = 0, pos;
while ( ( pos = line.find_first_of( deliminators, prev ) ) != std::string::npos )
{
if ( pos > prev )
{
tokens.emplace_back( token.substr( prev, pos - prev ) );
}
prev = pos + 1;
}
if ( prev < line.length() )
{
tokens.emplace_back( token.substr( prev, std::string::npos ) );
}
}
if ( tokens.size() < 4u )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_UNEXPECTED_STRUCTURE ).add_argument( line );
}
return false;
}
if ( tokens[0] != "GATE" )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_GATE ).add_argument( line );
}
return false;
}
auto const beg = tokens[3].find_first_of( "=" );
auto const end = tokens[3].find_first_of( ";" );
if ( beg == std::string::npos || end == std::string::npos )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_EXPRESSION ).add_argument( tokens[3] );
}
return false;
}
std::string const& name = tokens[1];
std::string const& expression = tokens[3].substr( beg + 1, end - beg - 1 );
double const area = std::stod( tokens[2] );
uint32_t num_vars{0};
for ( const auto& c : expression )
{
if ( c >= 'a' && c <= 'z' )
{
uint32_t const var = 1 + ( c - 'a' );
if ( var > num_vars )
{
num_vars = var;
}
}
}
std::vector<pin_spec> pins;
bool generic_pin{false};
uint64_t i{4};
for ( ; i+8 < tokens.size(); i += 9 )
{
/* check PIN specification */
if ( tokens[i] != "PIN" )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_PIN ).add_argument( tokens[i] );
}
return false;
}
std::string const& name = tokens[i+1];
if ( tokens[i+1] == "*" )
{
generic_pin = true;
}
phase_type phase{phase_type::UNKNOWN};
if ( tokens[i+2] == "INV" )
{
phase = phase_type::INV;
}
else if ( tokens[i+2] == "NONINV" )
{
phase = phase_type::NONINV;
}
else
{
if ( tokens[i+2] != "UNKNOWN" )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_PIN_PHASE ).add_argument( tokens[i+1] );
}
}
}
double const input_load = std::stod( tokens[i+3] );
double const max_load = std::stod( tokens[i+4] );
double const rise_block_delay = std::stod( tokens[i+5] );
double const rise_fanout_delay = std::stod( tokens[i+6] );
double const fall_block_delay = std::stod( tokens[i+7] );
double const fall_fanout_delay = std::stod( tokens[i+8] );
pins.emplace_back( pin_spec{name,phase,input_load,max_load,rise_block_delay,rise_fanout_delay,fall_block_delay,fall_fanout_delay} );
}
if ( pins.size() != num_vars && !( pins.size() == 1 && generic_pin ) )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_PIN ).add_argument( tokens[i] );
}
return false;
}
if ( i != tokens.size() )
{
if ( diag )
{
diag->report( diag_id::ERR_GENLIB_FAILED ).add_argument( tokens[i] );
}
return false;
}
reader.on_gate( name, expression, num_vars, area, pins );
return true;
}
protected:
std::istream& in;
genlib_reader const& reader;
diagnostic_engine* diag;
}; /* genlib_parser */
/*! \brief Reader function for the GENLIB format.
*
* Reads GENLIB format from a stream and invokes a callback
* method for each parsed primitive and each detected parse error.
*
* \param in Input stream
* \param reader GENLIB reader with callback methods invoked for parsed primitives
* \param diag An optional diagnostic engine with callback methods for parse errors
* \return Success if parsing has been successful, or parse error if parsing has failed
*/
[[nodiscard]] inline return_code read_genlib( std::istream& in, const genlib_reader& reader, diagnostic_engine* diag = nullptr )
{
genlib_parser parser( in, reader, diag );
auto result = parser.run();
if ( !result )
{
return return_code::parse_error;
}
else
{
return return_code::success;
}
}
/*! \brief Reader function for the GENLIB format.
*
* Reads GENLIB format from a file and invokes a callback
* method for each parsed primitive and each detected parse error.
*
* \param filename Name of the file
* \param reader GENLIB reader with callback methods invoked for parsed primitives
* \param diag An optional diagnostic engine with callback methods for parse errors
* \return Success if parsing has been successful, or parse error if parsing has failed
*/
[[nodiscard]] inline return_code read_genlib( const std::string& filename, const genlib_reader& reader, diagnostic_engine* diag = nullptr )
{
std::ifstream in( detail::word_exp_filename( filename ), std::ifstream::in );
if ( !in.is_open() )
{
if ( diag )
{
diag->report( diag_id::ERR_FILE_OPEN ).add_argument( filename );
}
return return_code::parse_error;
}
else
{
auto const ret = read_genlib( in, reader, diag );
in.close();
return ret;
}
}
} /* lorina */
| 8,506 | 2,931 |
#include <cstdio>
class FindUnion
{
private:
int rank;
FindUnion *parent;
public:
static void MakeSet(FindUnion &x)
{
x.parent = &x;
x.rank = 0;
}
static void Union(FindUnion &x, FindUnion &y)
{
FindUnion *xRoot = FindUnion::Find(x);
FindUnion *yRoot = FindUnion::Find(y);
if (xRoot == yRoot)
return;
if (xRoot->rank < yRoot->rank)
xRoot->parent = yRoot;
else if (xRoot->rank > yRoot->rank)
yRoot->parent = xRoot;
else
{
yRoot->parent = xRoot;
xRoot->rank += 1;
}
}
static FindUnion* Find(FindUnion &x)
{
if (x.parent != &x)
x.parent = FindUnion::Find(*x.parent);
return x.parent;
}
static int FindIndex(FindUnion &x, FindUnion fu[])
{
return FindUnion::Find(x) - fu;
}
};
int main()
{
int n;
scanf("%d", &n);
FindUnion fu[n];
for (int i = 0; i < n; i++)
FindUnion::MakeSet(fu[i]);
for (int i = 0; i < n; i++)
{
int a;
scanf("%d", &a);
a--;
FindUnion::Union(fu[i], fu[a]);
}
bool setRoot[n];
for (int i = 0; i < n; i++)
setRoot[i] = false;
for (int i = 0; i < n; i++)
setRoot[FindUnion::FindIndex(fu[i], fu)] = true;
int count = 0;
for (int i = 0; i < n; i++)
if (setRoot[i] == true)
count++;
printf("%d\n", count);
return 0;
}
| 1,635 | 548 |
#include"CountingSorts.h"
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
#include<ctime>
#include<cstdlib>
using namespace std;
void ResizeIntVector(vector<int>& S, const int size) {
//while the vector is not the correct size
while (S.size() != size)
//pop elements if it is too big, or push them if it is too small
(S.size() > size) ? S.pop_back() : S.push_back(0);
}
void RandomizeIntVector(vector<int> &S) {
//seed random with a new value
srand(time(0));
//loop through the array
for (int& I : S)
I = rand();
}
void PrintIntVector(ostream &out, string vectorName, vector<int> S) {
cout << endl << vectorName << endl;
for (int i = 0; i < S.size(); i++)
{
out << S.at(i);
i++;
if (i < S.size())
{
out << "\t" << S.at(i);
i++;
if (i < S.size())
{
out << "\t" << S.at(i);
i++;
}
}
cout << endl;
}
}
int FindMax(vector<int> S) {
//track the largest int
int max = S[0];
//loop through S
for (int I : S)
//if S-i is larger than the max
if (max < I)
//set max to S-i
max = I;
//return the max
return max;
}
| 1,100 | 477 |
//
// LogLights.hpp
// FilamentViewer
//
// Created by James Walker on 5/27/21.
//
#ifndef LogLights_hpp
#define LogLights_hpp
namespace filament
{
class Engine;
class Scene;
};
/*!
@function LogLights
@abstract Log various information about lights in a Scene to std::cout.
@param inEngine An engine.
@param inScene A scene.
*/
void LogLights( filament::Engine& inEngine, filament::Scene& inScene );
#endif /* LogLights_hpp */
| 447 | 175 |
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <afxres.h>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
#include <map>
#include <vector>
#include <string>
//#include <Crispen.h>
// #include <sqlite3.h/sqlite3>
#include <utility>
#define TRUE "true"
#define FALSE "false"
#include <time.h>
#include <stdio.h>
#include<stdlib.h>
#include <optional>
#include <cstdlib>
#include <vector>
#define PI 3.1429
#include <iostream>
using namespace std;
#include <string>
#include <iomanip>
#include <iterator>
/*
Write a C++ language program to swap two numbers using pointers and
function.
*/
/* Without using a temporary variable*/
void swap2(int *a, int *b){
*a = *a-*b;
*b = *a+*b;
*a= *b-*a;
}
/*By using a temporary variable*/
void swap1(int *a, int *b){
int temp = *a;
*a =*b;
*b = temp;
}
int main(){
cout<<"Enter two integers a and b respectively: ";
int a,b;
cin>>a>>b;
cout<<"Before swapp"<<endl;
cout<<"a = "<<a<<", b = "<<b<<endl;
cout<<"After swapp"<<endl;
swap2(&a,&b);
cout<<"a = "<<a<<", b = "<<b<<endl;
return 0;
}
// @ competetive coding STRAWBERRY
| 1,204 | 475 |
#include <iostream>
#include <vector>
using namespace std;
int calc_sum(vector<int> numbers) {
int ans = 0;
for(int i = 1; i <= numbers.size(); i++) ans += i * numbers.at(i-1);
return ans;
}
int main() {
int n, number, pos;
cin >> n;
vector<pair<int, int>> numbers;
for(int i = 0; i < n; i++) {
cin >> number;
if(number == 0) pos = i;
numbers.push_back(number);
}
int max_happiness = INT32_MIN, ps = -1;
for(int i = 1; i < n; i++) max_happiness = max(max_happiness, calc_sum(swap(numbers, i, pos)));
cout << max_happiness;
} | 599 | 237 |
#pragma once
#include <cstdlib>
namespace Legolas{
class VirtualVector {
public:
// virtual int getSize( void ) const = 0 ;
typedef std::size_t SizeType;
virtual SizeType size( void ) const = 0 ;
virtual const VirtualVector & getElement( SizeType i ) const = 0 ;
virtual VirtualVector & getElement( SizeType i ) = 0 ;
virtual VirtualVector * clone( void ) const = 0 ;
virtual VirtualVector * newVirtualVector( const VirtualVectorShape & shape) const = 0 ;
virtual ~VirtualVector( void ){};
virtual bool sameShape(const VirtualVector & source ) const = 0;
virtual void copy(const VirtualVector & source) = 0 ;
virtual void scale( double a ) =0 ;
virtual double relativeDiffAndCopy( const VirtualVector & source ) = 0;
virtual void plusAssign(double factor, const VirtualVector & source) = 0;
virtual double dot(const VirtualVector & source) const = 0;
virtual void scaleAndPlusAssign(double scaleFactor, double factor,const VirtualVector & source) = 0;
virtual void display( void ) const =0;
typedef VirtualVector * VirtualVectorPtr;
static inline VirtualVector & getClone(VirtualVectorPtr & vecPtr,const VirtualVector & source){
if (!vecPtr){
vecPtr=source.clone();
}
else{
if (!vecPtr->sameShape(source)){
delete vecPtr;
vecPtr=source.clone();
}
else{
vecPtr->copy(source);
}
}
return (*vecPtr);
}
};
}
| 1,451 | 431 |
/*
The MIT License (MIT)
Copyright (c) 2014 CantTouchDis <bauschp@informatik.uni-freiburg.de>
Copyright (c) 2014 brio1009 <christoph1009@gmail.com>
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.
*/
// GLM-define, because degree-methods are deprected.
#define GLM_FORCE_RADIANS
// RayTracerLib.
#include <Image.h>
#include <Ray.h>
#include <Scene.h>
#include <cameras/PerspectiveCamera.h>
#include <materials/Material.h>
#include <parser/SceneFileParser.h>
#include <shapes/Ellipsoid.h>
#include <shapes/Plane.h>
// C Header.
#include <omp.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/vector_angle.hpp>
// C++ Header.
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <vector>
//
void renderScene(const char* fileName, size_t chunks, size_t chunkNr) {
// Create the scene. This also adds all the objects.
Scene scene;
// Load the desired Scene.
SceneFileParser sceneParser;
sceneParser.parse("testScene.xml", &scene);
// Render all the images.
scene.render(chunks, chunkNr);
// Get the cameras and save the images.
for (size_t i = 0; i < scene.cameras().size(); ++i) {
// Save the image under different names.
char buff[100];
#ifdef WINDOWS
_snprintf_s(buff, sizeof(buff), "%s%03lu.bmp", fileName, i);
#else
snprintf(buff, sizeof(buff), "%s%03zu.bmp", fileName, i);
#endif // WINDOWS
scene.cameras().at(i)->getImage().saveAsBMP(buff);
}
}
// The main method.
int main(int argc, char** argv) {
const char* fileName = "Img";
// Print usage info.
if (argc > 5) {
printf(
"Usage: %s <optional: output> <optional: chunks chunknr> "
"<optional: random seed>\n",
argv[0]);
exit(EXIT_FAILURE);
}
omp_set_num_threads(1); // TODO: Need to replace rand() in PhongBRDF with
// thread-safe variant.
// Initialize the rand function.
unsigned int seed = static_cast<unsigned int>(time(NULL));
if (argc > 1) {
fileName = argv[1];
}
size_t chunks = 1;
size_t chunkNr = 0;
if (argc > 3) {
chunks = atol(argv[2]);
chunkNr = atol(argv[3]);
}
if (argc == 5) {
seed = static_cast<unsigned int>(atoi(argv[4]));
}
printf("Random seed used: %u\n\n", seed);
srand(seed);
// Render our test scene.
renderScene(fileName, chunks, chunkNr);
}
| 3,363 | 1,236 |
#include <sstream>
#include <stdint.h>
#include <iostream>
#include <iomanip>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/descriptor.pb.h>
#include "rapidxml-1.13/rapidxml.hpp"
#include "rapidxml-1.13/rapidxml_print.hpp"
#include "xml_format.h"
#define XML_TRUE_STRING "true"
#define XML_FALSE_STRING "false"
using namespace std;
namespace google {
namespace protobuf {
XmlFormat::Printer::Printer() {}
XmlFormat::Printer::~Printer() {
for (size_t i = 0; i < _string_pointers_.size(); ++i) {
delete _string_pointers_[i];
}
_string_pointers_.clear();
}
void XmlFormat::Printer::PrintToXmlString(const Message& message,
string* output) {
GOOGLE_DCHECK(output) << "output specified is NULL";
output->clear();
// create the xml dom
rapidxml::xml_document<> doc;
MessageToDOM(message,&doc);
std::stringstream ss;
ss << doc;
*output = ss.str();
}
void XmlFormat::Printer::MessageToDOM(const Message& message, rapidxml::xml_document<>* doc) {
// xml version and encoding
rapidxml::xml_node<>* xml_decl = doc->allocate_node(rapidxml::node_declaration);
xml_decl->append_attribute(doc->allocate_attribute("version", "1.0"));
xml_decl->append_attribute(doc->allocate_attribute("encoding", "utf-8"));
doc->append_node(xml_decl);
// the root node of the protobuf xml is the name of the protobuf container
rapidxml::xml_node<> *root_node = doc->allocate_node(rapidxml::node_element, message.GetDescriptor()->name().c_str());
doc->append_node(root_node);
PrintXml(message, doc, root_node);
}
void XmlFormat::Printer::PrintXml(const Message& message,
rapidxml::xml_document<>* doc,
rapidxml::xml_node<>* node) {
const Reflection* reflection = message.GetReflection();
vector<const FieldDescriptor*> fields;
reflection->ListFields(message, &fields);
for (unsigned int i = 0; i < fields.size(); i++) {
PrintXmlField(message,reflection, fields[i], doc, node);
}
}
void XmlFormat::Printer::PrintXmlField(const Message& message,
const Reflection* reflection,
const FieldDescriptor* field,
rapidxml::xml_document<>* doc,
rapidxml::xml_node<>* node) {
int count = 0;
if (field->is_repeated()) {
count = reflection->FieldSize(message, field);
} else if (reflection->HasField(message, field)) {
count = 1;
}
for (int j = 0; j < count; ++j) {
// Write the field value.
int field_index = j;
if (!field->is_repeated()) {
field_index = -1;
}
PrintXmlFieldValue(message, reflection, field, field_index, doc, node);
}
}
const string & XmlFormat::Printer::GetXmlFieldName(const Message& message,
const Reflection* reflection,
const FieldDescriptor* field) {
if (field->is_extension()) {
// We special-case MessageSet elements for compatibility with proto1.
if (field->containing_type()->options().message_set_wire_format()
&& field->type() == FieldDescriptor::TYPE_MESSAGE
&& field->is_optional()
&& field->extension_scope() == field->message_type()) {
return field->message_type()->full_name();
} else {
return field->full_name();
}
} else {
if (field->type() == FieldDescriptor::TYPE_GROUP) {
// Groups must be serialized with their original capitalization.
return field->message_type()->name();
} else {
return field->name();
}
}
}
void XmlFormat::Printer::PrintXmlFieldValue(
const Message& message,
const Reflection* reflection,
const FieldDescriptor* field,
int field_index,
rapidxml::xml_document<>* doc,
rapidxml::xml_node<>* node) {
GOOGLE_DCHECK(field->is_repeated() || (field_index == -1))
<< "field_index must be -1 for non-repeated fields";
switch (field->cpp_type()) {
//tm use the preprocessor to generate the numerical value cases
// replace the google used string methods with using a stringstream
#define OUTPUT_FIELD(CPPTYPE, METHOD, NUM_TYPE) \
case FieldDescriptor::CPPTYPE_##CPPTYPE: { \
NUM_TYPE value = field->is_repeated() ? \
reflection->GetRepeated##METHOD(message, field, field_index) : \
reflection->Get##METHOD(message, field); \
stringstream number_stream; \
number_stream << setprecision(12) << value; \
string *pStr = new string(number_stream.str()); \
_string_pointers_.push_back(pStr); \
rapidxml::xml_node<> *string_node = doc->allocate_node( \
rapidxml::node_element, \
GetXmlFieldName(message, reflection, field).c_str(), \
pStr->c_str()); \
node->append_node(string_node); \
break; \
}
OUTPUT_FIELD( INT32, Int32, int32_t);
OUTPUT_FIELD( INT64, Int64, int64_t);
OUTPUT_FIELD(UINT32, UInt32, uint32_t);
OUTPUT_FIELD(UINT64, UInt64, uint64_t);
OUTPUT_FIELD( FLOAT, Float, float);
OUTPUT_FIELD(DOUBLE, Double, double);
#undef OUTPUT_FIELD
case FieldDescriptor::CPPTYPE_STRING: {
string scratch;
const string& value = field->is_repeated() ?
reflection->GetRepeatedStringReference(
message, field, field_index, &scratch) :
reflection->GetStringReference(message, field, &scratch);
rapidxml::xml_node<> *string_node = doc->allocate_node(rapidxml::node_element,
GetXmlFieldName(message, reflection, field).c_str(),
value.c_str());
node->append_node(string_node);
break;
}
case FieldDescriptor::CPPTYPE_BOOL: {
if (field->is_repeated()) {
if (reflection->GetRepeatedBool(message, field, field_index)) {
rapidxml::xml_node<> *bool_node = doc->allocate_node(rapidxml::node_element,
GetXmlFieldName(message, reflection, field).c_str(),
XML_TRUE_STRING);
node->append_node(bool_node);
} else {
rapidxml::xml_node<> *bool_node = doc->allocate_node(rapidxml::node_element,
GetXmlFieldName(message, reflection, field).c_str(),
XML_FALSE_STRING);
node->append_node(bool_node);
}
} else {
if (reflection->GetBool(message,field)) {
rapidxml::xml_node<> *bool_node = doc->allocate_node(rapidxml::node_element,
GetXmlFieldName(message, reflection, field).c_str(),
XML_TRUE_STRING);
node->append_node(bool_node);
} else {
rapidxml::xml_node<> *bool_node = doc->allocate_node(rapidxml::node_element,
GetXmlFieldName(message, reflection, field).c_str(),
XML_FALSE_STRING);
node->append_node(bool_node);
}
}
break;
}
case FieldDescriptor::CPPTYPE_ENUM: {
string value = field->is_repeated() ?
reflection->GetRepeatedEnum(message, field, field_index)->name() :
reflection->GetEnum(message, field)->name();
rapidxml::xml_node<> *enum_node = doc->allocate_node(rapidxml::node_element,
GetXmlFieldName(message, reflection, field).c_str(),
value.c_str());
node->append_node(enum_node);
break;
}
case FieldDescriptor::CPPTYPE_MESSAGE: {
// create the child node and recurse
rapidxml::xml_node<> *message_node = doc->allocate_node(rapidxml::node_element, field->name().c_str());
node->append_node(message_node);
PrintXml(field->is_repeated() ?
reflection->GetRepeatedMessage(message, field, field_index) :
reflection->GetMessage(message, field),
doc, message_node);
break;
}
}
}
/* static */ void XmlFormat::PrintToXmlString(
const Message& message, string* output) {
Printer().PrintToXmlString(message, output);
}
/* static */ void XmlFormat::MessageToDOM(
const Message& message, rapidxml::xml_document<>* doc) {
Printer().MessageToDOM(message, doc);
}
} // namespace protobuf
} // namespace google
| 8,311 | 2,740 |
#include<iostream>
using namespace std;
int main()
{
int n , x;
cout <<"Enter the number : \n";
cin>>n;
if(n<2)
cout<<"Number is lesser than 2 and not applicable";
else
{
for(x=2;x<n;x++)
{
if(n%x==0)
{
cout<<"Not Prime Number";
exit(0);
}
else
{
cout<<"Prime Number";
exit(1);
}
}
}
}
| 364 | 186 |
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar
#include <java/lang/reflect/Array_.hpp>
extern void unimplemented_(const char16_t* name);
java::lang::Object* java::lang::reflect::Array_::get(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"java::lang::Object* java::lang::reflect::Array_::get(::java::lang::Object* array, int32_t index)");
return 0;
}
bool java::lang::reflect::Array_::getBoolean(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"bool java::lang::reflect::Array_::getBoolean(::java::lang::Object* array, int32_t index)");
return 0;
}
int8_t java::lang::reflect::Array_::getByte(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"int8_t java::lang::reflect::Array_::getByte(::java::lang::Object* array, int32_t index)");
return 0;
}
char16_t java::lang::reflect::Array_::getChar(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"char16_t java::lang::reflect::Array_::getChar(::java::lang::Object* array, int32_t index)");
return 0;
}
double java::lang::reflect::Array_::getDouble(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"double java::lang::reflect::Array_::getDouble(::java::lang::Object* array, int32_t index)");
return 0;
}
float java::lang::reflect::Array_::getFloat(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"float java::lang::reflect::Array_::getFloat(::java::lang::Object* array, int32_t index)");
return 0;
}
int32_t java::lang::reflect::Array_::getInt(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"int32_t java::lang::reflect::Array_::getInt(::java::lang::Object* array, int32_t index)");
return 0;
}
int32_t java::lang::reflect::Array_::getLength(::java::lang::Object* array)
{ /* native */
clinit();
unimplemented_(u"int32_t java::lang::reflect::Array_::getLength(::java::lang::Object* array)");
return 0;
}
int64_t java::lang::reflect::Array_::getLong(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"int64_t java::lang::reflect::Array_::getLong(::java::lang::Object* array, int32_t index)");
return 0;
}
int16_t java::lang::reflect::Array_::getShort(::java::lang::Object* array, int32_t index)
{ /* native */
clinit();
unimplemented_(u"int16_t java::lang::reflect::Array_::getShort(::java::lang::Object* array, int32_t index)");
return 0;
}
/* private: java::lang::Object* java::lang::reflect::Array_::multiNewArray_(::java::lang::Class* componentType, ::int32_tArray* dimensions) */
/* private: java::lang::Object* java::lang::reflect::Array_::newArray_(::java::lang::Class* componentType, int32_t length) */
void java::lang::reflect::Array_::set(::java::lang::Object* array, int32_t index, ::java::lang::Object* value)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::set(::java::lang::Object* array, int32_t index, ::java::lang::Object* value)");
}
void java::lang::reflect::Array_::setBoolean(::java::lang::Object* array, int32_t index, bool z)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setBoolean(::java::lang::Object* array, int32_t index, bool z)");
}
void java::lang::reflect::Array_::setByte(::java::lang::Object* array, int32_t index, int8_t b)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setByte(::java::lang::Object* array, int32_t index, int8_t b)");
}
void java::lang::reflect::Array_::setChar(::java::lang::Object* array, int32_t index, char16_t c)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setChar(::java::lang::Object* array, int32_t index, char16_t c)");
}
void java::lang::reflect::Array_::setDouble(::java::lang::Object* array, int32_t index, double d)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setDouble(::java::lang::Object* array, int32_t index, double d)");
}
void java::lang::reflect::Array_::setFloat(::java::lang::Object* array, int32_t index, float f)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setFloat(::java::lang::Object* array, int32_t index, float f)");
}
void java::lang::reflect::Array_::setInt(::java::lang::Object* array, int32_t index, int32_t i)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setInt(::java::lang::Object* array, int32_t index, int32_t i)");
}
void java::lang::reflect::Array_::setLong(::java::lang::Object* array, int32_t index, int64_t l)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setLong(::java::lang::Object* array, int32_t index, int64_t l)");
}
void java::lang::reflect::Array_::setShort(::java::lang::Object* array, int32_t index, int16_t s)
{ /* native */
clinit();
unimplemented_(u"void java::lang::reflect::Array_::setShort(::java::lang::Object* array, int32_t index, int16_t s)");
}
| 5,207 | 1,920 |
#include "Aspen/Python/Concat.hpp"
#include "Aspen/Python/Box.hpp"
using namespace Aspen;
using namespace pybind11;
void Aspen::export_concat(pybind11::module& module) {
export_box<SharedBox<object>>(module, "Box");
export_concat<SharedBox<SharedBox<object>>>(module, "");
module.def("concat",
[] (SharedBox<SharedBox<object>> producer) {
return shared_box(concat(std::move(producer)));
});
}
| 415 | 145 |
<?hh // strict
namespace Zynga\Framework\Lockable\Cache\V1\Config\Mock\PgData;
use Zynga\Framework\Testing\TestCase\V2\Base as TestCase;
use
Zynga\Framework\Lockable\Cache\V1\Config\Mock\PgData\Dev as ConfigUnderTest
;
use
Zynga\Framework\Cache\V2\Interfaces\DriverInterface as CacheDriverInterface
;
class DevTest extends TestCase {
public function testCreateKeyFromStorableObject(): void {
$obj = new ConfigUnderTest();
$this->assertInstanceOf(CacheDriverInterface::class, $obj->getCache());
$this->assertEquals('Caching', $obj->getDriver());
$this->assertEquals(10, $obj->getLockTTL());
}
}
| 628 | 220 |
// ILikeBanas
#include "FactorySkyline/UI/FSKeyMappingWidget.h"
#include "Components/Image.h"
#include "Components/HorizontalBox.h"
#include "Components/TextBlock.h"
#include "Components/CanvasPanel.h"
#include "Components/CanvasPanelSlot.h"
#include "Components/HorizontalBoxSlot.h"
UFSKeyMappingWidget::UFSKeyMappingWidget(const FObjectInitializer& ObjectInitializer)
:Super(ObjectInitializer)
{
}
void UFSKeyMappingWidget::SetTitle(const FText& Title)
{
this->Title->SetText(Title);
}
void UFSKeyMappingWidget::SetKey(const FText& Key)
{
this->Key->SetText(Key);
}
void UFSKeyMappingWidget::SetPadding(const float& Padding)
{
UHorizontalBoxSlot* Slot = Cast<UHorizontalBoxSlot>(this->Slot);
Slot->SetPadding(FMargin(Padding, 0.0f));
}
void UFSKeyMappingWidget::SetDefaultView()
{
HighLight->SetVisibility(ESlateVisibility::Hidden);
IsHighLight = false;
}
void UFSKeyMappingWidget::SetHighLightView()
{
HighLight->SetVisibility(ESlateVisibility::SelfHitTestInvisible);
IsHighLight = true;
}
| 1,055 | 363 |
// Copyright 2022 Burdukov Mikhail
#include <gtest/gtest.h>
#include "include/horse_min_range.h"
TEST(minHorseRange, Create) {
ASSERT_NO_THROW(minHorseRange hourse);
}
TEST(minHorseRange, Range_without_barriers) {
chess_position_t st('a', 1);
chess_position_t fin('b', 3);
minHorseRange a(st, fin);
EXPECT_EQ(1, a.calc_range());
}
TEST(minHorseRange, Range_without_barriers1) {
chess_position_t st('a', 1);
chess_position_t fin('b', 3);
minHorseRange a;
a.set_start(st);
a.set_finish(fin);
EXPECT_EQ(1, a.calc_range());
}
TEST(minHorseRange, Range_without_barriers3) {
chess_position_t st('a', 1);
chess_position_t fin('b', 7);
minHorseRange a;
a.set_start(st);
a.set_finish(fin);
EXPECT_EQ(3, a.calc_range());
}
TEST(minHorseRange, Range_without_barriers4) {
chess_position_t st('a', 1);
chess_position_t fin('g', 8);
minHorseRange a;
a.set_start(st);
a.set_finish(fin);
EXPECT_EQ(5, a.calc_range());
}
TEST(minHorseRange, Range_with_barriers) {
chess_position_t st('a', 1);
chess_position_t fin('b', 3);
chess_position_t bar('g', 8);
minHorseRange a;
a.set_start(st);
a.set_finish(fin);
a.set_barrier(bar);
EXPECT_EQ(1, a.calc_range());
}
TEST(minHorseRange, Range_with_barriers1) {
chess_position_t st('a', 1);
chess_position_t fin('b', 7);
chess_position_t bar('g', 8);
minHorseRange a;
a.set_start(st);
a.set_finish(fin);
a.set_barrier(bar);
EXPECT_EQ(3, a.calc_range());
}
TEST(minHorseRange, Range_with_barriers3) {
chess_position_t st('a', 1);
chess_position_t fin('b', 3);
chess_position_t bar('h', 2);
minHorseRange a(st, fin);
a.set_barrier(bar);
EXPECT_EQ(1, a.calc_range());
}
| 1,781 | 785 |
//
// BGLAffine.cc
// Part of the Belfry Geometry Library
//
// Created by GM on 10/13/10.
// Copyright 2010 Belfry Software. All rights reserved.
//
#include "config.h"
#include "BGLAffine.hh"
namespace BGL {
Affine Affine::translationAffine(double dx, double dy)
{
return Affine(1.0, 0.0, 0.0, 1.0, dx, dy);
}
Affine Affine::scalingAffine(double sx, double sy)
{
return Affine(sx, 0.0, 0.0, sy, 0.0, 0.0);
}
Affine Affine::rotationAffine(double radang)
{
double cosv = cos(radang);
double sinv = sin(radang);
return Affine(cosv, -sinv, sinv, cosv, 0.0, 0.0);
}
Affine& Affine::transform(const Affine& aff)
{
double olda = a;
double oldb = b;
double oldc = c;
double oldd = d;
a = aff.a * olda + aff.b * oldc;
b = aff.a * oldb + aff.b * oldd;
c = aff.c * olda + aff.d * oldc;
d = aff.c * oldb + aff.d * oldd;
tx += aff.tx * olda + aff.ty * oldc;
ty += aff.tx * oldb + aff.ty * oldd;
return *this;
}
Affine& Affine::translate(double dx, double dy)
{
return transform(translationAffine(dx,dy));
}
Affine& Affine::scale(double sx, double sy)
{
return transform(scalingAffine(sx,sy));
}
Affine& Affine::scaleAroundPoint(double sx, double sy, double x, double y)
{
translate(-x,-y);
transform(scalingAffine(sx,sy));
translate(x,y);
return *this;
}
Affine& Affine::rotate(double radang)
{
return transform(rotationAffine(radang));
}
Affine& Affine::rotateAroundPoint(double radang, double x, double y)
{
translate(-x,-y);
transform(rotationAffine(radang));
translate(x,y);
return *this;
}
void Affine::transformPoint(double& x, double &y) const
{
double nx = a * x + b * y + tx;
double ny = c * x + d * y + ty;
x = nx;
y = ny;
}
}
// vim: set ts=4 sw=4 nowrap expandtab: settings
| 1,860 | 797 |
#include <stdio.h>
int main(){
int n, t ;
int cont = 0;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &t);
if(t != 1){
cont++;
}
}
printf("%d\n", cont);
return 0;
}
| 244 | 105 |
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:39 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: System.Enum
#include "System/Enum.hpp"
// Including type: UnityEngine.RemoteConfigSettingsHelper
#include "UnityEngine/RemoteConfigSettingsHelper.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: UnityEngine
namespace UnityEngine {
// Autogenerated type: UnityEngine.RemoteConfigSettingsHelper/Tag
struct RemoteConfigSettingsHelper::Tag : public System::Enum {
public:
// public System.Int32 value__
// Offset: 0x0
int value;
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUnknown
static constexpr const int kUnknown = 0;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUnknown
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kUnknown();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUnknown
static void _set_kUnknown(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kIntVal
static constexpr const int kIntVal = 1;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kIntVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kIntVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kIntVal
static void _set_kIntVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kInt64Val
static constexpr const int kInt64Val = 2;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kInt64Val
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kInt64Val();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kInt64Val
static void _set_kInt64Val(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUInt64Val
static constexpr const int kUInt64Val = 3;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUInt64Val
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kUInt64Val();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kUInt64Val
static void _set_kUInt64Val(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kDoubleVal
static constexpr const int kDoubleVal = 4;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kDoubleVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kDoubleVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kDoubleVal
static void _set_kDoubleVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kBoolVal
static constexpr const int kBoolVal = 5;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kBoolVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kBoolVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kBoolVal
static void _set_kBoolVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kStringVal
static constexpr const int kStringVal = 6;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kStringVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kStringVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kStringVal
static void _set_kStringVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kArrayVal
static constexpr const int kArrayVal = 7;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kArrayVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kArrayVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kArrayVal
static void _set_kArrayVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMixedArrayVal
static constexpr const int kMixedArrayVal = 8;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMixedArrayVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kMixedArrayVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMixedArrayVal
static void _set_kMixedArrayVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMapVal
static constexpr const int kMapVal = 9;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMapVal
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kMapVal();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMapVal
static void _set_kMapVal(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// static field const value: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMaxTags
static constexpr const int kMaxTags = 10;
// Get static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMaxTags
static UnityEngine::RemoteConfigSettingsHelper::Tag _get_kMaxTags();
// Set static field: static public UnityEngine.RemoteConfigSettingsHelper/Tag kMaxTags
static void _set_kMaxTags(UnityEngine::RemoteConfigSettingsHelper::Tag value);
// Creating value type constructor for type: Tag
Tag(int value_ = {}) : value{value_} {}
}; // UnityEngine.RemoteConfigSettingsHelper/Tag
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::RemoteConfigSettingsHelper::Tag, "UnityEngine", "RemoteConfigSettingsHelper/Tag");
#pragma pack(pop)
| 6,426 | 1,668 |
/**********************************************************************
opconfab.cpp - Confab, the conformer generator described in
Journal of Cheminformatics, 3, 1, 8
http://www.jcheminf.com/content/3/1/8
Copyright (C) 2013 by Noel O'Boyle
This file is part of the Open Babel project.
For more information, see <http://openbabel.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 version 2 of the License.
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.
***********************************************************************/
#include <openbabel/babelconfig.h>
#include <iostream>
#include<openbabel/op.h>
#include<openbabel/mol.h>
#include<openbabel/forcefield.h>
#include <openbabel/obconversion.h>
#include<openbabel/generic.h>
#define CONFAB_VER "1.1.0"
namespace OpenBabel
{
using namespace std;
//////////////////////////////////////////////////////////
//
// Confab
//
//////////////////////////////////////////////////////////
class Confab
{
public:
Confab() {};
};
class OpConfab : public OBOp
{
public:
OpConfab(const char* ID) : OBOp(ID, false) {
}
const char* Description()
{
return "Confab, the diverse conformer generator\n"
"Typical usage: obabel infile.xxx -O outfile.yyy --confab --conf 1000000\n"
" options:\n"
" --conf # Max number of conformers to test (default is 1 million)\n"
" --rcutoff # RMSD cutoff (default 0.5 Angstrom)\n"
" --ecutoff # Energy cutoff (default 50.0 kcal/mol)\n"
" --original Include the input conformation as the first conformer\n"
" --verbose Verbose output\n"
;
}
virtual bool WorksWith(OBBase* pOb) const
{
return dynamic_cast<OBMol*>(pOb) != NULL;
}
virtual bool Do(OBBase* pOb, const char* OptionText, OpMap* pmap, OBConversion*);
void DisplayConfig(OBConversion* pConv);
void Run(OBConversion* pConv, OBMol* pmol);
double rmsd_cutoff;
double energy_cutoff;
unsigned int conf_cutoff;
bool verbose;
bool include_original;
unsigned int N;
OBForceField *pff;
};
//////////////////////////////////////////////////////////
OpConfab theConfab("confab"); //Global instance
//////////////////////////////////////////////////////////
bool OpConfab::Do(OBBase* pOb, const char* OptionText, OpMap* pmap, OBConversion* pConv=NULL)
{
OBMol* pmol = dynamic_cast<OBMol*>(pOb);
if(!pmol)
return false;
if(pConv->IsFirstInput())
{
pConv->AddOption("writeconformers", OBConversion::GENOPTIONS);
rmsd_cutoff = 0.5;
energy_cutoff = 50.0;
conf_cutoff = 1000000; // 1 Million
verbose = false;
include_original = false;
OpMap::const_iterator iter;
iter = pmap->find("rcutoff");
if(iter!=pmap->end())
rmsd_cutoff = atof(iter->second.c_str());
iter = pmap->find("ecutoff");
if(iter!=pmap->end())
energy_cutoff = atof(iter->second.c_str());
iter = pmap->find("conf");
if(iter!=pmap->end())
conf_cutoff = atoi(iter->second.c_str());
iter = pmap->find("verbose");
if(iter!=pmap->end())
verbose = true;
iter = pmap->find("original");
if(iter!=pmap->end())
include_original = true;
cout << "**Starting Confab " << CONFAB_VER << "\n";
cout << "**To support, cite Journal of Cheminformatics, 2011, 3, 8.\n";
pff = OpenBabel::OBForceField::FindType("mmff94");
if (!pff) {
cout << "!!Cannot find forcefield!" << endl;
exit(-1);
}
DisplayConfig(pConv);
}
Run(pConv, pmol);
return false;
}
void OpConfab::Run(OBConversion* pConv, OBMol* pmol)
{
OBMol mol = *pmol;
N++;
cout << "**Molecule " << N << endl << "..title = " << mol.GetTitle() << endl;
cout << "..number of rotatable bonds = " << mol.NumRotors() << endl;
mol.AddHydrogens();
bool success = pff->Setup(mol);
if (!success) {
cout << "!!Cannot set up forcefield for this molecule\n"
<< "!!Skipping\n" << endl;
return;
}
pff->DiverseConfGen(rmsd_cutoff, conf_cutoff, energy_cutoff, verbose);
pff->GetConformers(mol);
int nconfs = include_original ? mol.NumConformers() : mol.NumConformers() - 1;
cout << "..generated " << nconfs << " conformers" << endl;
unsigned int c = include_original ? 0 : 1;
for (; c < mol.NumConformers(); ++c) {
mol.SetConformer(c);
if(!pConv->GetOutFormat()->WriteMolecule(&mol, pConv))
break;
}
cout << endl;
}
void OpConfab::DisplayConfig(OBConversion* pConv)
{
cout << "..Input format = " << pConv->GetInFormat()->GetID() << endl;
cout << "..Output format = " << pConv->GetOutFormat()->GetID() << endl;
cout << "..RMSD cutoff = " << rmsd_cutoff << endl;
cout << "..Energy cutoff = " << energy_cutoff << endl;
cout << "..Conformer cutoff = " << conf_cutoff << endl;
cout << "..Write input conformation? " << (include_original ? "True" : "False") << endl;
cout << "..Verbose? " << (verbose ? "True" : "False") << endl;
cout << endl;
}
}//namespace
| 5,585 | 1,893 |
#include "gtest/gtest.h"
#include "commonfixture.h"
extern "C" {
#include <launchdarkly/api.h>
#include "lru.h"
#include "utility.h"
}
// Inherit from the CommonFixture to give a reasonable name for the test output.
// Any custom setup and teardown would happen in this derived class.
class LRUFixture : public CommonFixture {
};
TEST_F(LRUFixture, InsertExisting) {
struct LDLRU *lru;
ASSERT_TRUE(lru = LDLRUInit(10));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "abc"));
ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "abc"));
LDLRUFree(lru);
}
TEST_F(LRUFixture, MaxCapacity) {
struct LDLRU *lru;
ASSERT_TRUE(lru = LDLRUInit(2));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "456"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "789"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "789"));
LDLRUFree(lru);
}
TEST_F(LRUFixture, AccessBumpsPosition) {
struct LDLRU *lru;
ASSERT_TRUE(lru = LDLRUInit(3));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "456"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "789"));
ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "ABC"));
ASSERT_EQ(LDLRUSTATUS_EXISTED, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "456"));
LDLRUFree(lru);
}
TEST_F(LRUFixture, ZeroCapacityAlwaysNew) {
struct LDLRU *lru;
ASSERT_TRUE(lru = LDLRUInit(0));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123"));
ASSERT_EQ(LDLRUSTATUS_NEW, LDLRUInsert(lru, "123"));
LDLRUFree(lru);
}
| 1,763 | 821 |
#include <fstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cassert>
using namespace std;
const int kNmax = 50005;
const int inf = 999999;
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
int n;
int m;
int source;
vector<pair<int, int> > adj[kNmax];
void read_input() {
ifstream fin("in");
fin >> n >> m >> source;
for (int i = 1, x, y, w; i <= m; i++) {
fin >> x >> y >> w;
adj[x].push_back(make_pair(y, w));
}
fin.close();
}
vector<int> get_result() {
/*
TODO: Gasiti distantele minime de la nodul source la celelalte noduri
folosind BellmanFord pe graful orientat cu n noduri, m arce stocat in adj.
d[node] = costul minim / lungimea minima a unui drum de la source la nodul
node;
d[source] = 0;
d[node] = -1, daca nu se poate ajunge de la source la node.
Atentie:
O muchie este tinuta ca o pereche (nod adiacent, cost muchie):
adj[x][i].first = nodul adiacent lui x,
adj[x][i].second = costul.
In cazul in care exista ciclu de cost negativ, returnati un vector gol:
return vector<int>();
*/
vector<int> d(n + 1, inf);
queue<int> q;
vector<int> visited(n + 1, 0);
d[source] = 0;
q.push(source);
while(!q.empty()) {
int node = q.front();
q.pop();
visited[node]++;
if(visited[node] == n) {
return vector<int>();
}
for(auto& edge : adj[node]) {
if(d[edge.first] >= d[node] + edge.second) {
d[edge.first] = d[node] + edge.second;
q.push(edge.first);
}
}
}
for(int i = 1; i <= n; i++) {
if(d[i] == inf) {
d[i] = -1;
}
}
return d;
}
void print_output(vector<int> result) {
ofstream fout("out");
if (result.size() == 0) {
fout << "Ciclu negativ!\n";
} else {
for (int i = 1; i <= n; i++) {
fout << result[i] << ' ';
}
fout << '\n';
}
fout.close();
}
};
int main() {
Task *task = new Task();
task->solve();
delete task;
return 0;
}
| 2,016 | 940 |
/*++
Copyright (c) 2013 Microsoft Corporation
Module Name:
dl_mk_quantifier_abstraction.cpp
Abstract:
Create quantified Horn clauses from benchmarks with arrays.
Author:
Ken McMillan
Andrey Rybalchenko
Nikolaj Bjorner (nbjorner) 2013-04-02
Revision History:
--*/
#include "muz/transforms/dl_mk_quantifier_abstraction.h"
#include "muz/base/dl_context.h"
#include "ast/rewriter/expr_safe_replace.h"
#include "ast/expr_abstract.h"
namespace datalog {
// model converter:
// Given model for P^(x, y, i, a[i])
// create model: P(x,y,a) == forall i . P^(x,y,i,a[i])
// requires substitution and list of bound variables.
class mk_quantifier_abstraction::qa_model_converter : public model_converter {
ast_manager& m;
func_decl_ref_vector m_old_funcs;
func_decl_ref_vector m_new_funcs;
vector<expr_ref_vector> m_subst;
vector<sort_ref_vector> m_sorts;
vector<bool_vector > m_bound;
public:
qa_model_converter(ast_manager& m):
m(m), m_old_funcs(m), m_new_funcs(m) {}
~qa_model_converter() override {}
model_converter * translate(ast_translation & translator) override {
return alloc(qa_model_converter, m);
}
void display(std::ostream& out) override { display_add(out, m); }
void get_units(obj_map<expr, bool>& units) override { units.reset(); }
void insert(func_decl* old_p, func_decl* new_p, expr_ref_vector& sub, sort_ref_vector& sorts, bool_vector const& bound) {
m_old_funcs.push_back(old_p);
m_new_funcs.push_back(new_p);
m_subst.push_back(sub);
m_bound.push_back(bound);
m_sorts.push_back(sorts);
}
void operator()(model_ref & old_model) override {
model_ref new_model = alloc(model, m);
for (unsigned i = 0; i < m_new_funcs.size(); ++i) {
func_decl* p = m_new_funcs.get(i);
func_decl* q = m_old_funcs.get(i);
expr_ref_vector const& sub = m_subst[i];
sort_ref_vector const& sorts = m_sorts[i];
bool_vector const& is_bound = m_bound[i];
func_interp* f = old_model->get_func_interp(p);
expr_ref body(m);
SASSERT(0 < p->get_arity());
if (f) {
body = f->get_interp();
SASSERT(!f->is_partial());
SASSERT(body);
}
else {
expr_ref_vector args(m);
for (unsigned i = 0; i < p->get_arity(); ++i) {
args.push_back(m.mk_var(i, p->get_domain(i)));
}
body = m.mk_app(p, args);
}
// Create quantifier wrapper around body.
TRACE("dl", tout << body << "\n";);
// 1. replace variables by the compound terms from
// the original predicate.
expr_safe_replace rep(m);
for (unsigned i = 0; i < sub.size(); ++i) {
rep.insert(m.mk_var(i, sub[i]->get_sort()), sub[i]);
}
rep(body);
rep.reset();
TRACE("dl", tout << body << "\n";);
// 2. replace bound variables by constants.
expr_ref_vector consts(m), bound(m), _free(m);
svector<symbol> names;
ptr_vector<sort> bound_sorts;
for (unsigned i = 0; i < sorts.size(); ++i) {
sort* s = sorts[i];
consts.push_back(m.mk_fresh_const("C", s));
rep.insert(m.mk_var(i, s), consts.back());
if (is_bound[i]) {
bound.push_back(consts.back());
names.push_back(symbol(i));
bound_sorts.push_back(s);
}
else {
_free.push_back(consts.back());
}
}
rep(body);
rep.reset();
TRACE("dl", tout << body << "\n";);
// 3. abstract and quantify those variables that should be bound.
body = expr_abstract(bound, body);
body = m.mk_forall(names.size(), bound_sorts.c_ptr(), names.c_ptr(), body);
TRACE("dl", tout << body << "\n";);
// 4. replace remaining constants by variables.
unsigned j = 0;
for (expr* f : _free) {
rep.insert(f, m.mk_var(j++, f->get_sort()));
}
rep(body);
new_model->register_decl(q, body);
TRACE("dl", tout << body << "\n";);
}
old_model = new_model;
}
};
mk_quantifier_abstraction::mk_quantifier_abstraction(
context & ctx, unsigned priority):
plugin(priority),
m(ctx.get_manager()),
m_ctx(ctx),
a(m),
m_refs(m),
m_mc(nullptr) {
}
mk_quantifier_abstraction::~mk_quantifier_abstraction() {
}
func_decl* mk_quantifier_abstraction::declare_pred(rule_set const& rules, rule_set& dst, func_decl* old_p) {
if (rules.is_output_predicate(old_p)) {
dst.inherit_predicate(rules, old_p, old_p);
return nullptr;
}
unsigned sz = old_p->get_arity();
unsigned num_arrays = 0;
for (unsigned i = 0; i < sz; ++i) {
if (a.is_array(old_p->get_domain(i))) {
num_arrays++;
}
}
if (num_arrays == 0) {
return nullptr;
}
func_decl* new_p = nullptr;
if (!m_old2new.find(old_p, new_p)) {
expr_ref_vector sub(m), vars(m);
bool_vector bound;
sort_ref_vector domain(m), sorts(m);
expr_ref arg(m);
for (unsigned i = 0; i < sz; ++i) {
sort* s0 = old_p->get_domain(i);
unsigned lookahead = 0;
sort* s = s0;
while (a.is_array(s)) {
lookahead += get_array_arity(s);
s = get_array_range(s);
}
arg = m.mk_var(bound.size() + lookahead, s0);
s = s0;
while (a.is_array(s)) {
unsigned arity = get_array_arity(s);
expr_ref_vector args(m);
for (unsigned j = 0; j < arity; ++j) {
sort* s1 = get_array_domain(s, j);
domain.push_back(s1);
args.push_back(m.mk_var(bound.size(), s1));
bound.push_back(true);
sorts.push_back(s1);
}
arg = mk_select(arg, args.size(), args.c_ptr());
s = get_array_range(s);
}
domain.push_back(s);
bound.push_back(false);
sub.push_back(arg);
sorts.push_back(s0);
}
SASSERT(old_p->get_range() == m.mk_bool_sort());
new_p = m.mk_func_decl(old_p->get_name(), domain.size(), domain.c_ptr(), old_p->get_range());
m_refs.push_back(new_p);
m_ctx.register_predicate(new_p, false);
if (m_mc) {
m_mc->insert(old_p, new_p, sub, sorts, bound);
}
m_old2new.insert(old_p, new_p);
}
return new_p;
}
app_ref mk_quantifier_abstraction::mk_head(rule_set const& rules, rule_set& dst, app* p, unsigned idx) {
func_decl* new_p = declare_pred(rules, dst, p->get_decl());
if (!new_p) {
return app_ref(p, m);
}
expr_ref_vector args(m);
expr_ref arg(m);
unsigned sz = p->get_num_args();
for (unsigned i = 0; i < sz; ++i) {
arg = p->get_arg(i);
sort* s = arg->get_sort();
while (a.is_array(s)) {
unsigned arity = get_array_arity(s);
for (unsigned j = 0; j < arity; ++j) {
args.push_back(m.mk_var(idx++, get_array_domain(s, j)));
}
arg = mk_select(arg, arity, args.c_ptr()+args.size()-arity);
s = get_array_range(s);
}
args.push_back(arg);
}
TRACE("dl",
tout << mk_pp(new_p, m) << "\n";
for (unsigned i = 0; i < args.size(); ++i) {
tout << mk_pp(args[i].get(), m) << "\n";
});
return app_ref(m.mk_app(new_p, args.size(), args.c_ptr()), m);
}
app_ref mk_quantifier_abstraction::mk_tail(rule_set const& rules, rule_set& dst, app* p) {
func_decl* old_p = p->get_decl();
func_decl* new_p = declare_pred(rules, dst, old_p);
if (!new_p) {
return app_ref(p, m);
}
SASSERT(new_p->get_arity() > old_p->get_arity());
unsigned num_extra_args = new_p->get_arity() - old_p->get_arity();
var_shifter shift(m);
expr_ref p_shifted(m);
shift(p, num_extra_args, p_shifted);
app* ps = to_app(p_shifted);
expr_ref_vector args(m);
app_ref_vector pats(m);
sort_ref_vector vars(m);
svector<symbol> names;
expr_ref arg(m);
unsigned idx = 0;
unsigned sz = p->get_num_args();
for (unsigned i = 0; i < sz; ++i) {
arg = ps->get_arg(i);
sort* s = arg->get_sort();
bool is_pattern = false;
while (a.is_array(s)) {
is_pattern = true;
unsigned arity = get_array_arity(s);
for (unsigned j = 0; j < arity; ++j) {
vars.push_back(get_array_domain(s, j));
names.push_back(symbol(idx));
args.push_back(m.mk_var(idx++, vars.back()));
}
arg = mk_select(arg, arity, args.c_ptr()+args.size()-arity);
s = get_array_range(s);
}
if (is_pattern) {
pats.push_back(to_app(arg));
}
args.push_back(arg);
}
expr* pat = nullptr;
expr_ref pattern(m);
pattern = m.mk_pattern(pats.size(), pats.c_ptr());
pat = pattern.get();
app_ref result(m);
symbol qid, skid;
result = m.mk_app(new_p, args.size(), args.c_ptr());
result = m.mk_eq(m.mk_forall(vars.size(), vars.c_ptr(), names.c_ptr(), result, 1, qid, skid, 1, &pat), m.mk_true());
return result;
}
expr * mk_quantifier_abstraction::mk_select(expr* arg, unsigned num_args, expr* const* args) {
ptr_vector<expr> args2;
args2.push_back(arg);
args2.append(num_args, args);
return a.mk_select(args2.size(), args2.c_ptr());
}
rule_set * mk_quantifier_abstraction::operator()(rule_set const & source) {
if (!m_ctx.quantify_arrays()) {
return nullptr;
}
unsigned sz = source.get_num_rules();
for (unsigned i = 0; i < sz; ++i) {
rule& r = *source.get_rule(i);
if (r.has_negation()) {
return nullptr;
}
}
m_refs.reset();
m_old2new.reset();
m_new2old.reset();
rule_manager& rm = source.get_rule_manager();
rule_ref new_rule(rm);
expr_ref_vector tail(m);
app_ref head(m);
expr_ref fml(m);
rule_counter& vc = rm.get_counter();
if (m_ctx.get_model_converter()) {
m_mc = alloc(qa_model_converter, m);
}
scoped_ptr<rule_set> result = alloc(rule_set, m_ctx);
for (unsigned i = 0; i < sz; ++i) {
tail.reset();
rule & r = *source.get_rule(i);
TRACE("dl", r.display(m_ctx, tout); );
unsigned cnt = vc.get_max_rule_var(r)+1;
unsigned utsz = r.get_uninterpreted_tail_size();
unsigned tsz = r.get_tail_size();
for (unsigned j = 0; j < utsz; ++j) {
tail.push_back(mk_tail(source, *result, r.get_tail(j)));
}
for (unsigned j = utsz; j < tsz; ++j) {
tail.push_back(r.get_tail(j));
}
head = mk_head(source, *result, r.get_head(), cnt);
fml = m.mk_implies(m.mk_and(tail.size(), tail.c_ptr()), head);
proof_ref pr(m);
rm.mk_rule(fml, pr, *result, r.name());
TRACE("dl", result->last()->display(m_ctx, tout););
}
// proof converter: proofs are not necessarily preserved using this transformation.
if (m_old2new.empty()) {
dealloc(m_mc);
result = nullptr;
}
else {
m_ctx.add_model_converter(m_mc);
}
m_mc = nullptr;
return result.detach();
}
};
| 13,092 | 4,262 |
#pragma once
#include <ATen/ATen.h>
#include <c10/util/accumulate.h>
#include <c10d/Types.hpp>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
typedef SSIZE_T ssize_t;
#pragma comment(lib, "Ws2_32.lib")
#else
#include <fcntl.h>
#include <netdb.h>
#include <sys/poll.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <sys/types.h>
#include <chrono>
#include <cstdint>
#include <cstdlib>
#include <functional>
#include <limits>
#include <string>
#include <system_error>
#include <tuple>
#include <vector>
namespace c10d {
// Distributed c10d debug levels
enum DistributedDebugLevel {
OFF = 0,
DETAIL = 1,
INFO = 2,
};
// String debug log levels
extern const char* kDistDebugEnvVar;
extern const char* kDistDebugDetailLogLevel;
extern const char* kDistDebugInfoLogLevel;
extern const char* kDistDebugOffLogLevel;
std::string parse_env(const char* env_var_name);
DistributedDebugLevel parseDistDebugLevel();
// Turns at::IntArrayRef into "(1, 2, 3, 4)".
inline std::string toString(at::IntArrayRef l) {
std::stringstream ss;
ss << "(";
for (size_t i = 0; i < l.size(); i++) {
if (i > 0) {
ss << ", ";
}
ss << l[i];
}
ss << ")";
return ss.str();
}
inline std::string toString(const c10::Layout& layout) {
std::stringstream ss;
ss << layout;
return ss.str();
}
inline void assertSameType(
const at::DeprecatedTypeProperties& type,
const std::vector<at::Tensor>& tensors) {
for (size_t i = 0; i < tensors.size(); i++) {
if (!tensors[i].options().type_equal(type.options())) {
const std::string expected = type.toString();
const std::string actual = tensors[i].toString();
throw std::invalid_argument(
"mixed types (" + expected + " and " + actual + ")");
}
}
}
inline bool parseEnvVarFlag(const char* envVarName) {
char* stringValue = std::getenv(envVarName);
if (stringValue != nullptr) {
int val;
try {
val = std::stoi(stringValue);
} catch (std::exception& e) {
throw std::runtime_error(
"Invalid value for environment variable: " + std::string(envVarName));
}
if (val == 1) {
return true;
} else if (val == 0) {
return false;
} else {
throw std::runtime_error(
"Invalid value for environment variable: " + std::string(envVarName));
}
}
return false;
}
inline void assertSameSizes(
const at::IntArrayRef& sizes,
const std::vector<at::Tensor>& tensors) {
for (size_t i = 0; i < tensors.size(); i++) {
if (!tensors[i].sizes().equals(sizes)) {
const auto expected = toString(sizes);
const auto actual = toString(tensors[i].sizes());
throw std::invalid_argument(
"mixed sizes (" + expected + " and " + actual + ")");
}
}
}
inline void assertSameSizeAndType(const std::vector<at::Tensor>& tensors) {
// Ensure we have at least one tensor
if (tensors.size() == 0) {
throw std::invalid_argument("argument is empty");
}
// Ensure all tensors have identical type and shape
auto options = tensors[0].options();
auto sizes = tensors[0].sizes();
for (size_t i = 1; i < tensors.size(); i++) {
if (!tensors[i].options().type_equal(options)) {
const auto expected = toString(options);
const auto actual = toString(tensors[i].options());
throw std::invalid_argument(
"argument contains mixed types (" + expected + " and " + actual +
")");
}
if (!tensors[i].sizes().equals(sizes)) {
const auto expected = toString(sizes);
const auto actual = toString(tensors[i].sizes());
throw std::invalid_argument(
"argument contains mixed sizes (" + expected + " and " + actual +
")");
}
}
}
inline void assertTypeMatch(
std::function<void(const std::string&)> fn,
const at::DeprecatedTypeProperties& type,
const at::ArrayRef<at::Tensor> tensors,
size_t index) {
if (!tensors[index].options().type_equal(type.options())) {
fn("invalid tensor type at index " + std::to_string(index) + " (expected " +
type.toString() + ", got " + tensors[index].toString() + ")");
}
}
inline void assertTypeMatch(
std::function<void(const std::string&)> fn,
const at::TensorOptions& options,
const at::ArrayRef<at::Tensor> tensors,
size_t index) {
if (!tensors[index].options().type_equal(options)) {
fn("invalid tensor type at index " + std::to_string(index) + " (expected " +
toString(options) + ", got " + toString(tensors[index].options()) + ")");
}
}
inline void assertSizesMatch(
std::function<void(const std::string&)> fn,
const at::IntArrayRef& sizes,
const at::ArrayRef<at::Tensor> tensors,
size_t index) {
if (tensors[index].sizes() != sizes) {
fn("invalid tensor size at index " + std::to_string(index) + " (expected " +
toString(sizes) + ", got " + toString(tensors[index].sizes()) + ")");
}
}
inline void assertLayoutMatch(
std::function<void(const std::string&)> fn,
const c10::Layout& expected,
const at::ArrayRef<at::Tensor> tensors,
size_t index) {
const auto& actual = tensors[index].layout();
if (actual != expected) {
fn("invalid tensor layout at index " + std::to_string(index) +
" (expected " + toString(expected) + ", got " + toString(actual) + ")");
}
}
inline void assertLayoutMatch(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors) {
const auto& layout = tensors[0].layout();
for (size_t i = 1; i < tensors.size(); i++) {
assertLayoutMatch(fn, layout, tensors, i);
}
}
inline void assertNonEmpty(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors) {
if (tensors.size() == 0) {
fn("requires non-empty tensor list");
}
}
inline void assertSingleElement(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors) {
if (tensors.size() != 1) {
fn("requires a single-element tensor list");
}
}
inline void assertSingleElementInput(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors) {
if (tensors.size() != 1) {
fn("requires a single-element input tensor list");
}
}
inline void assertSingleElementOutput(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors) {
if (tensors.size() != 1) {
fn("requires a single-element output tensor list");
}
}
inline void assertRootRank(
std::function<void(const std::string&)> fn,
int rank,
int size) {
if (rank < 0 || rank >= size) {
fn("invalid root rank: " + std::to_string(rank));
}
}
inline void assertRootTensor(
std::function<void(const std::string&)> fn,
int rank,
int size) {
if (rank < 0 || rank >= size) {
fn("invalid root tensor: " + std::to_string(rank));
}
}
inline void assertDense(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors) {
const auto& layout = tensors[0].layout();
if (layout != at::kStrided) {
fn("only supports dense tensors");
}
}
inline void assertCPU(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors) {
const auto& device = tensors[0].device();
if (device.type() != at::kCPU) {
fn("only supports CPU tensors");
}
}
inline void assertSameDevice(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors) {
if (tensors.size() < 2) {
return;
}
const auto& device = tensors[0].device();
for (int i = 1; i < tensors.size(); ++i) {
if (tensors[i].device() != device) {
fn("tensors should be on the same device");
}
}
}
inline void assertTypeAndSizesMatch(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors,
const at::DeprecatedTypeProperties& type,
const at::IntArrayRef& sizes) {
for (size_t i = 0; i < tensors.size(); i++) {
assertTypeMatch(fn, type, tensors, i);
assertSizesMatch(fn, sizes, tensors, i);
}
}
inline void assertTypeAndSizesMatch(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors,
const at::TensorOptions& options,
const at::IntArrayRef& sizes) {
for (size_t i = 0; i < tensors.size(); i++) {
assertTypeMatch(fn, options, tensors, i);
assertSizesMatch(fn, sizes, tensors, i);
}
}
inline void assertTypeAndSizesMatch(
std::function<void(const std::string&)> fn,
const at::ArrayRef<at::Tensor> tensors) {
const auto& options = tensors[0].options();
const auto sizes = tensors[0].sizes();
assertTypeAndSizesMatch(fn, tensors.slice(1), options, sizes);
}
// Copied from ATen/core/functional.h.
template <typename F, typename T>
inline auto fmap(T& inputs, const F& fn)
-> std::vector<decltype(fn(*inputs.begin()))> {
std::vector<decltype(fn(*inputs.begin()))> r;
r.reserve(inputs.size());
for (auto& input : inputs) {
r.push_back(fn(input));
}
return r;
}
// Copied from torch/csrc/utils/tensor_flatten.h.
inline at::Tensor flattenDenseTensors(at::TensorList tensors) {
static const auto flatten = [](const at::Tensor& t) {
return t.contiguous().view({-1});
};
if (tensors.size() == 1) {
return flatten(tensors[0]);
}
return at::cat(::c10d::fmap(tensors, flatten));
}
inline at::Tensor newLikeFlat(
std::vector<std::vector<at::Tensor>>& tensors,
size_t deviceIdx) {
if (tensors.size() == 0 || tensors[0].size() == 0) {
throw std::runtime_error("Received an empty list");
}
if (deviceIdx >= tensors.size()) {
throw std::runtime_error("Invalid device index");
}
auto& t = tensors[deviceIdx][0];
auto device = t.device();
for (size_t i = 1; i < tensors[deviceIdx].size(); ++i) {
if (tensors[deviceIdx][i].device() != device) {
throw std::runtime_error("Expecting all tensors on the same device");
}
}
at::DeviceGuard gpuGuard(device);
std::vector<int64_t> sizes{static_cast<int64_t>(tensors[deviceIdx].size())};
std::vector<int64_t> strides{static_cast<int64_t>(t.numel())};
sizes.insert(sizes.end(), t.sizes().begin(), t.sizes().end());
strides.insert(strides.end(), t.strides().begin(), t.strides().end());
return at::empty_strided(
sizes, strides, t.options().memory_format(c10::nullopt));
}
inline at::Tensor newLikeFlat(std::vector<at::Tensor>& tensors) {
if (tensors.size() == 0) {
throw std::runtime_error("Received an empty list");
}
auto& t = tensors[0];
at::DeviceGuard gpuGuard(t.device());
std::vector<int64_t> sizes{static_cast<int64_t>(tensors.size())};
sizes.insert(sizes.end(), t.sizes().begin(), t.sizes().end());
return at::empty(sizes, t.options());
}
inline std::vector<std::vector<int64_t>> getSizes(
const std::vector<at::Tensor>& tensors) {
std::vector<std::vector<int64_t>> sizes(tensors.size());
for (size_t i = 0; i < tensors.size(); i++) {
sizes[i] = tensors[i].sizes().vec();
}
return sizes;
}
inline std::vector<int> getDevices(const std::vector<at::Tensor>& tensors) {
std::vector<int> devices(tensors.size(), -1);
if (tensors[0].device().is_cuda()) {
for (size_t i = 0; i < tensors.size(); i++) {
devices[i] = tensors[i].storage().device().index();
}
}
return devices;
}
template <typename T>
inline T* getDataPointer(const at::Tensor& tensor) {
// This method is only used in ProcessGroupGloo for now. Call sites must make
// sure that the input tensor is contiguous. It is OK if the tensor does not
// start from the beginning of the storage. For example, it could come from
// chunk(..., dim=0)[1]. Hence, we need to use data_ptr() instead of
// tensor.storage().data()
// NB: not using tensor.data<T>() because tensor is not aware of gloo::TYPE
return static_cast<T*>(tensor.data_ptr());
}
template <typename T>
std::vector<T*> getDataPointers(const std::vector<at::Tensor>& tensors) {
std::vector<T*> ptrs(tensors.size());
for (size_t i = 0; i < tensors.size(); i++) {
ptrs[i] = getDataPointer<T>(tensors[i]);
}
return ptrs;
}
// For alltoall split size sanity check
inline void checkSplitSizes(
const std::vector<int64_t>& split_sizes,
const at::Tensor& tensor,
int group_size) {
if (split_sizes.size() == 0) {
TORCH_CHECK(
tensor.size(0) % group_size == 0,
"Tensor's dim 0 does not divide equally across group size");
} else {
TORCH_CHECK(
split_sizes.size() == group_size,
"Number of tensor splits not equal to group size");
const auto sum = c10::sum_integers(split_sizes);
TORCH_CHECK(
sum == tensor.size(0), "Split sizes doesn't match total dim 0 size");
}
}
// Compute alltoall lengths and offsets, handling multi-dimension tensors
template <typename T>
size_t computeLengthsAndOffsets(
const std::vector<int64_t>& split_sizes,
const at::Tensor& tensor,
std::vector<T>* lengths,
std::vector<T>* offsets) {
size_t group_size = lengths->size();
bool equal_splits = false;
size_t dim0_size = tensor.size(0);
size_t row_size = (dim0_size ? tensor.numel() / dim0_size : 1);
size_t split_size = 0;
size_t offset = 0;
if (split_sizes.size() == 0) {
equal_splits = true;
split_size = tensor.size(0) / group_size;
}
for (int i = 0; i < group_size; i++) {
size_t length = row_size * (equal_splits ? split_size : split_sizes[i]);
TORCH_INTERNAL_ASSERT(
length <= std::numeric_limits<int>::max() &&
offset <= std::numeric_limits<int>::max(),
"Length or offset larger than INT_MAX not supported");
(*lengths)[i] = length;
(*offsets)[i] = offset;
offset += length;
}
return offset;
}
template <typename T>
size_t computeLengthsAndOffsets(
const std::vector<at::Tensor>& tensors,
std::vector<T>* lengths,
std::vector<T>* offsets) {
size_t group_size = lengths->size();
size_t offset = 0;
for (int i = 0; i < group_size; i++) {
size_t length = tensors[i].numel();
TORCH_INTERNAL_ASSERT(
length <= std::numeric_limits<int>::max() &&
offset <= std::numeric_limits<int>::max(),
"Length or offset larger than INT_MAX not supported");
(*lengths)[i] = length;
(*offsets)[i] = offset;
offset += length;
}
return offset;
}
using RankType = uint32_t;
using PortType = uint16_t;
using SizeType = uint64_t;
// `errno` is only meaningful when it fails. E.g., a successful `fork()` sets
// `errno` to `EINVAL` in child process on some macos
// (https://stackoverflow.com/a/20295079), and thus `errno` should really only
// be inspected if an error occurred.
//
// `success_cond` is an expression used to check if an error has happend. So for
// `fork()`, we can use `SYSCHECK(pid = fork(), pid != -1)`. The function output
// is stored in variable `__output` and may be used in `success_cond`.
#ifdef _WIN32
#define SYSCHECK(expr, success_cond) \
while (true) { \
auto __output = (expr); \
auto errno_local = WSAGetLastError(); \
(void)__output; \
if (!(success_cond)) { \
if (errno == EINTR) { \
continue; \
} else if ( \
errno_local == WSAETIMEDOUT || errno_local == WSAEWOULDBLOCK) { \
throw std::runtime_error("Socket Timeout"); \
} else { \
throw std::system_error(errno_local, std::system_category()); \
} \
} else { \
break; \
} \
}
#else
#define SYSCHECK(expr, success_cond) \
while (true) { \
auto __output = (expr); \
(void)__output; \
if (!(success_cond)) { \
if (errno == EINTR) { \
continue; \
} else if (errno == EAGAIN || errno == EWOULDBLOCK) { \
throw std::runtime_error("Socket Timeout"); \
} else { \
throw std::system_error(errno, std::system_category()); \
} \
} else { \
break; \
} \
}
#endif
// Most functions indicate error by returning `-1`. This is a helper macro for
// this common case with `SYSCHECK`.
// Since SOCKET_ERROR = -1 in MSVC, so also leverage SYSCHECK_ERR_RETURN_NEG1
#define SYSCHECK_ERR_RETURN_NEG1(expr) SYSCHECK(expr, __output != -1)
// Helper resource guard class
class ResourceGuard {
public:
ResourceGuard(std::function<void()> destructor)
: destructor_(std::move(destructor)), released_(false) {}
~ResourceGuard() {
if (!released_) {
destructor_();
}
}
void release() {
released_ = true;
}
private:
std::function<void()> destructor_;
bool released_;
};
namespace tcputil {
constexpr std::chrono::milliseconds kNoTimeout = std::chrono::milliseconds(-1);
const std::string kConnectTimeoutMsg = "connect() timed out.";
// Send and receive
template <typename T>
void sendBytes(
int socket,
const T* buffer,
size_t length,
bool moreData = false) {
size_t bytesToSend = sizeof(T) * length;
if (bytesToSend == 0) {
return;
}
auto bytes = reinterpret_cast<const uint8_t*>(buffer);
uint8_t* currentBytes = const_cast<uint8_t*>(bytes);
int flags = 0;
#ifdef MSG_MORE
if (moreData) { // there is more data to send
flags |= MSG_MORE;
}
#endif
// Ignore SIGPIPE as the send() return value is always checked for error
#ifdef MSG_NOSIGNAL
flags |= MSG_NOSIGNAL;
#endif
while (bytesToSend > 0) {
ssize_t bytesSent;
SYSCHECK_ERR_RETURN_NEG1(
bytesSent =
::send(socket, (const char*)currentBytes, bytesToSend, flags))
if (bytesSent == 0) {
throw std::system_error(ECONNRESET, std::system_category());
}
bytesToSend -= bytesSent;
currentBytes += bytesSent;
}
}
template <typename T>
void recvBytes(int socket, T* buffer, size_t length) {
size_t bytesToReceive = sizeof(T) * length;
if (bytesToReceive == 0) {
return;
}
auto bytes = reinterpret_cast<uint8_t*>(buffer);
uint8_t* currentBytes = bytes;
while (bytesToReceive > 0) {
ssize_t bytesReceived;
SYSCHECK_ERR_RETURN_NEG1(
bytesReceived = recv(socket, (char*)currentBytes, bytesToReceive, 0))
if (bytesReceived == 0) {
throw std::system_error(ECONNRESET, std::system_category());
}
bytesToReceive -= bytesReceived;
currentBytes += bytesReceived;
}
}
// send a vector's length and data
template <typename T>
void sendVector(int socket, const std::vector<T>& vec, bool moreData = false) {
SizeType size = vec.size();
sendBytes<SizeType>(socket, &size, 1, true);
sendBytes<T>(socket, vec.data(), size, moreData);
}
// receive a vector as sent in sendVector
template <typename T>
std::vector<T> recvVector(int socket) {
SizeType valueSize;
recvBytes<SizeType>(socket, &valueSize, 1);
std::vector<T> value(valueSize);
recvBytes<T>(socket, value.data(), value.size());
return value;
}
// this is only for convenience when sending rvalues
template <typename T>
void sendValue(int socket, const T& value, bool moreData = false) {
sendBytes<T>(socket, &value, 1, moreData);
}
template <typename T>
T recvValue(int socket) {
T value;
recvBytes<T>(socket, &value, 1);
return value;
}
// send a string's length and data
inline void sendString(
int socket,
const std::string& str,
bool moreData = false) {
SizeType size = str.size();
sendBytes<SizeType>(socket, &size, 1, true);
sendBytes<char>(socket, str.data(), size, moreData);
}
// receive a string as sent in sendString
inline std::string recvString(int socket) {
SizeType valueSize;
recvBytes<SizeType>(socket, &valueSize, 1);
std::vector<char> value(valueSize);
recvBytes<char>(socket, value.data(), value.size());
return std::string(value.data(), value.size());
}
// Other helpers
std::string sockaddrToString(struct sockaddr* addr);
std::pair<int, PortType> listen(PortType port);
int connect(
const std::string& address,
PortType port,
bool wait = true,
const std::chrono::milliseconds& timeout = kNoTimeout);
std::tuple<int, std::string> accept(
int listenSocket,
const std::chrono::milliseconds& timeout = kNoTimeout);
} // namespace tcputil
} // namespace c10d
| 21,382 | 7,197 |
/*
// Copyright (c) 2016 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
///////////////////////////////////////////////////////////////////////////////////////////////////
#include <gtest/gtest.h>
#include "api/CPP/memory.hpp"
#include <api/CPP/input_layout.hpp>
#include "api/CPP/reorder.hpp"
#include <api/CPP/topology.hpp>
#include <api/CPP/network.hpp>
#include <api/CPP/engine.hpp>
#include "test_utils/test_utils.h"
#include <api/CPP/data.hpp>
#include <cmath>
#include <gmock/gmock.h>
#include <limits>
using namespace cldnn;
using namespace tests;
using namespace testing;
TEST(reorder_gpu_f32, basic)
{
// Input : yxfb:2x2x2x2
// Output : bfyx:2x2x2x2
//
// Input:
// f0: b0: 1 2 b1: 0 0
// f0: b0: 3 4 b1: 0.5 -0.5
// f1: b0: 5 6 b1: 1.5 5.2
// f1: b0: 7 8 b1: 12 8
//
// Output:
// b0 f0: 1 2
// b0 f0: 3 4
//
// b0 f1: 5 6
// b0 f1: 7 8
//
// b1 f0: 0 0
// b1 f0: 0.5 -0.5
//
// b1 f1: 1.5 5.2
// b1 f1: 12 8
//
engine engine;
auto input = memory::allocate(engine, { data_types::f32, format::yxfb, { 2, 2, 2, 2 } });
layout output_layout(data_types::f32, format::bfyx,{ 2,2,2,2 });
set_values(input, {
1.f, 0.f,
5.f, 1.5f,
2.f, 0.f,
6.f, 5.2f,
3.f, 0.5f,
7.f, 12.f,
4.f, -0.5f,
8.f, 8.f
});
topology topology(
input_layout("input", input.get_layout()),
reorder("reorder", "input", output_layout));
network network(engine, topology);
network.set_input_data("input", input);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(1));
EXPECT_EQ(outputs.begin()->first, "reorder");
auto output = outputs.begin()->second.get_memory();
float answers[16] = {
1.0f, 2.0f,
3.0f, 4.0f,
5.0f, 6.0f,
7.0f, 8.0f,
0.0f, 0.0f,
0.5f, -0.5f,
1.5f, 5.2f,
12.0f, 8.0f
};
auto output_ptr = output.pointer<float>();
for (int i = 0; i < 16; i++)
{
EXPECT_FLOAT_EQ(answers[i], output_ptr[i]);
}
}
TEST(reorder_gpu_f32, basic_subtract) {
// Input : 2x2x2x2
// Output : 2x2x2x2
// Subtract : 1x2x2x2 (only first batch is taken into consideration)
//
// Input:
// f0: b0: 1 2 b1: 0 0
// f0: b0: 3 4 b1: 0.5 -0.5
// f1: b0: 5 6 b1: 1.5 5.2
// f1: b0: 7 8 b1: 12 8
//
// Subtract:
// f0: b0: 1 1.5
// f0: b0: 2 2.5
// f1: b0: 4 3
// f1: b0: 2 1
//
//
// Output:
// b0 f0: 0 0.5
// b0 f0: 1 1.5
//
// b0 f1: 1 3
// b0 f1: 5 7
//
// b1 f0: -1 -1.5
// b1 f0: -1.5 -3
//
// b1 f1: -2.5 2.2
// b1 f1: 10 7
//
engine engine;
auto input = memory::allocate(engine, { data_types::f32, format::yxfb, { 2, 2, 2, 2 } });
layout output_layout( data_types::f32, format::bfyx, {2,2,2,2} );
auto subtract = memory::allocate(engine, { data_types::f32, format::byxf, { 1, 2, 2, 2 } });
set_values(input, {
1.f, 0.f,
5.f, 1.5f,
2.f, 0.f,
6.f, 5.2f,
3.f, 0.5f,
7.f, 12.f,
4.f, -0.5f,
8.f, 8.f
});
set_values(subtract, {
1.0f, 4.0f, 1.5f, 3.0f,
2.0f, 2.0f, 2.5f, 1.0f,
});
topology topology(
input_layout("input", input.get_layout()),
input_layout("subtract", subtract.get_layout()),
reorder("reorder", "input", output_layout, "subtract"));
network network(engine, topology);
network.set_input_data("input", input);
network.set_input_data("subtract", subtract);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(1));
EXPECT_EQ(outputs.begin()->first, "reorder");
auto output = outputs.begin()->second.get_memory();
float answers[16] = { 0.0f, 0.5f,
1.0f, 1.5f,
1.0f, 3.0f,
5.0f, 7.0f,
-1.0f, -1.5f,
-1.5f, -3.0f,
-2.5f, 2.2f,
10.0f, 7.0f
};
auto output_ptr = output.pointer<float>();
for (int i = 0; i < 16; i++)
{
EXPECT_FLOAT_EQ(answers[i], output_ptr[i]);
}
}
TEST(reorder_gpu_f32, basic_subtract_value) {
// Values_to_subtract : 2
// Input : 2x2x2x2
// Output : 2x2x2x2
//
// Input:
// f0: b0: 1 2 b1: 0 0
// f0: b0: 3 4 b1: 0.5 -0.5
// f1: b0: 5 6 b1: 1.5 5.2
// f1: b0: 7 8 b1: 12 8
//
// subtract values
// f0: 0.5
// f1: 2.5
//
// Output:
// b0 f0: 0.5 1.5
// b0 f0: 2.5 3.5
//
// b0 f1: 2.5 3.5
// b0 f1: 4.5 5.5
//
// b1 f0: -0.5 -0.5
// b1 f0: 0.0 -1.0
//
// b1 f1: -1.0 2.7
// b1 f1: 9.5 5.5
//
engine engine;
auto input = memory::allocate(engine, { data_types::f32, format::yxfb, { 2, 2, 2, 2 } });
layout output_layout(data_types::f32, format::bfyx,{ 2,2,2,2 });
std::vector<float> subtract_val = { 0.5, 2.5 };
set_values(input, {
1.f, 0.f,
5.f, 1.5f,
2.f, 0.f,
6.f, 5.2f,
3.f, 0.5f,
7.f, 12.f,
4.f, -0.5f,
8.f, 8.f
});
topology topology;
topology.add(input_layout("input", input.get_layout()), reorder("reorder", "input", output_layout, subtract_val));
network network(engine, topology);
network.set_input_data("input", input);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(1));
EXPECT_EQ(outputs.begin()->first, "reorder");
auto output = outputs.begin()->second.get_memory();
float answers[16] = { 0.5f, 1.5f,
2.5f, 3.5f,
2.5f, 3.5f,
4.5f, 5.5f,
-0.5f, -0.5f,
0.0f, -1.0f,
-1.0f, 2.7f,
9.5f, 5.5f
};
auto output_ptr = output.pointer<float>();
for (int i = 0; i < 16; i++)
{
EXPECT_TRUE(are_equal(answers[i], output_ptr[i]));
}
}
TEST(reorder_gpu_f16, basic_subtract_f32_output_f32) {
// Input : 2x2x2x2 (FP16)
// Output : 2x2x2x2 (FP32)
// Subtract : 1x2x2x2 (FP32, only first batch is taken into consideration)
//
// Input:
// f0: b0: 1 2 b1: 0 0
// f0: b0: 3 4 b1: 0.5 -0.5
// f1: b0: 5 6 b1: 1.5 5.2
// f1: b0: 7 8 b1: 12 8
//
// Subtract (FP32 - converted internally to FP16 before subtraction):
// f0: b0: 1 1.5
// f0: b0: 2 2.5
// f1: b0: 4 3
// f1: b0: 2 1
//
//
// Output:
// b0 f0: 0 0.5
// b0 f0: 1 1.5
//
// b0 f1: 1 3
// b0 f1: 5 7
//
// b1 f0: -1 -1.5
// b1 f0: -1.5 -3
//
// b1 f1: -2.5 2.2
// b1 f1: 10 7
//
engine engine;
if (!engine.get_info().supports_fp16)
{
std::cout << "[ SKIPPED ] The test is skipped (cl_khr_fp16 is not supported)." << std::endl;
EXPECT_EQ(1, 1);
return;
}
auto input = memory::allocate(engine, { data_types::f16, format::yxfb, { 2, 2, 2, 2 } });
layout output_layout(data_types::f32, format::bfyx,{ 2,2,2,2 });
auto subtract = memory::allocate(engine, { data_types::f32, format::byxf, { 1, 2, 2, 2 } });
set_values(input, {
half_t(0x3C00), half_t(0x0000), // 1.f, 0.f,
half_t(0x4500), half_t(0x3E00), // 5.f, 1.5f,
half_t(0x4000), half_t(0x0000), // 2.f, 0.f,
half_t(0x4600), half_t(0x4533), // 6.f, 5.2f,
half_t(0x4200), half_t(0x3800), // 3.f, 0.5f,
half_t(0x4700), half_t(0x4A00), // 7.f, 12.f,
half_t(0x4400), half_t(0xB800), // 4.f, -0.5f,
half_t(0x4800), half_t(0x4800) // 8.f, 8.f
});
set_values(subtract, {
1.0f, 4.0f, 1.5f, 3.0f,
2.0f, 2.0f, 2.5f, 1.0f,
});
topology topology;
topology.add(input_layout("input", input.get_layout()));
topology.add(data("subtract", subtract));
topology.add(reorder("reorder", "input", output_layout, "subtract"));
network network(engine, topology);
network.set_input_data("input", input);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(1));
EXPECT_EQ(outputs.begin()->first, "reorder");
auto output = outputs.begin()->second.get_memory();
float answers[16] = { 0.0f, 0.5f,
1.0f, 1.5f,
1.0f, 3.0f,
5.0f, 7.0f,
-1.0f, -1.5f,
-1.5f, -3.0f,
-2.5f, 2.2f,
10.0f, 7.0f
};
auto output_ptr = output.pointer<float>();
for (int i = 0; i < 16; i++)
{
EXPECT_TRUE(are_equal(answers[i], output_ptr[i]));
}
}
TEST(reorder_gpu_f16, basic_subtract_value) {
// Values_to_subtract : 2
// Input : 2x2x2x2 (FP16)
// Output : 2x2x2x2 (FP16)
//
// Input:
// f0: b0: 1 2 b1: 0 0
// f0: b0: 3 4 b1: 0.5 -0.5
// f1: b0: 5 6 b1: 1.5 5.2
// f1: b0: 7 8 b1: 12 8
//
// subtract values (FP32 - converted internally to FP16 before subtraction)
// f0: 0.5
// f1: 2.5
//
// Output:
// b0 f0: 0.5 1.5
// b0 f0: 2.5 3.5
//
// b0 f1: 2.5 3.5
// b0 f1: 4.5 5.5
//
// b1 f0: -0.5 -0.5
// b1 f0: 0.0 -1.0
//
// b1 f1: -1.0 2.7
// b1 f1: 9.5 5.5
//
engine engine;
if (!engine.get_info().supports_fp16)
{
std::cout << "[ SKIPPED ] The test is skipped (cl_khr_fp16 is not supported)." << std::endl;
EXPECT_EQ(1, 1);
return;
}
auto input = memory::allocate(engine, { data_types::f16, format::yxfb, { 2, 2, 2, 2 } });
layout output_layout(data_types::f16, format::bfyx,{ 2,2,2,2 });
std::vector<float> subtract_val = { 0.5, 2.5 };
set_values(input, {
half_t(0x3C00), half_t(0x0000), // 1.f, 0.f,
half_t(0x4500), half_t(0x3E00), // 5.f, 1.5f,
half_t(0x4000), half_t(0x0000), // 2.f, 0.f,
half_t(0x4600), half_t(0x4533), // 6.f, 5.2f,
half_t(0x4200), half_t(0x3800), // 3.f, 0.5f,
half_t(0x4700), half_t(0x4A00), // 7.f, 12.f,
half_t(0x4400), half_t(0xB800), // 4.f, -0.5f,
half_t(0x4800), half_t(0x4800) // 8.f, 8.f
});
topology topology;
topology.add(input_layout("input", input.get_layout()));
topology.add(reorder("reorder", "input", output_layout, subtract_val));
network network(engine, topology);
network.set_input_data("input", input);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(1));
EXPECT_EQ(outputs.begin()->first, "reorder");
auto output = outputs.begin()->second.get_memory();
half_t answers[16] = { half_t(0x3800), half_t(0x3E00), // 0.5f, 1.5f,
half_t(0x4100), half_t(0x4300), // 2.5f, 3.5f,
half_t(0x4100), half_t(0x4300), // 2.5f, 3.5f,
half_t(0x4480), half_t(0x4580), // 4.5f, 5.5f,
half_t(0xB800), half_t(0xB800), // -0.5f, -0.5f,
half_t(0x0000), half_t(0xBC00), // 0.0f, -1.0f,
half_t(0xBC00), half_t(0x4166), // -1.0f, 2.7f,
half_t(0x48C0), half_t(0x4580) // 9.5f, 5.5f
};
auto output_ptr = output.pointer<half_t>();
for (int i = 0; i < 16; i++)
{
EXPECT_TRUE(are_equal(static_cast<uint16_t>(answers[i]), static_cast<uint16_t>(output_ptr[i])));
}
}
TEST(reorder_gpu, basic_convert_f16_f32_f16) {
// Converts entire unambiguous range of FP16 numbers to FP32 and back.
//
// Input : 2x2x15873x1 (FP16)
// Intermediate : 1x2x2x15873 (FP32) {different mem format but the same ordering because batch is 1}
// Output : 2x2x15673x1 (FP16)
//
// Output is expected to contain the same value as input in range of indices from 0x0000 to 0xF801.
//
engine engine;
if (!engine.get_info().supports_fp16)
{
std::cout << "[ SKIPPED ] The test is skipped (cl_khr_fp16 is not supported)." << std::endl;
EXPECT_EQ(1, 1);
return;
}
std::vector<half_t> expected_values;
expected_values.resize(0xF804);
for (int i = 0; i < 0x7C00; ++i)
expected_values[i] = half_t(i); // norms/denorms/zero (positive).
for (int i = 0x7C00; i < 0xF800; ++i)
expected_values[i] = half_t(i + 0x0400); // norms/denorms (negative).
expected_values[0x7C00] = half_t(0x0000); // NOTE: do not do final test for negative 0 (-0).
// Special values.
expected_values[0xF800] = half_t(0x7C00); // +infinity
expected_values[0xF801] = half_t(0xFC00); // -infinity
// Special values (ambiguous ones).
expected_values[0xF802] = half_t(0x8000); // -0
expected_values[0xF803] = half_t(0xFC12); // A NaN (sample: -NaN.0x12).
auto input = memory::allocate(engine, { data_types::f16, format::yxfb, { 1, static_cast<int32_t>(expected_values.size()) / 4, 2, 2 } });
layout interm_layout( data_types::f32, format::byxf, { 1, static_cast<int32_t>(expected_values.size()) / 4, 2, 2 });
auto output_layout = input.get_layout();
set_values(input, expected_values);
topology topology;
topology.add(input_layout("input", input.get_layout()));
topology.add(reorder("reorder_f16_f32", "input", interm_layout));
topology.add(reorder("reorder_f32_f16", "reorder_f16_f32", output_layout));
network network(
engine,
topology,
{
build_option::outputs({"reorder_f16_f32", "reorder_f32_f16"})
});
network.set_input_data("input", input);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(2));
EXPECT_TRUE(outputs.find("reorder_f16_f32") != outputs.end());
EXPECT_TRUE(outputs.find("reorder_f32_f16") != outputs.end());
auto interm = outputs.at("reorder_f16_f32").get_memory();
auto interm_ptr = interm.pointer<float>();
// Sample positive.
EXPECT_TRUE(are_equal(interm_ptr[0x3400], 0.25f));
EXPECT_TRUE(are_equal(interm_ptr[0x3800], 0.5f));
EXPECT_TRUE(are_equal(interm_ptr[0x3C00], 1.0f));
EXPECT_TRUE(are_equal(interm_ptr[0x4000], 2.0f));
EXPECT_TRUE(are_equal(interm_ptr[0x4400], 4.0f));
// Sample negative.
EXPECT_TRUE(are_equal(interm_ptr[0x3400 + 0x7C00], -0.25f));
EXPECT_TRUE(are_equal(interm_ptr[0x3800 + 0x7C00], -0.5f));
EXPECT_TRUE(are_equal(interm_ptr[0x3C00 + 0x7C00], -1.0f));
EXPECT_TRUE(are_equal(interm_ptr[0x4000 + 0x7C00], -2.0f));
EXPECT_TRUE(are_equal(interm_ptr[0x4400 + 0x7C00], -4.0f));
// Special values.
EXPECT_TRUE(are_equal(interm_ptr[0xF800], std::numeric_limits<float>::infinity()));
EXPECT_TRUE(are_equal(interm_ptr[0xF801], -std::numeric_limits<float>::infinity()));
EXPECT_TRUE(are_equal(interm_ptr[0xF802], -0.0f));
EXPECT_TRUE(std::isnan(interm_ptr[0xF803]));
auto output = outputs.at("reorder_f32_f16").get_memory();
auto output_ptr = output.pointer<half_t>();
for (int i = 0; i < 0xF802; ++i) // NOTE: do not test for possibly ambiguous values of floating point (-0, NaNs).
{
EXPECT_TRUE(are_equal(static_cast<uint16_t>(expected_values[i]), static_cast<uint16_t>(output_ptr[i])));
}
}
TEST(DISABLED_reorder_gpu_f32, basic_flatten_yxfb_to_bx)
{
// Input : yxfb:2x2x2x2
// Output : bx:2x8
//
// Input:
// f0: b0: 1 2 b1: 0 0
// f0: b0: 3 4 b1: 0.5 -0.5
// f1: b0: 5 6 b1: 1.5 5.2
// f1: b0: 7 8 b1: 12 8
//
// Output:
// b0: 1 2 3 4 5 6 7 8
// b1: 0 0 0.5 -0.5 1.5 5.2 12 8
engine engine;
auto batch_num = 2;
auto feature_num = 2;
auto x_size = 2;
auto y_size = 2;
auto input = memory::allocate(engine, { data_types::f32, format::yxfb,{ batch_num, feature_num, x_size, y_size } });
layout output_layout(data_types::f32, format::bfyx,{ batch_num, 1, y_size * x_size * feature_num, 1 });
std::vector<float> input_vec = {
1.f, 0.f,
5.f, 1.5f,
2.f, 0.f,
6.f, 5.2f,
3.f, 0.5f,
7.f, 12.f,
4.f, -0.5f,
8.f, 8.f
};
set_values(input, input_vec);
topology topology(
input_layout("input", input.get_layout()),
reorder("reorder", "input", output_layout));
network network(engine, topology);
network.set_input_data("input", input);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(1));
EXPECT_EQ(outputs.begin()->first, "reorder");
auto output = outputs.begin()->second.get_memory();
auto output_ptr = output.pointer<float>();
for (int i = 0; i < batch_num; ++i) { //B
for (int j = 0; j < feature_num * y_size * x_size; ++j) { //F * Y * X
int linear_id_output = j + i * feature_num * y_size * x_size;
int cpos = j / (x_size * y_size);
int ypos = (j / x_size) % y_size;
int xpos = j % x_size;
int linear_id = i + batch_num * (cpos + feature_num * (xpos + x_size * ypos));
EXPECT_EQ(output_ptr[linear_id_output], input_vec[linear_id]);
}
}
}
TEST(DISABLED_reorder_gpu_f32, basic_flatten_yxfb_to_xb)
{
// Input : yxfb:2x2x2x2
// Output : bx:2x8
//
// Input:
// f0: b0: 1 2 b1: 0 0
// f0: b0: 3 4 b1: 0.5 -0.5
// f1: b0: 5 6 b1: 1.5 5.2
// f1: b0: 7 8 b1: 12 8
//
// Output:
// b0: 1 2 3 4 5 6 7 8
// b1: 0 0 0.5 -0.5 1.5 5.2 12 8
engine engine;
auto batch_num = 2;
auto feature_num = 2;
auto x_size = 2;
auto y_size = 2;
auto input = memory::allocate(engine, { data_types::f32, format::yxfb,{ batch_num, feature_num, x_size, y_size } });
layout output_layout(data_types::f32, format::yxfb,{ batch_num, 1, y_size * x_size * feature_num, 1 });
std::vector<float> input_vec = {
1.f, 0.f,
5.f, 1.5f,
2.f, 0.f,
6.f, 5.2f,
3.f, 0.5f,
7.f, 12.f,
4.f, -0.5f,
8.f, 8.f
};
set_values(input, input_vec);
topology topology(
input_layout("input", input.get_layout()),
reorder("reorder", "input", output_layout));
network network(engine, topology);
network.set_input_data("input", input);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(1));
EXPECT_EQ(outputs.begin()->first, "reorder");
auto output = outputs.begin()->second.get_memory();
auto output_ptr = output.pointer<float>();
std::vector<float> debug, debug2, debug3;
for (int j = 0; j < batch_num * feature_num * y_size * x_size; ++j) {
debug.push_back(output_ptr[j]);
}
for (int i = 0; i < batch_num; ++i) { //B
for (int j = 0; j < feature_num * y_size * x_size; ++j) { //F * Y * X
int linear_id_output = j * batch_num + i;
int cpos = j / (x_size * y_size);
int ypos = (j / x_size) % y_size;
int xpos = j % x_size;
int linear_id = i + batch_num * (cpos + feature_num * (xpos + x_size * ypos));
EXPECT_EQ(output_ptr[linear_id_output], input_vec[linear_id]);
}
}
}
TEST(DISABLED_reorder_gpu_f32, basic_flatten_bfyx_to_bx)
{
// Input : yxfb:2x2x2x2
// Output : bx:2x8
//
// Input:
// f0: b0: 1 2 b1: 0 0
// f0: b0: 3 4 b1: 0.5 -0.5
// f1: b0: 5 6 b1: 1.5 5.2
// f1: b0: 7 8 b1: 12 8
//
// Output:
// b0: 1 2 3 4 5 6 7 8
// b1: 0 0 0.5 -0.5 1.5 5.2 12 8
engine engine;
auto batch_num = 2;
auto feature_num = 2;
auto x_size = 2;
auto y_size = 2;
auto input = memory::allocate(engine, { data_types::f32,format::bfyx,{ batch_num, feature_num, x_size, y_size } });
layout output_layout(data_types::f32, format::bfyx,{ batch_num, 1, y_size * x_size * feature_num, 1 });
std::vector<float> input_vec = {
1.f, 2.f,
3.f, 4.f,
5.f, 6.f,
7.f, 8.f,
0.f, 0.f,
0.5f, -0.5f,
1.5f, 5.2f,
12.f, 8.f
};
set_values(input, input_vec);
topology topology(
input_layout("input", input.get_layout()),
reorder("reorder", "input", output_layout));
network network(engine, topology);
network.set_input_data("input", input);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(1));
EXPECT_EQ(outputs.begin()->first, "reorder");
auto output = outputs.begin()->second.get_memory();
auto output_ptr = output.pointer<float>();
for (int i = 0; i < batch_num; ++i) { //B
for (int j = 0; j < feature_num * y_size * x_size; ++j) { //F * Y * X
int linear_id = j + i * feature_num * y_size * x_size;
EXPECT_EQ(output_ptr[linear_id], input_vec[linear_id]);
}
}
}
TEST(DISABLED_reorder_gpu_f32, basic_flatten_yxfb_to_x)
{
// Input : yxfb:2x2x2x2
// Output : bx:2x8
//
// Input:
// f0: b0: 1 2 b1: 0 0
// f0: b0: 3 4 b1: 0.5 -0.5
// f1: b0: 5 6 b1: 1.5 5.2
// f1: b0: 7 8 b1: 12 8
//
// Output:
// 1 0 5 1.5 2 0 6 5.2 3 0.5 7 12 4 -0.5 8 8
engine engine;
auto batch_num = 2;
auto feature_num = 2;
auto x_size = 2;
auto y_size = 2;
auto input = memory::allocate(engine, { data_types::f32,format::yxfb,{ batch_num, feature_num, x_size, y_size } });
layout output_layout(data_types::f32, format::yxfb,{ 1, 1, y_size * x_size * feature_num * batch_num, 1 });
std::vector<float> input_vec = {
1.f, 0.f,
5.f, 1.5f,
2.f, 0.f,
6.f, 5.2f,
3.f, 0.5f,
7.f, 12.f,
4.f, -0.5f,
8.f, 8.f
};
set_values(input, input_vec);
topology topology(
input_layout("input", input.get_layout()),
reorder("reorder", "input", output_layout));
network network(engine, topology);
network.set_input_data("input", input);
auto outputs = network.execute();
EXPECT_EQ(outputs.size(), size_t(1));
EXPECT_EQ(outputs.begin()->first, "reorder");
auto output = outputs.begin()->second.get_memory();
auto output_ptr = output.pointer<float>();
for (int i = 0; i < batch_num; ++i) { //B
for (int j = 0; j < feature_num * y_size * x_size; ++j) { //F * Y * X
int linear_id_output = j * batch_num + i;
int cpos = j / (x_size * y_size);
int ypos = (j / x_size) % y_size;
int xpos = j % x_size;
int linear_id = i + batch_num * (cpos + feature_num * (xpos + x_size * ypos));
EXPECT_EQ(output_ptr[linear_id_output], input_vec[linear_id]);
}
}
}
using namespace cldnn;
class reorder_test : public tests::generic_test
{
public:
static void TearDownTestCase()
{
for (auto generic_params : all_generic_params)
{
delete generic_params;
}
for (auto test_param : all_test_params)
{
auto primitive = std::get<1>(test_param);
delete primitive;
}
}
static std::vector<std::tuple<test_params*, cldnn::primitive*>> generate_specific_test_params()
{
generic_test::generate_generic_test_params(all_generic_params, true);
const std::vector<cldnn::data_types> data_types = { cldnn::data_types::f32 , cldnn::data_types::f16 };
for (auto test_param : all_generic_params)
{
cldnn::tensor input_tensor = test_param->input_layouts[0];
std::vector<cldnn::layout> output_layouts = {};
for (auto dt : data_types)
{
for (auto fmt : generic_test::test_input_formats)
{
output_layouts.push_back({ dt, fmt, input_tensor });
}
}
// TODO: check unsupported formats.
//TODO: check subtract.
std::vector<float> subtract = {};
for (auto output_layout : output_layouts)
{
//TODO: check input + output padding.
all_test_params.push_back(std::make_tuple(test_param, new reorder("reorder", "input0", output_layout, subtract)));
}
}
return all_test_params;
}
virtual bool is_format_supported(cldnn::format format)
{
return ( (format == cldnn_format_type::cldnn_format_yxfb) ||
(format == cldnn_format_type::cldnn_format_byxf) ||
(format == cldnn_format_type::cldnn_format_bfyx) ||
(format == cldnn_format_type::cldnn_format_fyxb)
);
}
template<typename InputType, typename OutputType>
memory generate_reference_typed(const std::vector<cldnn::memory>& inputs)
{
const cldnn::reorder* reorder = (cldnn::reorder*)layer_params;
primitive_id mean = reorder->mean;
std::vector<float> subtract_per_feature = reorder->subtract_per_feature;
assert(mean == "");
assert(subtract_per_feature.size() == 0);
auto output = memory::allocate(engine, cldnn::layout(reorder->output_data_type, inputs[0].get_layout().format, inputs[0].get_layout().size));
cldnn::pointer<InputType> input_mem = inputs[0].pointer<InputType>();
cldnn::pointer<OutputType> output_mem = output.pointer<OutputType>();
for (size_t i = 0; i < inputs[0].get_layout().get_linear_size(); i++)
{
// Write the output in the same order as the input with type conversion as needed.
// The correct order will be checked in generic_test::compare_buffers.
output_mem[i] = (OutputType)input_mem[i];
}
return output;
}
virtual memory generate_reference(const std::vector<cldnn::memory>& inputs)
{
if (generic_params->data_type == data_types::f32)
{
if (((cldnn::reorder*)layer_params)->output_data_type == data_types::f32)
{
return generate_reference_typed<float, float>(inputs);
}
else
{
return generate_reference_typed<float, FLOAT16>(inputs);
}
}
else
{
if (((cldnn::reorder*)layer_params)->output_data_type == data_types::f32)
{
return generate_reference_typed<FLOAT16, float>(inputs);
}
else
{
return generate_reference_typed<FLOAT16, FLOAT16>(inputs);
}
}
}
private:
static std::vector<tests::test_params*> all_generic_params;
static std::vector<std::tuple<test_params*, cldnn::primitive*>> all_test_params;
};
std::vector<tests::test_params*> reorder_test::all_generic_params = {};
std::vector<std::tuple<test_params*, cldnn::primitive*>> reorder_test::all_test_params = {};
TEST_P(reorder_test, DISABLED_test_all)
{
run_single_test();
}
INSTANTIATE_TEST_CASE_P(REORDER,
reorder_test,
::testing::ValuesIn(reorder_test::generate_specific_test_params()),
tests::generic_test::custom_param_name_functor());
| 28,301 | 12,265 |
#pragma once
/**
@file
@brief check msg
@author MITSUNARI Shigeo(@herumi)
@license modified new BSD license
http://opensource.org/licenses/BSD-3-Clause
*/
#include <stdint.h>
#include <set>
#include <memory.h>
namespace bls_util {
const size_t MSG_SIZE = 32;
struct Msg {
uint8_t v[MSG_SIZE];
bool operator<(const Msg& rhs) const
{
for (size_t i = 0; i < MSG_SIZE; i++) {
if (v[i] < rhs.v[i]) return true;
if (v[i] > rhs.v[i]) return false;
}
return false;
}
bool operator==(const Msg& rhs) const
{
return memcmp(v, rhs.v, MSG_SIZE) == 0;
}
};
inline bool areAllMsgDifferent(const void *buf, size_t bufSize)
{
size_t n = bufSize / MSG_SIZE;
if (bufSize != n * MSG_SIZE) {
return false;
}
const Msg *msg = (const Msg*)buf;
typedef std::set<Msg> MsgSet;
MsgSet ms;
for (size_t i = 0; i < n; i++) {
std::pair<MsgSet::iterator, bool> ret = ms.insert(msg[i]);
if (!ret.second) return false;
}
return true;
}
} // bls_util
| 964 | 432 |
/*
* Copyright (C) 2015 Christopher Gilbert.
*
* 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.
*/
#define CATCH_CONFIG_MAIN
#include "../test/catch.hpp"
#include "chrono/utility/to_duration.hpp"
namespace cu = chrono::utility;
TEST_CASE("to_duration works as required", "[to_duration]") {
SECTION("std::string") {
std::string str("1s");
auto d = cu::to_duration<std::chrono::seconds>(str);
REQUIRE(d.count() == 1);
}
SECTION("std::wstring") {
std::wstring str(L"1s");
auto d = cu::to_duration<std::chrono::seconds>(str);
REQUIRE(d.count() == 1);
}
SECTION("char*") {
auto d = cu::to_duration<std::chrono::seconds>("1s");
REQUIRE(d.count() == 1);
}
SECTION("wchar_t*") {
std::string str("1s");
auto d = cu::to_duration<std::chrono::seconds>(L"1s");
REQUIRE(d.count() == 1);
}
SECTION("throws std::invalid_argument") {
REQUIRE_NOTHROW(cu::to_duration<std::chrono::seconds>(""));
REQUIRE_THROWS(cu::to_duration<std::chrono::seconds>("invalid"));
REQUIRE_THROWS(cu::to_duration<std::chrono::seconds>("12z"));
}
SECTION("nanoseconds") {
auto d = cu::to_duration<std::chrono::nanoseconds>("1ns");
REQUIRE(d.count() == 1);
}
SECTION("microseconds") {
auto d = cu::to_duration<std::chrono::microseconds>("1us");
REQUIRE(d.count() == 1);
}
SECTION("milliseconds") {
auto d = cu::to_duration<std::chrono::milliseconds>("1ms");
REQUIRE(d.count() == 1);
}
SECTION("seconds") {
auto d = cu::to_duration<std::chrono::seconds>("1s");
REQUIRE(d.count() == 1);
}
SECTION("minutes") {
auto d = cu::to_duration<std::chrono::minutes>("1m");
REQUIRE(d.count() == 1);
}
SECTION("hours") {
auto d = cu::to_duration<std::chrono::hours>("1h");
REQUIRE(d.count() == 1);
}
SECTION("combination") {
auto ns = cu::to_duration<std::chrono::nanoseconds>("1ns");
auto us = cu::to_duration<std::chrono::nanoseconds>("1us");
auto ms = cu::to_duration<std::chrono::nanoseconds>("1ms");
auto s = cu::to_duration<std::chrono::nanoseconds>("1s");
auto m = cu::to_duration<std::chrono::nanoseconds>("1m");
auto h = cu::to_duration<std::chrono::nanoseconds>("1h");
auto d = cu::to_duration<std::chrono::nanoseconds>("1h1m1s1ms1us1ns");
REQUIRE(d.count() == ns.count() + us.count() + ms.count() + s.count() + m.count() + h.count());
}
} | 3,318 | 1,338 |
/***************************************************************************
* 2005 by Axel Gonzalez *
* loox@e-shell.net *
* *
* This software is in the public domain. Permission to use, copy, *
* modify, and distribute this software and its documentation for any *
* purpose and without fee is hereby granted, without any conditions or *
* restrictions. This software is provided "as is" without express or *
* implied warranty. *
* *
***************************************************************************/
#include "ovPCRE.h"
ovPCRE::ovPCRE()
{
pattern = "*";
flags = 0;
options = 0;
error = NULL;
erroffset = 0;
re = NULL;
re = pcre_compile(pattern, flags, &error, &erroffset, NULL);
}
ovPCRE::ovPCRE(ovStr p)
{
pattern = p;
flags = 0;
options = 0;
error = NULL;
erroffset = 0;
re = NULL;
re = pcre_compile(pattern, flags, &error, &erroffset, NULL);
}
ovPCRE::ovPCRE(ovStr p, int f)
{
pattern = p;
flags = PCRE_CASELESS;
options = 0;
error = NULL;
erroffset = 0;
re = NULL;
re = pcre_compile(pattern, flags, &error, &erroffset, NULL);
}
ovPCRE::~ovPCRE()
{
if (re != NULL)
pcre_free(re);
}
void ovPCRE::SetPattern(ovStr p)
{
pattern = p;
flags = 0;
if (re != NULL)
pcre_free(re);
re = pcre_compile(pattern, flags, &error, &erroffset, NULL);
}
int ovPCRE::GetOptions()
{
return(this->flags);
}
void ovPCRE::SetOptions(int f)
{
this->flags = f;
}
int ovPCRE::Match(ovStr subject)
{
int rc;
if (re == NULL)
return(0);
rc = pcre_exec(re, NULL, subject, subject.Len(), 0, this->options, ovector, MAX_VECTORS);
if (rc < 0)
return(0);
return(ovector[0] + 1);
}
int ovPCRE::MatchAll(ovStr subject, ovStrArray &matches, unsigned int index)
{
int i;
int count, rc;
int offset;
const char **listptr;
ovStr str;
i = 0;
offset = 0;
if (index < 0)
index = 0;
matches.Clean();
while ((count = pcre_exec(re, NULL, subject, subject.Len(), offset, options, ovector, MAX_VECTORS)) > 0) {
rc = pcre_get_substring_list(subject, ovector, count, &listptr);
if (rc < 0)
return(0);
str = listptr[0];
offset = subject.strpos(str, offset) + str.Len();
str = listptr[index < count ? index : (count - 1)];
matches.Add(str);
pcre_free_substring_list(listptr);
i++;
}
//printf("COunt: %d\n", count);
return(i);
}
ovStr ovPCRE::Replace()
{
}
ovStr ovPCRE::Error()
{
if (error == NULL)
return("");
else
return(error);
}
| 3,012 | 1,040 |
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "../../include/pdfwindow/PDFWindow.h"
#include "../../include/pdfwindow/PWL_Wnd.h"
#include "../../include/pdfwindow/PWL_ListCtrl.h"
/* ---------------------------- CPWL_ListCtrl ---------------------------- */
CPWL_ListCtrl::CPWL_ListCtrl() :
m_rcContent(0,0,0,0),
m_ptScroll(0,0),
m_fItemSpace(0.0f),
m_fTopSpace(0.0f),
m_fBottomSpace(0.0f)
{
}
CPWL_ListCtrl::~CPWL_ListCtrl()
{
}
void CPWL_ListCtrl::SetScrollPos(const CPDF_Point& point)
{
m_ptScroll = point;
if (m_ptScroll.x < m_rcContent.left)
m_ptScroll.x = m_rcContent.left;
if (m_ptScroll.x > m_rcContent.right)
m_ptScroll.x = m_rcContent.right;
if (m_ptScroll.y > m_rcContent.top)
m_ptScroll.y = m_rcContent.top;
if (m_ptScroll.y < m_rcContent.bottom)
m_ptScroll.y = m_rcContent.bottom;
}
CPDF_Point CPWL_ListCtrl::GetScrollPos() const
{
return m_ptScroll;
}
CPDF_Rect CPWL_ListCtrl::GetScrollArea() const
{
return m_rcContent;
}
void CPWL_ListCtrl::ResetFace()
{
ResetAll(FALSE, 0);
}
void CPWL_ListCtrl::ResetContent(FX_INT32 nStart)
{
if (nStart < 0)
nStart = 0;
if (nStart >= 0 && nStart < m_aChildren.GetSize())
ResetAll(TRUE, nStart);
}
FX_FLOAT CPWL_ListCtrl::GetContentsHeight(FX_FLOAT fLimitWidth)
{
FX_FLOAT fRet = m_fTopSpace;
FX_FLOAT fBorderWidth = (FX_FLOAT)this->GetBorderWidth();
if (fLimitWidth > fBorderWidth* 2)
{
for (FX_INT32 i=0,sz=m_aChildren.GetSize(); i<sz; i++)
{
if (CPWL_Wnd* pChild = m_aChildren.GetAt(i))
{
FX_FLOAT fLeft = pChild->GetItemLeftMargin();
FX_FLOAT fRight = pChild->GetItemRightMargin();
fRet += pChild->GetItemHeight(fLimitWidth - fBorderWidth* 2 - fLeft - fRight);
fRet += m_fItemSpace;
}
}
fRet -= m_fItemSpace;
}
fRet += m_fBottomSpace;
return fRet;
}
void CPWL_ListCtrl::ResetAll(FX_BOOL bMove, FX_INT32 nStart)
{
CPDF_Rect rcClient = GetClientRect();
FX_FLOAT fWidth = rcClient.Width();
FX_FLOAT fy = 0.0f - m_fTopSpace;
if (nStart-1 >= 0 && nStart-1 < m_aChildren.GetSize())
if (CPWL_Wnd* pChild = m_aChildren.GetAt(nStart-1))
fy = pChild->GetWindowRect().bottom - m_fItemSpace;
for (FX_INT32 i=nStart,sz=m_aChildren.GetSize(); i<sz; i++)
{
if (CPWL_Wnd* pChild = m_aChildren.GetAt(i))
{
FX_FLOAT fLeft = pChild->GetItemLeftMargin();
FX_FLOAT fRight = pChild->GetItemRightMargin();
pChild->SetChildMatrix(
CPDF_Matrix(1,0,0,1,
rcClient.left - m_ptScroll.x,
rcClient.top - m_ptScroll.y)
);
if (bMove)
{
FX_FLOAT fItemHeight = pChild->GetItemHeight(fWidth - fLeft - fRight);
pChild->Move(CPDF_Rect(fLeft, fy-fItemHeight, fWidth - fRight, fy), TRUE, FALSE);
fy -= fItemHeight;
fy -= m_fItemSpace;
}
}
}
fy += m_fItemSpace;
fy -= m_fBottomSpace;
if (bMove)
{
m_rcContent.left = 0;
m_rcContent.top = 0;
m_rcContent.right = fWidth;
m_rcContent.bottom = fy;
}
}
void CPWL_ListCtrl::SetItemSpace(FX_FLOAT fSpace)
{
m_fItemSpace = fSpace;
}
void CPWL_ListCtrl::SetTopSpace(FX_FLOAT fSpace)
{
m_fTopSpace = fSpace;
}
void CPWL_ListCtrl::SetBottomSpace(FX_FLOAT fSpace)
{
m_fBottomSpace = fSpace;
}
void CPWL_ListCtrl::RePosChildWnd()
{
ResetFace();
}
void CPWL_ListCtrl::DrawChildAppearance(CFX_RenderDevice* pDevice, CPDF_Matrix* pUser2Device)
{
pDevice->SaveState();
CPDF_Rect rcClient = GetClientRect();
CPDF_Rect rcTemp = rcClient;
pUser2Device->TransformRect(rcTemp);
FX_RECT rcClip((FX_INT32)rcTemp.left,
(FX_INT32)rcTemp.bottom,
(FX_INT32)rcTemp.right,
(FX_INT32)rcTemp.top);
pDevice->SetClip_Rect(&rcClip);
for (FX_INT32 i=0,sz=m_aChildren.GetSize(); i<sz; i++)
{
if (CPWL_Wnd * pChild = m_aChildren.GetAt(i))
{
CPDF_Rect rcChild = pChild->ChildToParent(pChild->GetWindowRect());
if (!(rcChild.top < rcClient.bottom || rcChild.bottom > rcClient.top))
{
CPDF_Matrix mt = pChild->GetChildMatrix();
if (mt.IsIdentity())
{
pChild->DrawAppearance(pDevice,pUser2Device);
}
else
{
mt.Concat(*pUser2Device);
pChild->DrawAppearance(pDevice,&mt);
}
}
}
}
pDevice->RestoreState();
}
FX_INT32 CPWL_ListCtrl::GetItemIndex(CPWL_Wnd* pItem)
{
for (FX_INT32 i=0, sz=m_aChildren.GetSize(); i<sz; i++)
{
if (pItem == m_aChildren.GetAt(i))
return i;
}
return -1;
}
CPDF_Point CPWL_ListCtrl::InToOut(const CPDF_Point& point) const
{
CPDF_Rect rcClient = GetClientRect();
return CPDF_Point(point.x + rcClient.left - m_ptScroll.x,
point.y + rcClient.top - m_ptScroll.y);
}
CPDF_Point CPWL_ListCtrl::OutToIn(const CPDF_Point& point) const
{
CPDF_Rect rcClient = GetClientRect();
return CPDF_Point(point.x - rcClient.left + m_ptScroll.x,
point.y - rcClient.top + m_ptScroll.y);
}
CPDF_Rect CPWL_ListCtrl::InToOut(const CPDF_Rect& rect) const
{
CPDF_Rect rcClient = GetClientRect();
return CPDF_Rect(rect.left + rcClient.left - m_ptScroll.x,
rect.bottom + rcClient.top - m_ptScroll.y,
rect.right + rcClient.left - m_ptScroll.x,
rect.top + rcClient.top - m_ptScroll.y);
}
CPDF_Rect CPWL_ListCtrl::OutToIn(const CPDF_Rect& rect) const
{
CPDF_Rect rcClient = GetClientRect();
return CPDF_Rect(rect.left - rcClient.left + m_ptScroll.x,
rect.bottom - rcClient.top + m_ptScroll.y,
rect.right - rcClient.left + m_ptScroll.x,
rect.top - rcClient.top + m_ptScroll.y);
}
| 5,759 | 2,629 |
/*
* 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.
*/
#include "TcpRemotingClient.h"
#include <stddef.h>
#if !defined(WIN32) && !defined(__APPLE__)
#include <sys/prctl.h>
#endif
#include "Logging.h"
#include "MemoryOutputStream.h"
#include "TopAddressing.h"
#include "UtilAll.h"
namespace rocketmq {
//<!************************************************************************
TcpRemotingClient::TcpRemotingClient(int pullThreadNum,
uint64_t tcpConnectTimeout,
uint64_t tcpTransportTryLockTimeout)
: m_pullThreadNum(pullThreadNum),
m_tcpConnectTimeout(tcpConnectTimeout),
m_tcpTransportTryLockTimeout(tcpTransportTryLockTimeout),
m_namesrvIndex(0),
m_ioServiceWork(m_ioService) {
#if !defined(WIN32) && !defined(__APPLE__)
string taskName = UtilAll::getProcessName();
prctl(PR_SET_NAME, "networkTP", 0, 0, 0);
#endif
for (int i = 0; i != pullThreadNum; ++i) {
m_threadpool.create_thread(
boost::bind(&boost::asio::io_service::run, &m_ioService));
}
#if !defined(WIN32) && !defined(__APPLE__)
prctl(PR_SET_NAME, taskName.c_str(), 0, 0, 0);
#endif
LOG_INFO(
"m_tcpConnectTimeout:%ju, m_tcpTransportTryLockTimeout:%ju, "
"m_pullThreadNum:%d",
m_tcpConnectTimeout, m_tcpTransportTryLockTimeout, m_pullThreadNum);
m_async_service_thread.reset(new boost::thread(
boost::bind(&TcpRemotingClient::boost_asio_work, this)));
}
void TcpRemotingClient::boost_asio_work() {
LOG_INFO("TcpRemotingClient::boost asio async service runing");
boost::asio::io_service::work work(m_async_ioService); // avoid async io
// service stops after
// first timer timeout
// callback
m_async_ioService.run();
}
TcpRemotingClient::~TcpRemotingClient() {
m_tcpTable.clear();
m_futureTable.clear();
m_asyncFutureTable.clear();
m_namesrvAddrList.clear();
removeAllTimerCallback();
}
void TcpRemotingClient::stopAllTcpTransportThread() {
LOG_DEBUG("TcpRemotingClient::stopAllTcpTransportThread Begin");
m_async_ioService.stop();
m_async_service_thread->interrupt();
m_async_service_thread->join();
removeAllTimerCallback();
{
TcpMap::iterator it = m_tcpTable.begin();
for (; it != m_tcpTable.end(); ++it) {
it->second->disconnect(it->first);
}
m_tcpTable.clear();
}
m_ioService.stop();
m_threadpool.join_all();
{
boost::lock_guard<boost::mutex> lock(m_futureTableMutex);
for (ResMap::iterator it = m_futureTable.begin(); it != m_futureTable.end();
++it) {
if (it->second) it->second->releaseThreadCondition();
}
}
LOG_DEBUG("TcpRemotingClient::stopAllTcpTransportThread End");
}
void TcpRemotingClient::updateNameServerAddressList(const string& addrs) {
if (!addrs.empty()) {
boost::unique_lock<boost::timed_mutex> lock(m_namesrvlock,
boost::try_to_lock);
if (!lock.owns_lock()) {
if (!lock.timed_lock(boost::get_system_time() +
boost::posix_time::seconds(10))) {
LOG_ERROR("updateNameServerAddressList get timed_mutex timeout");
return;
}
}
// clear first;
m_namesrvAddrList.clear();
vector<string> out;
UtilAll::Split(out, addrs, ";");
for (size_t i = 0; i < out.size(); i++) {
string addr = out[i];
UtilAll::Trim(addr);
string hostName;
short portNumber;
if (UtilAll::SplitURL(addr, hostName, portNumber)) {
LOG_INFO("update Namesrv:%s", addr.c_str());
m_namesrvAddrList.push_back(addr);
}
}
out.clear();
}
}
bool TcpRemotingClient::invokeHeartBeat(const string& addr,
RemotingCommand& request) {
boost::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);
if (pTcp != NULL) {
int code = request.getCode();
int opaque = request.getOpaque();
boost::shared_ptr<ResponseFuture> responseFuture(
new ResponseFuture(code, opaque, this, 3000, false, NULL));
addResponseFuture(opaque, responseFuture);
// LOG_INFO("invokeHeartbeat success, addr:%s, code:%d, opaque:%d,
// timeoutms:%d", addr.c_str(), code, opaque, 3000);
if (SendCommand(pTcp, request)) {
responseFuture->setSendRequestOK(true);
unique_ptr<RemotingCommand> pRsp(responseFuture->waitResponse(3000));
if (pRsp == NULL) {
LOG_ERROR(
"wait response timeout of heartbeat, so closeTransport of addr:%s",
addr.c_str());
CloseTransport(addr, pTcp);
return false;
} else if (pRsp->getCode() == SUCCESS_VALUE) {
return true;
} else {
LOG_WARN("get error response:%d of heartbeat to addr:%s",
pRsp->getCode(), addr.c_str());
return false;
}
} else {
CloseTransport(addr, pTcp);
}
}
return false;
}
RemotingCommand* TcpRemotingClient::invokeSync(const string& addr,
RemotingCommand& request,
int timeoutMillis /* = 3000 */) {
boost::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);
if (pTcp != NULL) {
int code = request.getCode();
int opaque = request.getOpaque();
boost::shared_ptr<ResponseFuture> responseFuture(
new ResponseFuture(code, opaque, this, timeoutMillis, false, NULL));
addResponseFuture(opaque, responseFuture);
if (SendCommand(pTcp, request)) {
// LOG_INFO("invokeSync success, addr:%s, code:%d, opaque:%d,
// timeoutms:%d", addr.c_str(), code, opaque, timeoutMillis);
responseFuture->setSendRequestOK(true);
RemotingCommand* pRsp = responseFuture->waitResponse(timeoutMillis);
if (pRsp == NULL) {
if (code != GET_CONSUMER_LIST_BY_GROUP) {
LOG_WARN(
"wait response timeout or get NULL response of code:%d, so "
"closeTransport of addr:%s",
code, addr.c_str());
CloseTransport(addr, pTcp);
}
// avoid responseFuture leak;
findAndDeleteResponseFuture(opaque);
return NULL;
} else {
return pRsp;
}
} else {
// avoid responseFuture leak;
findAndDeleteResponseFuture(opaque);
CloseTransport(addr, pTcp);
}
}
return NULL;
}
bool TcpRemotingClient::invokeAsync(const string& addr,
RemotingCommand& request,
AsyncCallbackWrap* cbw,
int64 timeoutMilliseconds,
int maxRetrySendTimes,
int retrySendTimes) {
boost::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);
if (pTcp != NULL) {
//<!not delete, for callback to delete;
int code = request.getCode();
int opaque = request.getOpaque();
boost::shared_ptr<ResponseFuture> responseFuture(
new ResponseFuture(code, opaque, this, timeoutMilliseconds, true, cbw));
responseFuture->setMaxRetrySendTimes(maxRetrySendTimes);
responseFuture->setRetrySendTimes(retrySendTimes);
responseFuture->setBrokerAddr(addr);
responseFuture->setRequestCommand(request);
addAsyncResponseFuture(opaque, responseFuture);
if (cbw) {
boost::asio::deadline_timer* t = new boost::asio::deadline_timer(
m_async_ioService,
boost::posix_time::milliseconds(timeoutMilliseconds));
addTimerCallback(t, opaque);
boost::system::error_code e;
t->async_wait(
boost::bind(&TcpRemotingClient::handleAsyncPullForResponseTimeout,
this, e, opaque));
}
if (SendCommand(pTcp, request)) // Even if send failed, asyncTimerThread
// will trigger next pull request or report
// send msg failed
{
LOG_DEBUG("invokeAsync success, addr:%s, code:%d, opaque:%d",
addr.c_str(), code, opaque);
responseFuture->setSendRequestOK(true);
}
return true;
}
LOG_ERROR("invokeAsync failed of addr:%s", addr.c_str());
return false;
}
void TcpRemotingClient::invokeOneway(const string& addr,
RemotingCommand& request) {
//<!not need callback;
boost::shared_ptr<TcpTransport> pTcp = GetTransport(addr, true);
if (pTcp != NULL) {
request.markOnewayRPC();
LOG_DEBUG("invokeOneway success, addr:%s, code:%d", addr.c_str(),
request.getCode());
SendCommand(pTcp, request);
}
}
boost::shared_ptr<TcpTransport> TcpRemotingClient::GetTransport(
const string& addr, bool needRespons) {
if (addr.empty()) return CreateNameserverTransport(needRespons);
return CreateTransport(addr, needRespons);
}
boost::shared_ptr<TcpTransport> TcpRemotingClient::CreateTransport(
const string& addr, bool needRespons) {
boost::shared_ptr<TcpTransport> tts;
{
// try get m_tcpLock util m_tcpTransportTryLockTimeout to avoid blocking
// long
// time, if could not get m_tcpLock, return NULL
bool bGetMutex = false;
boost::unique_lock<boost::timed_mutex> lock(m_tcpLock, boost::try_to_lock);
if (!lock.owns_lock()) {
if (!lock.timed_lock(
boost::get_system_time() +
boost::posix_time::seconds(m_tcpTransportTryLockTimeout))) {
LOG_ERROR("GetTransport of:%s get timed_mutex timeout", addr.c_str());
boost::shared_ptr<TcpTransport> pTcp;
return pTcp;
} else {
bGetMutex = true;
}
} else {
bGetMutex = true;
}
if (bGetMutex) {
if (m_tcpTable.find(addr) != m_tcpTable.end()) {
boost::weak_ptr<TcpTransport> weakPtcp(m_tcpTable[addr]);
boost::shared_ptr<TcpTransport> tcp = weakPtcp.lock();
if (tcp) {
tcpConnectStatus connectStatus = tcp->getTcpConnectStatus();
if (connectStatus == e_connectWaitResponse) {
boost::shared_ptr<TcpTransport> pTcp;
return pTcp;
} else if (connectStatus == e_connectFail) {
LOG_ERROR("tcpTransport with server disconnected, erase server:%s",
addr.c_str());
tcp->disconnect(
addr); // avoid coredump when connection with broker was broken
m_tcpTable.erase(addr);
} else if (connectStatus == e_connectSuccess) {
return tcp;
} else {
LOG_ERROR(
"go to fault state, erase:%s from tcpMap, and reconnect "
"it",
addr.c_str());
m_tcpTable.erase(addr);
}
}
}
//<!callback;
READ_CALLBACK callback =
needRespons ? &TcpRemotingClient::static_messageReceived : NULL;
tts.reset(new TcpTransport(this, callback));
tcpConnectStatus connectStatus = tts->connect(addr, m_tcpConnectTimeout);
if (connectStatus != e_connectWaitResponse) {
LOG_WARN("can not connect to :%s", addr.c_str());
tts->disconnect(addr);
boost::shared_ptr<TcpTransport> pTcp;
return pTcp;
} else {
m_tcpTable[addr] = tts; // even if connecting failed finally, this
// server transport will be erased by next
// CreateTransport
}
} else {
LOG_WARN("get tcpTransport mutex failed :%s", addr.c_str());
boost::shared_ptr<TcpTransport> pTcp;
return pTcp;
}
}
tcpConnectStatus connectStatus =
tts->waitTcpConnectEvent(m_tcpConnectTimeout);
if (connectStatus != e_connectSuccess) {
LOG_WARN("can not connect to server:%s", addr.c_str());
tts->disconnect(addr);
boost::shared_ptr<TcpTransport> pTcp;
return pTcp;
} else {
LOG_INFO("connect server with addr:%s success", addr.c_str());
return tts;
}
}
boost::shared_ptr<TcpTransport> TcpRemotingClient::CreateNameserverTransport(
bool needRespons) {
// m_namesrvLock was added to avoid operation of nameServer was blocked by
// m_tcpLock, it was used by single Thread mostly, so no performance impact
// try get m_tcpLock util m_tcpTransportTryLockTimeout to avoid blocking long
// time, if could not get m_namesrvlock, return NULL
bool bGetMutex = false;
boost::unique_lock<boost::timed_mutex> lock(m_namesrvlock,
boost::try_to_lock);
if (!lock.owns_lock()) {
if (!lock.timed_lock(
boost::get_system_time() +
boost::posix_time::seconds(m_tcpTransportTryLockTimeout))) {
LOG_ERROR("CreateNameserverTransport get timed_mutex timeout");
boost::shared_ptr<TcpTransport> pTcp;
return pTcp;
} else {
bGetMutex = true;
}
} else {
bGetMutex = true;
}
if (bGetMutex) {
if (!m_namesrvAddrChoosed.empty()) {
boost::shared_ptr<TcpTransport> pTcp =
GetTransport(m_namesrvAddrChoosed, true);
if (pTcp)
return pTcp;
else
m_namesrvAddrChoosed.clear();
}
vector<string>::iterator itp = m_namesrvAddrList.begin();
for (; itp != m_namesrvAddrList.end(); ++itp) {
unsigned int index = m_namesrvIndex % m_namesrvAddrList.size();
if (m_namesrvIndex == numeric_limits<unsigned int>::max())
m_namesrvIndex = 0;
m_namesrvIndex++;
LOG_INFO("namesrvIndex is:%d, index:%d, namesrvaddrlist size:" SIZET_FMT
"",
m_namesrvIndex, index, m_namesrvAddrList.size());
boost::shared_ptr<TcpTransport> pTcp =
GetTransport(m_namesrvAddrList[index], true);
if (pTcp) {
m_namesrvAddrChoosed = m_namesrvAddrList[index];
return pTcp;
}
}
boost::shared_ptr<TcpTransport> pTcp;
return pTcp;
} else {
LOG_WARN("get nameServer tcpTransport mutex failed");
boost::shared_ptr<TcpTransport> pTcp;
return pTcp;
}
}
void TcpRemotingClient::CloseTransport(const string& addr,
boost::shared_ptr<TcpTransport> pTcp) {
if (addr.empty()) {
return CloseNameServerTransport(pTcp);
}
bool bGetMutex = false;
boost::unique_lock<boost::timed_mutex> lock(m_tcpLock, boost::try_to_lock);
if (!lock.owns_lock()) {
if (!lock.timed_lock(
boost::get_system_time() +
boost::posix_time::seconds(m_tcpTransportTryLockTimeout))) {
LOG_ERROR("CloseTransport of:%s get timed_mutex timeout", addr.c_str());
return;
} else {
bGetMutex = true;
}
} else {
bGetMutex = true;
}
LOG_ERROR("CloseTransport of:%s", addr.c_str());
if (bGetMutex) {
bool removeItemFromTable = true;
if (m_tcpTable.find(addr) != m_tcpTable.end()) {
if (m_tcpTable[addr]->getStartTime() != pTcp->getStartTime()) {
LOG_INFO(
"tcpTransport with addr:%s has been closed before, and has been "
"created again, nothing to do",
addr.c_str());
removeItemFromTable = false;
}
} else {
LOG_INFO(
"tcpTransport with addr:%s had been removed from tcpTable before",
addr.c_str());
removeItemFromTable = false;
}
if (removeItemFromTable == true) {
LOG_WARN("closeTransport: disconnect broker:%s with state:%d",
addr.c_str(), m_tcpTable[addr]->getTcpConnectStatus());
if (m_tcpTable[addr]->getTcpConnectStatus() == e_connectSuccess)
m_tcpTable[addr]->disconnect(
addr); // avoid coredump when connection with server was broken
LOG_WARN("closeTransport: erase broker: %s", addr.c_str());
m_tcpTable.erase(addr);
}
} else {
LOG_WARN("CloseTransport::get tcpTransport mutex failed:%s", addr.c_str());
return;
}
LOG_ERROR("CloseTransport of:%s end", addr.c_str());
}
void TcpRemotingClient::CloseNameServerTransport(
boost::shared_ptr<TcpTransport> pTcp) {
bool bGetMutex = false;
boost::unique_lock<boost::timed_mutex> lock(m_namesrvlock,
boost::try_to_lock);
if (!lock.owns_lock()) {
if (!lock.timed_lock(
boost::get_system_time() +
boost::posix_time::seconds(m_tcpTransportTryLockTimeout))) {
LOG_ERROR("CreateNameserverTransport get timed_mutex timeout");
return;
} else {
bGetMutex = true;
}
} else {
bGetMutex = true;
}
if (bGetMutex) {
string addr = m_namesrvAddrChoosed;
bool removeItemFromTable = true;
if (m_tcpTable.find(addr) != m_tcpTable.end()) {
if (m_tcpTable[addr]->getStartTime() != pTcp->getStartTime()) {
LOG_INFO(
"tcpTransport with addr:%s has been closed before, and has been "
"created again, nothing to do",
addr.c_str());
removeItemFromTable = false;
}
} else {
LOG_INFO(
"tcpTransport with addr:%s had been removed from tcpTable before",
addr.c_str());
removeItemFromTable = false;
}
if (removeItemFromTable == true) {
m_tcpTable[addr]->disconnect(
addr); // avoid coredump when connection with server was broken
LOG_WARN("closeTransport: erase broker: %s", addr.c_str());
m_tcpTable.erase(addr);
m_namesrvAddrChoosed.clear();
}
} else {
LOG_WARN("CloseNameServerTransport::get tcpTransport mutex failed:%s",
m_namesrvAddrChoosed.c_str());
return;
}
}
bool TcpRemotingClient::SendCommand(boost::shared_ptr<TcpTransport> pTts,
RemotingCommand& msg) {
const MemoryBlock* phead = msg.GetHead();
const MemoryBlock* pbody = msg.GetBody();
unique_ptr<MemoryOutputStream> result(new MemoryOutputStream(1024));
if (phead->getData()) {
result->write(phead->getData(), phead->getSize());
}
if (pbody->getData()) {
result->write(pbody->getData(), pbody->getSize());
}
const char* pData = static_cast<const char*>(result->getData());
int len = result->getDataSize();
return pTts->sendMessage(pData, len);
}
void TcpRemotingClient::static_messageReceived(void* context,
const MemoryBlock& mem,
const string& addr) {
TcpRemotingClient* pTcpRemotingClient = (TcpRemotingClient*)context;
if (pTcpRemotingClient) pTcpRemotingClient->messageReceived(mem, addr);
}
void TcpRemotingClient::messageReceived(const MemoryBlock& mem,
const string& addr) {
m_ioService.post(
boost::bind(&TcpRemotingClient::ProcessData, this, mem, addr));
}
void TcpRemotingClient::ProcessData(const MemoryBlock& mem,
const string& addr) {
RemotingCommand* pRespondCmd = NULL;
try {
pRespondCmd = RemotingCommand::Decode(mem);
} catch (...) {
LOG_ERROR("processData_error");
return;
}
int opaque = pRespondCmd->getOpaque();
//<!process self;
if (pRespondCmd->isResponseType()) {
boost::shared_ptr<ResponseFuture> pFuture(
findAndDeleteAsyncResponseFuture(opaque));
if (!pFuture) {
pFuture = findAndDeleteResponseFuture(opaque);
if (pFuture) {
if (pFuture->getSyncResponseFlag()) {
LOG_WARN("waitResponse already timeout of opaque:%d", opaque);
deleteAndZero(pRespondCmd);
return;
}
LOG_DEBUG("find_response opaque:%d", opaque);
} else {
LOG_DEBUG("responseFuture was deleted by timeout of opaque:%d", opaque);
deleteAndZero(pRespondCmd);
return;
}
}
processResponseCommand(pRespondCmd, pFuture);
} else {
processRequestCommand(pRespondCmd, addr);
}
}
void TcpRemotingClient::processResponseCommand(
RemotingCommand* pCmd, boost::shared_ptr<ResponseFuture> pfuture) {
int code = pfuture->getRequestCode();
int opaque = pCmd->getOpaque();
LOG_DEBUG("processResponseCommand, code:%d,opaque:%d, maxRetryTimes:%d, retrySendTimes:%d", code, opaque, pfuture->getMaxRetrySendTimes(), pfuture->getRetrySendTimes());
pCmd->SetExtHeader(code); // set head , for response use
pfuture->setResponse(pCmd);
if (pfuture->getASyncFlag()) {
if (!pfuture->getAsyncResponseFlag()) {
pfuture->setAsyncResponseFlag();
pfuture->setAsyncCallBackStatus(asyncCallBackStatus_response);
cancelTimerCallback(opaque);
pfuture->executeInvokeCallback();
}
}
}
void TcpRemotingClient::processRequestCommand(RemotingCommand* pCmd,
const string& addr) {
unique_ptr<RemotingCommand> pRequestCommand(pCmd);
int requestCode = pRequestCommand->getCode();
if (m_requestTable.find(requestCode) == m_requestTable.end()) {
LOG_ERROR("can_not_find request:%d processor", requestCode);
} else {
unique_ptr<RemotingCommand> pResponse(
m_requestTable[requestCode]->processRequest(addr,
pRequestCommand.get()));
if (!pRequestCommand->isOnewayRPC()) {
if (pResponse) {
pResponse->setOpaque(pRequestCommand->getOpaque());
pResponse->markResponseType();
pResponse->Encode();
invokeOneway(addr, *pResponse);
}
}
}
}
void TcpRemotingClient::addResponseFuture(
int opaque, boost::shared_ptr<ResponseFuture> pfuture) {
boost::lock_guard<boost::mutex> lock(m_futureTableMutex);
m_futureTable[opaque] = pfuture;
}
// Note: after call this function, shared_ptr of m_syncFutureTable[opaque] will
// be erased, so caller must ensure the life cycle of returned shared_ptr;
boost::shared_ptr<ResponseFuture>
TcpRemotingClient::findAndDeleteResponseFuture(int opaque) {
boost::lock_guard<boost::mutex> lock(m_futureTableMutex);
boost::shared_ptr<ResponseFuture> pResponseFuture;
if (m_futureTable.find(opaque) != m_futureTable.end()) {
pResponseFuture = m_futureTable[opaque];
m_futureTable.erase(opaque);
}
return pResponseFuture;
}
void TcpRemotingClient::handleAsyncPullForResponseTimeout(
const boost::system::error_code& e, int opaque) {
if (e == boost::asio::error::operation_aborted) {
LOG_INFO("handleAsyncPullForResponseTimeout aborted opaque:%d, e_code:%d, msg:%s", opaque, e.value(), e.message().data());
return;
}
LOG_DEBUG("handleAsyncPullForResponseTimeout opaque:%d, e_code:%d, msg:%s", opaque, e.value(), e.message().data());
boost::shared_ptr<ResponseFuture> pFuture(
findAndDeleteAsyncResponseFuture(opaque));
if (pFuture && pFuture->getASyncFlag() && (pFuture->getAsyncCallbackWrap())) {
if ((pFuture->getAsyncResponseFlag() !=
true)) // if no response received, then check timeout or not
{
LOG_ERROR("no response got for opaque:%d", opaque);
pFuture->setAsyncCallBackStatus(asyncCallBackStatus_timeout);
pFuture->executeInvokeCallbackException();
}
}
eraseTimerCallback(opaque);
}
void TcpRemotingClient::addAsyncResponseFuture(
int opaque, boost::shared_ptr<ResponseFuture> pfuture) {
boost::lock_guard<boost::mutex> lock(m_asyncFutureLock);
m_asyncFutureTable[opaque] = pfuture;
}
// Note: after call this function, shared_ptr of m_asyncFutureTable[opaque] will
// be erased, so caller must ensure the life cycle of returned shared_ptr;
boost::shared_ptr<ResponseFuture>
TcpRemotingClient::findAndDeleteAsyncResponseFuture(int opaque) {
boost::lock_guard<boost::mutex> lock(m_asyncFutureLock);
boost::shared_ptr<ResponseFuture> pResponseFuture;
if (m_asyncFutureTable.find(opaque) != m_asyncFutureTable.end()) {
pResponseFuture = m_asyncFutureTable[opaque];
m_asyncFutureTable.erase(opaque);
}
return pResponseFuture;
}
void TcpRemotingClient::registerProcessor(
MQRequestCode requestCode,
ClientRemotingProcessor* clientRemotingProcessor) {
if (m_requestTable.find(requestCode) != m_requestTable.end())
m_requestTable.erase(requestCode);
m_requestTable[requestCode] = clientRemotingProcessor;
}
void TcpRemotingClient::addTimerCallback(boost::asio::deadline_timer* t,
int opaque) {
boost::lock_guard<boost::mutex> lock(m_timerMapMutex);
if (m_async_timer_map.find(opaque) != m_async_timer_map.end()) {
LOG_DEBUG("addTimerCallback:erase timerCallback opaque:%lld", opaque);
boost::asio::deadline_timer* old_t = m_async_timer_map[opaque];
old_t->cancel();
delete old_t;
old_t = NULL;
m_async_timer_map.erase(opaque);
}
m_async_timer_map[opaque] = t;
}
void TcpRemotingClient::eraseTimerCallback(int opaque) {
boost::lock_guard<boost::mutex> lock(m_timerMapMutex);
if (m_async_timer_map.find(opaque) != m_async_timer_map.end()) {
LOG_DEBUG("eraseTimerCallback: opaque:%lld", opaque);
boost::asio::deadline_timer* t = m_async_timer_map[opaque];
delete t;
t = NULL;
m_async_timer_map.erase(opaque);
}
}
void TcpRemotingClient::cancelTimerCallback(int opaque) {
boost::lock_guard<boost::mutex> lock(m_timerMapMutex);
if (m_async_timer_map.find(opaque) != m_async_timer_map.end()) {
LOG_DEBUG("cancelTimerCallback: opaque:%lld", opaque);
boost::asio::deadline_timer* t = m_async_timer_map[opaque];
t->cancel();
delete t;
t = NULL;
m_async_timer_map.erase(opaque);
}
}
void TcpRemotingClient::removeAllTimerCallback() {
boost::lock_guard<boost::mutex> lock(m_timerMapMutex);
for (asyncTimerMap::iterator it = m_async_timer_map.begin();
it != m_async_timer_map.end(); ++it) {
boost::asio::deadline_timer* t = it->second;
t->cancel();
delete t;
t = NULL;
}
m_async_timer_map.clear();
}
void TcpRemotingClient::deleteOpaqueForDropPullRequest(const MQMessageQueue& mq, int opaque) {
//delete the map record of opaque<->ResponseFuture, so the answer for the pull request will discard when receive it later
boost::shared_ptr<ResponseFuture> pFuture(findAndDeleteAsyncResponseFuture(opaque));
if (!pFuture) {
pFuture = findAndDeleteResponseFuture(opaque);
if (pFuture) {
LOG_DEBUG("succ deleted the sync pullrequest for opaque:%d, mq:%s", opaque, mq.toString().data());
}
} else {
LOG_DEBUG("succ deleted the async pullrequest for opaque:%d, mq:%s", opaque, mq.toString().data());
}
//delete the timeout timer for opaque for pullrequest
cancelTimerCallback(opaque);
}
//<!************************************************************************
} //<!end namespace;
| 28,179 | 8,877 |
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "garnet/lib/ui/gfx/engine/duration_predictor.h"
#include <src/lib/fxl/logging.h>
namespace scenic_impl {
namespace gfx {
DurationPredictor::DurationPredictor(size_t window_size, zx::duration initial_prediction)
: kWindowSize(window_size), window_(kWindowSize, initial_prediction) {
FXL_DCHECK(kWindowSize > 0);
current_maximum_duration_index_ = kWindowSize - 1;
}
zx::duration DurationPredictor::GetPrediction() const {
return window_[current_maximum_duration_index_];
}
void DurationPredictor::InsertNewMeasurement(zx::duration duration) {
// Move window forward.
window_.push_front(duration);
window_.pop_back();
++current_maximum_duration_index_;
if (current_maximum_duration_index_ >= kWindowSize) {
// If old min went out of scope, find the new min.
current_maximum_duration_index_ = 0;
for (size_t i = 1; i < kWindowSize; ++i) {
if (window_[i] > window_[current_maximum_duration_index_]) {
current_maximum_duration_index_ = i;
}
}
} else if (window_.front() >= window_[current_maximum_duration_index_]) {
// Use newest possible maximum.
current_maximum_duration_index_ = 0;
}
}
} // namespace gfx
} // namespace scenic_impl
| 1,381 | 477 |
#include "vta/runtime.h"
#include "vta/vtalib/include/Bundle/VTABundle.h"
#include "vtaFCTestBundle.h"
SymbolTableEntry symbolTableEntry[2]={{"inputP",0,2048,'1'},{"outP",2048,1000,'1'}};
BundleConfig vtaFCTestBundle_config = {2052000, 3048, 0, 64, 2, symbolTableEntry};
int vtaFCTestMainEntry(int8_t *constantWeight, int8_t *mutableWeight, int8_t *activations){
xlnk_reset();
int8_t* filterP = constantWeight + 0;
int8_t* biasP = constantWeight + 2048000;
int8_t* inputP = mutableWeight + 0;
int8_t* outP = mutableWeight + 2048;
fullyconnected(inputP, 1.0/8.000000, 0, filterP, 1.0/128.000000, 0, biasP, 1.0/1024.000000, 0, outP, 1.0/4.000000, 0, 1, 2048, 2048, 1000, 1, 1000, 1 );
return 0;
} | 711 | 379 |
#include "matrix_support.h"
#include "../doctest.h"
#include "Support/Helpers.h" // random_float()
using namespace V3DLib;
void compare_arrays(Float::Array2D &a, float const *b, float precision) {
// Values empirically determined - the bigger the matrices, the less precise
if (precision == -1.0f) {
if (Platform::has_vc4()) {
precision = 1.0e-3f;
} else {
precision = 2.5e-4f; // This value works for 640x640 matrices
}
}
float max_diff = -1;
for (int r = 0; r < a.rows(); r++) {
for (int c = 0; c < a.columns(); c++) {
float diff = abs(a[r][c] - b[r*a.columns() + c]);
if (max_diff == -1 || max_diff < diff) {
max_diff = diff;
}
}
}
INFO("Max diff: " << max_diff << ", precision: " << precision);
for (int r = 0; r < a.rows(); r++) {
for (int c = 0; c < a.columns(); c++) {
INFO("r: " << r << ", c: " << c);
//INFO("Result: " << a.dump());
INFO("result: " << a[r][c] << ", expected: " << b[r*a.columns() + c]);
REQUIRE(abs(a[r][c] - b[r*a.columns() + c]) < precision);
}
}
}
/**
* This is better than:
*
* REQUIRE(m1.result() == m2.result());
*
* ....which has been known to fail incorrectly.
*/
void compare_arrays(Float::Array2D &a, Float::Array2D &b, float precision) {
REQUIRE(a.rows() == b.rows());
REQUIRE(a.columns() == b.columns());
if ( precision == -1.0f) {
//precision = 1.0e-4f; // for high precision sin/cos in kernels
precision = 4.1e-1f; // for low precision sin/cos in vc4 kernels (yeah, it sucks)
}
for (int r = 0; r < a.rows(); ++r) {
for (int c = 0; c < a.columns(); ++c) {
INFO("(r, c): ( " << r << ", " << c << ")");
INFO(a[r][c] << " == " << b[r][c]);
// <= for dealing with precision 0.0f
REQUIRE(abs(a[r][c] - b[r][c]) <= precision);
REQUIRE(abs(a[r][c] - b[r][c]) <= precision);
}
}
}
void compare_arrays(Complex::Array2D &a, Complex::Array2D &b, float precision) {
REQUIRE(a.rows() == b.rows());
REQUIRE(a.columns() == b.columns());
if ( precision == -1.0f) {
//precision = 1.0e-4f; // for high precision sin/cos in kernels
precision = 4.0e-1f; // for low precision sin/cos in kernels
}
float max_diff_re = -1;
float max_diff_im = -1;
for (int r = 0; r < a.rows(); r++) {
for (int c = 0; c < a.columns(); c++) {
float diff_re = abs(a[r][c].re() - b[r][c].re());
if (max_diff_re == -1 || max_diff_re < diff_re) {
max_diff_re = diff_re;
}
float diff_im = abs(a[r][c].im() - b[r][c].im());
if (max_diff_im == -1 || max_diff_im < diff_im) {
max_diff_im = diff_im;
}
}
}
// Do an overall check
if (max_diff_re <= precision && max_diff_im <= precision) {
return; // All is well
}
INFO("Max diff re: " << max_diff_re
<< ", max diff im: " << max_diff_im
<< ", precision: " << precision);
// Do a specific check to find the (r,c) coordinate where it goes wrong
for (int r = 0; r < a.rows(); ++r) {
for (int c = 0; c < a.columns(); ++c) {
INFO("(r, c): ( " << r << ", " << c << ")");
INFO(a[r][c].dump() << " == " << b[r][c].dump());
// <= for dealing with precision 0.0f
// REQUIRE(abs(a[r][c].magnitude() - b[r][c].magnitude()) <= precision);
REQUIRE(abs(a[r][c].re() - b[r][c].re()) <= precision);
REQUIRE(abs(a[r][c].im() - b[r][c].im()) <= precision);
}
}
}
void compare_arrays(std::vector<float> &a, float const *b) {
float precision = 1e-4f;
for (int r = 0; r < (int) a.size(); ++r) {
REQUIRE(abs(a[r] - b[r]) < precision);
}
}
void check_unitary(std::vector<float> &a, int dim) {
for (int r = 0; r < dim; r++) {
for (int c = 0; c < dim; c++) {
INFO("rows: " << dim << ", (r,c): (" << r << ", " << c << ")");
int offset = r*dim + c;
if (r == c) {
REQUIRE(a[offset] == 1.0f);
} else {
REQUIRE(a[offset] == 0.0f);
}
}
}
}
void check_unitary(Float::Array2D &a) {
REQUIRE(a.rows() == a.columns());
for (int r = 0; r < a.rows(); r++) {
for (int c = 0; c < a.columns(); c++) {
INFO("rows: " << a.rows() << ", (r,c): (" << r << ", " << c << ")");
if (r == c) {
REQUIRE(a[r][c] == 1.0f);
} else {
REQUIRE(a[r][c] == 0.0f);
}
}
}
}
void fill_random(float *arr, int size) {
for (int n = 0; n < size; n++) {
arr[n] = random_float();
}
}
void fill_random(std::vector<float> &arr) {
assert(!arr.empty());
fill_random(arr.data(), (int) arr.size());
}
/**
* Pre: dst properly initialized, matches with src
*/
void copy_array(Float::Array2D &dst, float const *src) {
for (int r = 0; r < dst.rows(); r++) {
for (int c = 0; c < dst.columns(); c++) {
dst[r][c] = src[r*dst.columns() + c];
}
}
}
void copy_array(Float::Array2D &dst, std::vector<float> const &src) {
assert(!src.empty());
assert((int) src.size() == dst.rows()*dst.columns());
copy_array(dst, src.data());
}
void copy_transposed(float *dst, float const *src, int rows, int columns) {
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
dst[c*rows + r] = src[r*columns + c];
}
}
}
void copy_transposed(std::vector<float> &dst, std::vector<float> const &src, int rows, int columns) {
copy_transposed(dst.data(), src.data(), rows, columns);
}
void compare_array_scalar(Float::Array2D &arr, float scalar) {
for (int r = 0; r < arr.rows(); ++r) {
for (int c = 0; c < arr.columns(); ++c) {
INFO("r: " << r << ", c: " << c);
INFO("result: " << arr[r][c] << ", expected: " << scalar);
REQUIRE(arr[r][c] == scalar);
}
}
}
| 5,710 | 2,364 |
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "cpu_blocked_memory_desc.h"
#include "mkldnn_memory.h"
#include "utils/cpu_utils.hpp"
using namespace MKLDNNPlugin;
BlockedMemoryDesc::BlockedMemoryDesc(InferenceEngine::Precision prc, const std::vector<size_t>& dims) : MemoryDesc(dims, Blocked) , precision(prc) {
order.resize(dims.size());
std::iota(order.begin(), order.end(), 0);
blockedDims = dims;
offsetPadding = 0;
offsetPaddingToData.resize(dims.size(), 0);
strides.resize(order.size());
strides[strides.size() - 1] = 1;
for (size_t i = 2; i <= order.size(); i++) {
strides[strides.size() - i] = strides[strides.size() - (i - 1)] * blockedDims[blockedDims.size() - (i - 1)];
}
}
BlockedMemoryDesc::BlockedMemoryDesc(InferenceEngine::Precision prc, const std::vector<size_t>& dims, const std::vector<size_t>& blockedDims,
const std::vector<size_t>& order, size_t offsetPadding, const std::vector<size_t>& offsetPaddingToData,
const std::vector<size_t>& strides) : MemoryDesc(dims, Blocked), precision(prc) {
if (std::any_of(order.begin(), order.end(), [](size_t val) { return val == Shape::UNDEFINED_DIM; })) {
IE_THROW() << "BlockedMemoryDesc do not support undefined order.";
}
if (std::any_of(blockedDims.begin() + dims.size(), blockedDims.end(), [](size_t val) { return val == Shape::UNDEFINED_DIM; })) {
IE_THROW() << "BlockedMemoryDesc doesn't support undefined blockedDims.";
}
this->order = order;
this->blockedDims = blockedDims;
this->offsetPadding = offsetPadding;
if (offsetPaddingToData.empty() && !order.empty()) {
this->offsetPaddingToData.resize(order.size());
this->offsetPaddingToData[order.size() - 1] = 0;
for (size_t i = 2; i <= order.size(); i++) {
this->offsetPaddingToData[order.size() - i] = 0;
}
} else {
this->offsetPaddingToData = offsetPaddingToData;
}
if (strides.empty() && !order.empty()) {
if (std::any_of(this->blockedDims.begin(), this->blockedDims.end(), [](size_t val) { return val == Shape::UNDEFINED_DIM; })) {
this->strides.resize(order.size(), Shape::UNDEFINED_DIM);
} else {
this->strides.resize(order.size());
this->strides[order.size() - 1] = 1;
for (size_t i = 2; i <= order.size(); i++) {
this->strides[order.size() - i] = this->strides[order.size() - (i - 1)] * this->blockedDims[blockedDims.size() - (i - 1)];
}
}
} else {
this->strides = strides;
}
if (!everyone_is(this->order.size(), this->blockedDims.size(), this->offsetPaddingToData.size(), this->strides.size())) {
IE_THROW() << "Order, blocked dims, offset padding to data and strides must have equals size";
}
}
bool BlockedMemoryDesc::isDefined() const {
bool defined = true;
defined = defined && std::none_of(blockedDims.cbegin(), blockedDims.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; });
defined = defined && std::none_of(strides.cbegin(), strides.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; });
defined = defined && std::none_of(order.cbegin(), order.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; });
defined = defined && std::none_of(offsetPaddingToData.cbegin(), offsetPaddingToData.cend(), [](size_t val) { return val == Shape::UNDEFINED_DIM; });
defined = defined && offsetPadding != Shape::UNDEFINED_DIM;
return defined;
}
bool BlockedMemoryDesc::isCompatible(const MemoryDesc& rhs) const {
const MemoryDesc* pRhs = &rhs;
if (auto blockingDesc = dynamic_cast<const BlockedMemoryDesc*>(pRhs)) {
return isCompatible(*blockingDesc);
} else if (auto mkldnnDesc = dynamic_cast<const MKLDNNMemoryDesc*>(pRhs)) {
return mkldnnDesc->isCompatible(*this);
} else {
return false;
}
}
bool BlockedMemoryDesc::isCompatible(const BlockedMemoryDesc& rhs) const {
if (this->getShape() != rhs.getShape() || this->getPrecision() != rhs.getPrecision())
return false;
if (!dimsEqualWeak(this->getBlockDims(), rhs.getBlockDims())) {
return false;
}
if (!dimsEqualWeak(this->getOffsetPaddingToData(), rhs.getOffsetPaddingToData())) {
return false;
}
// this check needed to avoid inserting unnecessary reorders if the memory is used in place and the batch size is equal to 1
size_t skipAxis = this->getShape().getRank() > 0 && this->getShape().getDims().front() == 1 ? 0 :
Shape::UNDEFINED_DIM; //ignore batch axis if batch size == 1
if (!dimsEqualWeak(this->getStrides(), rhs.getStrides(), skipAxis)) {
return false;
}
if (!dimsEqualWeak(this->getOrder(), rhs.getOrder())) {
return false;
}
return dimsEqualWeak(this->getOffsetPadding(), rhs.getOffsetPadding());
}
bool BlockedMemoryDesc::isCompatible(const MKLDNNMemoryDesc& rhs) const {
return rhs.isCompatible(*this);
}
size_t BlockedMemoryDesc::getMemSizeImp() const {
int64_t e_size = getOffsetPadding() + 1; // size in bytes (from begin of data to last element)
for (int j = 0; j < getBlockDims().size(); j++)
e_size += (getBlockDims()[j] - 1) * getStrides()[j];
e_size *= getPrecision() == InferenceEngine::Precision::BIN ? 1 : getPrecision().size();
return e_size;
}
size_t BlockedMemoryDesc::getOffset(const InferenceEngine::SizeVector& v) const {
InferenceEngine::SizeVector off_v = v;
size_t n_blocked_dims = order.size();
if (blockedDims.size() != n_blocked_dims || strides.size() != n_blocked_dims) {
IE_THROW() << "Cannot calculate offset. Incorrect primitive descriptor!";
}
InferenceEngine::SizeVector blockedShift(n_blocked_dims);
for (size_t i = 1; i <= n_blocked_dims; i++) {
blockedShift[n_blocked_dims - i] = off_v[order[n_blocked_dims - i]] % blockedDims[n_blocked_dims - i];
off_v[order[n_blocked_dims - i]] /= blockedDims[n_blocked_dims - i];
}
size_t offset = getOffsetPadding();
for (size_t d = 0; d < n_blocked_dims; ++d) {
const size_t p = blockedShift[d] + getOffsetPaddingToData()[d];
offset += p * strides[d];
}
return offset;
}
size_t BlockedMemoryDesc::getElementOffset(size_t elemNumber) const {
// TODO [DS]: rewrite to support dynamic shapes
auto& dims = shape.getStaticDims();
size_t n_dims = dims.size();
InferenceEngine::SizeVector pos(n_dims);
for (size_t rd = 1; rd <= n_dims; ++rd) {
const size_t d = n_dims - rd;
const size_t cur_dim = dims[d];
pos[d] = elemNumber % cur_dim;
elemNumber /= cur_dim;
}
return getOffset(pos);
}
bool BlockedMemoryDesc::hasLayoutType(LayoutType layoutType) const {
switch (layoutType) {
case LayoutType::ncsp:
return isPlainFormat();
case LayoutType::nspc:
return isTailCFormat();
case LayoutType::nCsp8c:
return isBlockedCFormat(8);
case LayoutType::nCsp16c:
return isBlockedCFormat(16);
default:
return false;
}
}
bool BlockedMemoryDesc::isPlainFormat() const {
if (shape.getRank() != order.size()) {
return false;
}
for (size_t i = 0; i < order.size(); ++i) {
if (order[i] != i) {
return false;
}
}
return true;
}
bool BlockedMemoryDesc::isBlockedCFormat(size_t blk_size) const {
if ((order.size() - shape.getRank()) != 1) {
return false;
}
for (size_t i = 0; i < order.size() - 1; ++i) {
if (order[i] != i) {
return false;
}
}
if (order.back() != 1) {
return false;
}
if (blockedDims.back() != blk_size) {
return false;
}
return true;
}
bool BlockedMemoryDesc::isTailCFormat() const {
if (shape.getRank() < 3) {
return false;
}
if (shape.getRank() != order.size()) {
return false;
}
if (!std::is_sorted(order.begin(), --order.end())) {
return false;
}
if (order.back() != 1) {
return false;
}
return true;
}
std::string BlockedMemoryDesc::serializeFormat() const {
std::stringstream result;
char startLetter = 'a';
std::unordered_map<size_t, size_t> mapAxisBlockSize;
for (size_t i = shape.getRank(); i < order.size(); ++i) {
mapAxisBlockSize.insert({order[i], blockedDims[i]});
}
for (size_t i = 0; i < shape.getRank(); ++i) {
char nextLetter = startLetter + order[i];
if (mapAxisBlockSize.count(i)) {
nextLetter = toupper(nextLetter);
}
result << nextLetter;
}
for (auto& item : mapAxisBlockSize) {
result << item.second << char(startLetter + item.first);
}
return result.str();
}
| 8,928 | 3,112 |
// A sample program
#include <stdio.h>
int main(){
printf("Hello World\n");
}
| 81 | 31 |
/*
gpe_scene_tilemap_class.cpp
This file is part of:
GAME PENCIL ENGINE
https://www.pawbyte.com/gamepencilengine
Copyright (c) 2014-2020 Nathan Hurde, Chase Lee.
Copyright (c) 2014-2020 PawByte LLC.
Copyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page )
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.
-Game Pencil Engine <https://www.pawbyte.com/gamepencilengine>
*/
#include "gpe_scene_tilemap_class.h"
GPE_SceneTile::GPE_SceneTile()
{
isLocked = false;
branchType = gpe::branch_type::TILE;
iconTexture = paw_gui_rsm->texture_add_filename( gpe::app_directory_name+"resources/gfx/iconpacks/fontawesome/table.png") ;
tileTypeId = -1;
tileIndexId = -1;
tilesheetIndexId = -1;
tileRect.x = 0;
tileRect.y = 0;
tileRect.w = 0;
tileRect.h = 0;
}
GPE_SceneTile::~GPE_SceneTile()
{
}
void GPE_SceneTile::add_typed_elements()
{
if( PANEL_INSPECTOR!=NULL )
{
}
}
void GPE_SceneTile::render_branch()
{
}
bool GPE_SceneTile::save_branch_data(std::ofstream * fileTarget, int nestedFoldersIn )
{
return true;
}
GPE_SceneTileMap::GPE_SceneTileMap( std::string mapName, int x, int y, GPE_GeneralResourceContainer *pFolder )
{
projectParentFolder = pFolder;
if( projectParentFolder!=NULL)
{
tilesheetDropDown = new GPE_DropDown_Resouce_Menu( "Tilesheet",projectParentFolder->find_resource_from_name( gpe::resource_type_names[ gpe::resource_type_tilesheet]+"s"),-1,true );
tilesheetDropDown->set_width(192);
tSPreviewer = new tilesheetPreviewer();
}
else
{
tilesheetDropDown = NULL;
tSPreviewer = NULL;
}
isLocked = false;
set_position( x, y);
branchType = gpe::branch_type::TILEMAP;
iconTexture = paw_gui_rsm->texture_add_filename( gpe::app_directory_name+"resources/gfx/iconpacks/fontawesome/th.png") ;
update_rectangle(&tsPlacementArea,0,0,0,0);
tileWidth = gpe::tile_default_width;
tileHeight = gpe::tile_default_height;
tileAmountX = prevTileAmountX = 0;
tileAmountY = prevTileAmountY = 0;
xPosField->set_number( xPos );
xPosField->set_label("Map-XStart");
yPosField->set_number( yPos );
yPosField->set_label("Map-YStart");
fieldTileWidth = new gpe_text_widget_number( "32" );
fieldTileWidth->set_number( tileWidth );
fieldTileWidth->set_label("Tile Width");
fieldTileWidth->scale_width( 0.4 );
fieldTileHeight = new gpe_text_widget_number( "32" );
fieldTileHeight->set_number( tileHeight );
fieldTileHeight->set_label("Tile Height");
fieldTileHeight->scale_width( 0.4 );
fieldAmountX = new gpe_text_widget_number( "" );
fieldAmountX->set_number( tileAmountX );
fieldAmountX->set_label("Map Width");
fieldAmountX->scale_width( 0.4 );
fieldAmountY = new gpe_text_widget_number( "y-tile-amount" );
fieldAmountY->set_label("Map Height");
fieldAmountY->set_number( tileAmountY );
fieldAmountY->scale_width( 0.4 );
fillScene = new GPE_CheckBoxBasic("Fill Scene","Check to use remainder of scene" );
if( (int)mapName.size()==0 )
{
name = "tilemap";
}
else
{
set_name( mapName );
}
}
void GPE_SceneTileMap::add_typed_elements()
{
if( PANEL_INSPECTOR!=NULL )
{
PANEL_INSPECTOR->add_gui_element( tilesheetDropDown, true );
PANEL_INSPECTOR->add_gui_element( fieldTileWidth, false );
PANEL_INSPECTOR->add_gui_element( fieldTileHeight, true );
PANEL_INSPECTOR->add_gui_element( fieldAmountX, false );
PANEL_INSPECTOR->add_gui_element( fieldAmountY, true );
PANEL_INSPECTOR->add_gui_element( fillScene, true );
}
}
GPE_SceneTileMap::~GPE_SceneTileMap()
{
if( tSPreviewer!=NULL)
{
delete tSPreviewer;
tSPreviewer = NULL;
}
}
bool GPE_SceneTileMap::build_intohtml5_file(std::ofstream * fileTarget, int leftTabAmount, GPE_GeneralResourceContainer * localResTypeController )
{
if( localResTypeController == NULL )
{
return false;
}
std::string nestedTabsStr = generate_tabs( leftTabAmount );
GPE_SceneTile * fSceneTile = NULL;
GPE_GeneralResourceContainer * fTSToPlace = NULL;
int maxTilesInLayer = (int)mapTiles.size();
for( int i = 0; i < maxTilesInLayer; i++)
{
fSceneTile = mapTiles.at(i);
if( fSceneTile!=NULL &&fSceneTile->tilesheetIndexId>=0 && fSceneTile->tileIndexId>=0)
{
fTSToPlace = localResTypeController->find_resource_from_id(fSceneTile->tilesheetIndexId);
if( fTSToPlace!=NULL)
{
*fileTarget << nestedTabsStr << "_scn_temp_layer.scnStartTiles.push( {tileNumber: " << stg_ex::int_to_string( i ) << ",";
*fileTarget << "tileSheetId: " << stg_ex::int_to_string(fTSToPlace->exportBuildGlobalId) << ",";
*fileTarget << "tileIndexId: " << stg_ex::int_to_string(fSceneTile->tileIndexId);
*fileTarget << "}); \n";
}
}
}
GPE_SceneBasicClass::build_intohtml5_file( fileTarget, leftTabAmount+1, localResTypeController);
return true;
}
void GPE_SceneTileMap::calculate_size()
{
}
void GPE_SceneTileMap::create_new_map(int newTX, int newTY,int ntileType )
{
tileAmountX=newTX;
tileAmountY=newTY;
int newSize = tileAmountX*tileAmountY;
if( mapTiles.size() >0 )
{
for(std::vector<GPE_SceneTile*>::const_iterator it = mapTiles.begin(); it != mapTiles.end(); it++)
{
delete *it;
}
mapTiles.clear();
}
GPE_SceneTile * newTile = NULL;
for(int i=0; i<newSize; i++)
{
newTile = new GPE_SceneTile();
newTile->tileTypeId = ntileType;
mapTiles.push_back(newTile);
}
xPosField->set_number( xPos );
yPosField->set_number( yPos );
fieldTileWidth->set_number( tileWidth );
fieldTileHeight->set_number( tileHeight );
fieldAmountX->set_number( tileAmountX );
fieldAmountY->set_number( tileAmountY );
gpe::error_log->report("Tile Map created.");
}
int GPE_SceneTileMap::get_map_size()
{
return (int)mapTiles.size();
}
int GPE_SceneTileMap::get_xmax()
{
return xPos+tileWidth * tileAmountX;
}
int GPE_SceneTileMap::get_ymax()
{
return yPos+tileHeight * tileAmountY;
}
int GPE_SceneTileMap::get_sizex()
{
return tileAmountX;
}
int GPE_SceneTileMap::get_sizey()
{
return tileAmountY;
}
int GPE_SceneTileMap::get_tile_x( int xInPixels)
{
if( tileAmountX == 0 || tileWidth == 0)
{
return -1;
}
if( xInPixels > xPos )
{
xInPixels-= xPos;
if( xInPixels < tileWidth * tileAmountX )
{
return xInPixels /tileWidth;
}
else
{
return tileAmountX;
}
}
return -1;
}
int GPE_SceneTileMap::get_tile_y( int yInPixels)
{
if( tileAmountY == 0 || tileHeight == 0)
{
return -1;
}
if( yInPixels > yPos )
{
yInPixels-= yPos;
if( yInPixels < tileHeight * tileAmountY )
{
return yInPixels /tileHeight;
}
else
{
return tileAmountY;
}
}
return -1;
}
GPE_SceneTile* GPE_SceneTileMap::get_tile_at(int xIn, int yIn)
{
if( xIn >=0 && yIn >=0)
{
if( xIn < tileAmountX && yIn < tileAmountY)
{
int cTilePosition = xIn+ yIn*tileAmountX;
if( cTilePosition >=0 && cTilePosition < (int)mapTiles.size() )
{
return mapTiles.at(cTilePosition);
}
}
}
return NULL;
}
void GPE_SceneTileMap::process_elements()
{
GPE_SceneBasicClass::process_elements();
int previousTileSheetId = tilesheetDropDown->get_selected_id();
PANEL_TS_RESOURCE = GPE_DOCK->find_panel("Tilesheet");
if(PANEL_TS_RESOURCE!=NULL )
{
if( tSPreviewer!=NULL )
{
tSPreviewer->tileSheetToPreview = NULL;
PANEL_TS_RESOURCE->clear_panel();
PANEL_TS_RESOURCE->add_gui_element(tilesheetDropDown,true);
if( tilesheetDropDown!=NULL && tSPreviewer!=NULL )
{
if( tilesheetDropDown->is_clicked() || previousTileSheetId != tilesheetDropDown->get_selected_id() )
{
tileToPlaceX1 = 0;
tileToPlaceY1 = 0;
tileToPlaceX2 = 0;
tileToPlaceY2 = 0;
tilesToPlacePerRow = 0;
tileIdsToPlace.clear();
tSPreviewer->reset_preview(true);
}
GPE_GeneralResourceContainer * tsTypeContainer = tilesheetDropDown->get_selected_container();
if( tsTypeContainer!=NULL)
{
tsRes = (tilesheetResource*) tsTypeContainer->get_held_resource();
tSPreviewer->tileSheetToPreview = tsRes->tilesheetInEditor;
}
tSPreviewer->set_width( PANEL_TS_RESOURCE->get_width()-GENERAL_GPE_GUI_PADDING );
tSPreviewer->set_height( PANEL_TS_RESOURCE->get_height()-GENERAL_GPE_GUI_PADDING-tilesheetDropDown->get_height() );
PANEL_TS_RESOURCE->add_gui_element(tSPreviewer,true);
}
PANEL_TS_RESOURCE->process_self( );
}
}
int sceneTileMouseX = 0;
int sceneTileMouseY = 0;
if( spm !=NULL )
{
if( tileWidth > 0)
{
sceneTileMouseX = ( spm->mouseXPos - xPos) / tileWidth;
}
else
{
sceneTileMouseX = 0;
}
if( tileHeight > 0)
{
sceneTileMouseY = ( spm->mouseYPos - yPos) /tileHeight;
}
}
else
{
return;
}
//if( shortcutButtonBar->get_tab_id() == SCENE_MODE_PLACE && mouseIsInScene && tSPreviewer!=NULL && !selectedLayerMap->isLocked )
if( tSPreviewer!=NULL && !isLocked && tSPreviewer!=NULL && spm->mouseInScene && spm->editMode == SCENE_MODE_PLACE )
{
if( gpe::input->check_mouse_down( mb_left ) && tileWidth > 0 && tileHeight > 0 && (int)tSPreviewer->tilesIdsInPreview.size()>0 )
{
//Place Tiles and Such
if( tsRes!=NULL && tsRes->tilesheetInEditor!=NULL && tsRes->tilesheetInEditor->tsImage!=NULL)
{
//select tiles to place / place tiles / add tiles
//if( RESOURCE_TO_DRAG==NULL && mouseIsInScene && sceneXScroll->is_scrolling()==false && sceneYScroll->is_scrolling()==false )
{
GPE_SceneTile* fSceneTileToEdit = NULL;
int tileRowItr = 0;
int tilesItr= 0;
int newTileX = 0, newTileY = 0;
for( tilesItr = 0; tilesItr < (int)tSPreviewer->tilesIdsInPreview.size(); tilesItr++ )
{
fSceneTileToEdit = get_tile_at(sceneTileMouseX+newTileX,sceneTileMouseY+newTileY);
if( fSceneTileToEdit!=NULL)
{
fSceneTileToEdit->tileIndexId = tSPreviewer->tilesIdsInPreview.at(tilesItr);
fSceneTileToEdit->tilesheetIndexId = tilesheetDropDown->get_selected_id();
fSceneTileToEdit->tileTypeId = 1;
}
else
{
// main_OVERLAY->update_tooltip("Unable to find scene tile to edit...");
}
newTileX+=1;
tileRowItr+=1;
if( tileRowItr >= tSPreviewer->tilesToPlacePerRow)
{
tileRowItr = 0;
newTileX = 0;
newTileY+=1;
}
}
}
}
}
}
//else if(shortcutButtonBar->get_tab_id() == SCENE_MODE_ERASE && mouseIsInScene && selectedLayerMap!=NULL && !selectedLayerMap->isLocked )
else if( !isLocked && gpe::input->check_mouse_down( mb_right ) && spm->mouseInScene && spm->editMode == SCENE_MODE_ERASE )
{
//Remove Tiles / Delete Tiles
//if( mouseIsInScene && sceneXScroll->is_scrolling()==false && sceneYScroll->is_scrolling()==false )
if( spm!=NULL )
{
GPE_SceneTile* fSceneTileToEdit = NULL;
fSceneTileToEdit = get_tile_at(sceneTileMouseX,sceneTileMouseY);
if( fSceneTileToEdit!=NULL )
{
fSceneTileToEdit->tileIndexId = -1;
fSceneTileToEdit->tilesheetIndexId = -1;
fSceneTileToEdit->tileTypeId = 1;
}
}
}
}
void GPE_SceneTileMap::resize_tilemap( int newTX, int newTY,int ntileType)
{
if( (newTX!=tileAmountX || newTY!=tileAmountY )&& newTX>0 && newTY>0)
{
int newSize = newTX*newTY;
GPE_SceneTile *newTile = NULL;
GPE_SceneTile *prevTile = NULL;
int i, j;
std::vector <GPE_SceneTile*> tempMapTiles;
for( i=0; i<(int)mapTiles.size(); i++)
{
prevTile = mapTiles[i];
newTile = new GPE_SceneTile();
if( prevTile!=NULL)
{
newTile->tileTypeId = ntileType;
newTile->tileIndexId = prevTile->tileIndexId;
newTile->tilesheetIndexId = prevTile->tilesheetIndexId;
}
tempMapTiles.push_back(newTile);
}
//destroys old map to be reborn later
if( (int)mapTiles.size() >0 )
{
for(std::vector<GPE_SceneTile*>::const_iterator it = mapTiles.begin(); it != mapTiles.end(); it++)
{
delete *it;
}
}
mapTiles.clear();
gpe::error_log->report("Map cleared ("+ stg_ex::int_to_string((int)mapTiles.size() ) +").");
gpe::error_log->report("New Dimensions ("+ stg_ex::int_to_string(newTX) +" x "+ stg_ex::int_to_string(newTY)+" = "+ stg_ex::int_to_string(newSize)+".");
for( i=0; i<newSize; i++)
{
newTile = new GPE_SceneTile();
newTile->tileTypeId = ntileType;
mapTiles.push_back(newTile);
}
gpe::error_log->report("Map resized ("+ stg_ex::int_to_string((int)mapTiles.size() ) +").");
//creates the tile layer with new dimensions all blanked out
newTile = NULL;
int iMaxPrevXTiles = std::max(newTX, tileAmountX);
int jMaxPrevYTiles = std::max(newTY, tileAmountY);
if( (int)tempMapTiles.size() >0 && (int)mapTiles.size() >0 )
{
for( j=0; j<jMaxPrevYTiles; j++)
{
for( i=0; i<iMaxPrevXTiles; i++)
{
if( tileAmountX > i && tileAmountY > j)
{
prevTile = tempMapTiles.at(i+tileAmountX*j);
}
else
{
prevTile = NULL;
}
if( newTX > i && newTY > j)
{
newTile = mapTiles.at(i+newTX*j);
}
else
{
newTile = NULL;
}
if( prevTile!=NULL && newTile!=NULL)
{
newTile->tileTypeId = prevTile->tileIndexId;
newTile->tileIndexId = prevTile->tileIndexId;
newTile->tilesheetIndexId = prevTile->tilesheetIndexId;
}
}
}
}
tileAmountX=newTX;
tileAmountY=newTY;
//destroys the temp map
if( (int)tempMapTiles.size() >0 )
{
for(std::vector<GPE_SceneTile*>::const_iterator itOld = tempMapTiles.begin(); itOld != tempMapTiles.end(); itOld++)
{
delete *itOld;
}
tempMapTiles.clear();
}
xPosField->set_number( xPos );
yPosField->set_number( yPos );
fieldTileWidth->set_number( tileWidth );
fieldTileHeight->set_number( tileHeight );
fieldAmountX->set_number( tileAmountX );
fieldAmountY->set_number( tileAmountY );
gpe::error_log->report("Tile Map created.");
gpe::error_log->report("Map updated after resize ("+ stg_ex::int_to_string((int)mapTiles.size() ) +").");
}
}
void GPE_SceneTileMap::set_map_size( int newW, int newH )
{
if( tileWidth !=0 & tileHeight!=0 )
{
int expectedNewSizeX = ceil( (float)newW/tileWidth );
int expectedNewSizeY = ceil( (float)newW/tileHeight );
if( prevTileAmountX < tileAmountX || prevTileAmountX < tileAmountY )
{
resize_tilemap( expectedNewSizeX, expectedNewSizeY);
}
}
}
void GPE_SceneTileMap::render_branch()
{
//Avoid the time waste and don't continue if alpha is too low.
if( branchAlpha!=NULL && branchAlpha->get_value() < 5)
{
return;
}
if( spm == NULL)
{
return;
}
if( spm->cSceneTstList!=NULL && tileWidth!=0 && tileHeight!=0 && spm->zoomValue!=0 )
{
gpe::shape_rect foundTsRect;
int cTileXPos = 0;
int cTileYPos = 0;
int i = 0;
int j = 0;
int foundTilePos = 0;
int tileXStartPos = std::max(0, get_tile_x( spm->cameraFloorXPos )-2 );
int tileYStartPos = std::max(0, get_tile_y( spm->cameraFloorYPos )-2 );
int tileXEndPos = tileXStartPos + std::max(0,get_tile_x( ( spm->currentCamera->w / spm->zoomValue) ) ) +2;
int tileYEndPos = tileYStartPos + std::max(0,get_tile_y( ( spm->currentCamera->h / spm->zoomValue) ) ) +2;
if( tileXStartPos>=0 && tileXStartPos > tileXEndPos)
{
tileXEndPos = tileAmountX;
}
if( tileYStartPos>=0 && tileYStartPos > tileYEndPos)
{
tileYEndPos = tileAmountY;
}
GPE_SceneTile * fSceneTile = NULL;
GPE_GeneralResourceContainer * foundTSResource = NULL;
tilesheetResource * foundHeldTSRes = NULL;
//gpe::error_log->report("Performing 1st loop");
for( i = tileXStartPos; i < tileAmountX; i++ )
{
//gpe::error_log->report("Performing 2nd loop");
for( j = tileYStartPos; j < tileAmountY; j++)
{
fSceneTile = get_tile_at( i, j);
if( fSceneTile!=NULL)
{
if( fSceneTile->tilesheetIndexId >= 0 && fSceneTile->tileIndexId >= 0 )
{
foundTSResource = spm->cSceneTstList->find_resource_from_id(fSceneTile->tilesheetIndexId);
if( foundTSResource!=NULL)
{
foundHeldTSRes = (tilesheetResource * )foundTSResource->get_held_resource();
if( foundHeldTSRes->tilesheetInEditor!=NULL )
{
if( foundHeldTSRes->tilesheetInEditor->tsImage!=NULL && fSceneTile->tileIndexId < (int)foundHeldTSRes->tilesheetInEditor->tsRects.size() )
{
cTileXPos = floor( (i*tileWidth ) * spm->zoomValue ) - spm->currentCamera->x * spm->zoomValue;
cTileYPos = floor( (j*tileHeight ) * spm->zoomValue ) - spm->currentCamera->y * spm->zoomValue;
foundTsRect = foundHeldTSRes->tilesheetInEditor->tsRects.at(fSceneTile->tileIndexId );
//if( check_collision(editorCameraRect,cTileXPos,cTileYPos,foundTsRect.w,foundTsRect.h) )
{
foundHeldTSRes->tilesheetInEditor->tsImage->render_tex_scaled( cTileXPos,cTileYPos, spm->zoomValue,spm->zoomValue,&foundTsRect,branchColor->get_color(), branchAlpha->get_value() );
/*if( renderOutlines )
{
gpe::gcanvas->render_rectangle( cTileXPos,cTileYPos, cTileXPos+ceil( (float)foundTsRect.w*spm->zoomValue),cTileYPos+ceil( (float)foundTsRect.h*spm->zoomValue ), c_red, true, 255 );
//render_text( cTileXPos,cTileYPos, stg_ex::int_to_string(fSceneTile->tilesheetIndexId)+"-"+ stg_ex::int_to_string(fSceneTile->tileIndexId),c_red,font_default,gpe::fa_left,gpe::fa_top, 255 );
}
*/
}
}
}
}
}
}
}
//gpe::error_log->report("2nd loop completed");
}
//gpe::error_log->report("1st loop completed");
//Previews tilesheet if selected
GPE_GeneralResourceContainer * tsTypeContainer = tilesheetDropDown->get_selected_container();
if( tsTypeContainer!=NULL && spm->mouseInScene && spm->editMode == SCENE_MODE_PLACE && RESOURCE_TO_DRAG==NULL )
{
tsRes = (tilesheetResource*) tsTypeContainer->get_held_resource();
if( tsRes!=NULL && tsRes->tilesheetInEditor!=NULL && tsRes->tilesheetInEditor->tsImage!=NULL)
{
//if( sceneXScroll->is_scrolling()==false && sceneYScroll->is_scrolling()==false )
{
int sceneTileMouseX = spm->mouseXPos;
int sceneTileMouseY = spm->mouseYPos;
if( tileWidth!=0 &&tileHeight!=0)
{
sceneTileMouseX = sceneTileMouseX/tileWidth;
sceneTileMouseX = (sceneTileMouseX *tileWidth);
sceneTileMouseY = sceneTileMouseY/tileHeight;
sceneTileMouseY = (sceneTileMouseY *tileHeight);
}
sceneTileMouseX = floor( (sceneTileMouseX*spm->zoomValue-spm->cameraFloorXPos * spm->zoomValue ) );
sceneTileMouseY = floor( (sceneTileMouseY*spm->zoomValue-spm->cameraFloorYPos * spm->zoomValue) );
if( isLocked )
{
tSPreviewer->render_selection( sceneTileMouseX,sceneTileMouseY, NULL,NULL, spm->zoomValue, gpe::c_orangered );
}
else if( sceneTileMouseX >=0 && sceneTileMouseY >=0 )
{
tSPreviewer->render_selection( sceneTileMouseX,sceneTileMouseY,NULL,NULL,spm->zoomValue, gpe::c_white );
}
/*
else if( spm->mouseXPos < 0 || spm->mouseYPos < 0 || spm->mouseXPos > spm->tempRect->w || spm->mouseYPos > spm->tempRect->h )
{
tSPreviewer->render_selection( sceneTileMouseX,sceneTileMouseY,NULL,NULL,true,spm->zoomValue, c_red );
}
else
{
tSPreviewer->render_selection( sceneTileMouseX,sceneTileMouseY,NULL,NULL,true,spm->zoomValue,c_white);
}
*/
}
}
}
}
GPE_SpecialMenu_Branch::render_branch();
}
bool GPE_SceneTileMap::save_branch_data(std::ofstream * fileTarget, int nestedFoldersIn )
{
if( fileTarget!=NULL && fileTarget->is_open() )
{
std::string nestedTabsStr = generate_tabs( nestedFoldersIn );
*fileTarget << nestedTabsStr+ "[GPE_TileMap=";
*fileTarget << stg_ex::int_to_string( tileWidth )+",";
*fileTarget << stg_ex::int_to_string( tileHeight )+",";
*fileTarget << stg_ex::int_to_string( tileAmountX )+",";
*fileTarget << stg_ex::int_to_string( tileAmountY )+",";
*fileTarget << stg_ex::int_to_string( xPos )+",";
*fileTarget << stg_ex::int_to_string( yPos )+",";
if( fillScene!=NULL)
{
*fileTarget << stg_ex::int_to_string( fillScene->is_clicked() )+",";
}
else
{
*fileTarget << "0,";
}
if( (int)name.size() > 0 )
{
*fileTarget << name +",,";
}
else
{
*fileTarget << +"tilemap,,";
}
*fileTarget << "]\n";
GPE_SceneBasicClass::save_branch_data( fileTarget, nestedFoldersIn+1 );
int maxTilesInMap = (int)mapTiles.size();
nestedTabsStr = generate_tabs( nestedFoldersIn+1 );
GPE_SceneTile * fSceneTile = NULL;
for( int i = 0; i < maxTilesInMap; i++)
{
fSceneTile = mapTiles.at(i);
if( fSceneTile!=NULL && fSceneTile->tilesheetIndexId > 0 && fSceneTile->tileIndexId >= 0 )
{
*fileTarget << nestedTabsStr+ "GPE_SingleTile=";
//This is the position of the tile in the tilemap
*fileTarget << stg_ex::int_to_string( i )+",";
*fileTarget << stg_ex::int_to_string( fSceneTile->tilesheetIndexId )+",";
*fileTarget << stg_ex::int_to_string( fSceneTile->tileIndexId )+",";
*fileTarget << stg_ex::int_to_string( fSceneTile->tileTypeId )+",";
/*
*fileTarget << fSceneTile->get_name() +",,";
//For later version I plan to add more data here...
fSceneTile->save_branch_data( fileTarget, nestedFoldersIn+1 );
*/
*fileTarget << "\n";
}
}
*fileTarget << nestedTabsStr+"[/GPE_TileMap]\n";
return true;
}
return false;
}
| 27,650 | 9,255 |
#include <limits>
#include "common/common/basic_resource_impl.h"
#include "test/mocks/runtime/mocks.h"
#include "gtest/gtest.h"
using testing::NiceMock;
using testing::Return;
namespace Envoy {
class BasicResourceLimitImplTest : public testing::Test {
protected:
NiceMock<Runtime::MockLoader> runtime_;
};
TEST_F(BasicResourceLimitImplTest, NoArgsConstructorVerifyMax) {
BasicResourceLimitImpl br;
EXPECT_EQ(br.max(), std::numeric_limits<uint64_t>::max());
}
TEST_F(BasicResourceLimitImplTest, VerifySetClearMax) {
BasicResourceLimitImpl br(123);
EXPECT_EQ(br.max(), 123);
br.setMax(321);
EXPECT_EQ(br.max(), 321);
br.resetMax();
EXPECT_EQ(br.max(), std::numeric_limits<uint64_t>::max());
}
TEST_F(BasicResourceLimitImplTest, IncDecCount) {
BasicResourceLimitImpl br;
EXPECT_EQ(br.count(), 0);
br.inc();
EXPECT_EQ(br.count(), 1);
br.inc();
br.inc();
EXPECT_EQ(br.count(), 3);
br.dec();
EXPECT_EQ(br.count(), 2);
br.decBy(2);
EXPECT_EQ(br.count(), 0);
}
TEST_F(BasicResourceLimitImplTest, CanCreate) {
BasicResourceLimitImpl br(2);
EXPECT_TRUE(br.canCreate());
br.inc();
EXPECT_TRUE(br.canCreate());
br.inc();
EXPECT_FALSE(br.canCreate());
br.dec();
EXPECT_TRUE(br.canCreate());
br.dec();
}
TEST_F(BasicResourceLimitImplTest, RuntimeMods) {
BasicResourceLimitImpl br(1337, runtime_, "trololo");
EXPECT_CALL(runtime_.snapshot_, getInteger("trololo", 1337)).WillOnce(Return(555));
EXPECT_EQ(br.max(), 555);
EXPECT_CALL(runtime_.snapshot_, getInteger("trololo", 1337)).WillOnce(Return(1337));
EXPECT_EQ(br.max(), 1337);
}
} // namespace Envoy
| 1,625 | 672 |
/*
==============================================================================
KratosR1StructuralApplication
A library based on:
Kratos
A General Purpose Software for Multi-Physics Finite Element Analysis
Version 1.0 (Released on march 05, 2007).
Copyright 2007
Pooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel
pooyan@cimne.upc.edu
rrossi@cimne.upc.edu
janosch.stascheit@rub.de
nagel@sd.rub.de
- CIMNE (International Center for Numerical Methods in Engineering),
Gran Capita' s/n, 08034 Barcelona, Spain
- Ruhr-University Bochum, Institute for Structural Mechanics, Germany
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 condition:
Distribution of this code for any commercial purpose is permissible
ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS.
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.
==============================================================================
*/
/* **************************************************************************************
*
* Last Modified by: $Author: mengmeng $
* Date: $Date: 2008-10-17 11:58:58 $
* Revision: $Revision: 1.1 $
*
* ***************************************************************************************/
// System includes
// External includes
// Project includes
#include "includes/define.h"
#include "custom_conditions/face_load_pressure.h"
#include "includes/variables.h"
#include "freezing_soil_application.h"
#include "utilities/math_utils.h"
namespace Kratos
{
//----------------------
//----- PUBLIC -------
//----------------------
// Constructor
//***********************************************************************************
FaceLoadPressure::FaceLoadPressure() {}
//***********************************************************************************
FaceLoadPressure::FaceLoadPressure(IndexType NewId, GeometryType::Pointer pGeometry)
: Condition(NewId, pGeometry) {}
//***********************************************************************************
FaceLoadPressure::FaceLoadPressure(IndexType NewId, GeometryType::Pointer pGeometry, PropertiesType::Pointer pProperties)
: Condition(NewId, pGeometry, pProperties) {}
//***********************************************************************************
Condition::Pointer FaceLoadPressure::Create(IndexType NewId, NodesArrayType const& ThisNodes, PropertiesType::Pointer pProperties) const
{
return Condition::Pointer(new FaceLoadPressure(NewId, GetGeometry().Create(ThisNodes), pProperties));
}
// Destructor
//***********************************************************************************
FaceLoadPressure::~FaceLoadPressure() {}
//***********************************************************************************
void FaceLoadPressure::EquationIdVector(EquationIdVectorType& rResult, ProcessInfo& rCurrentProcessInfo)
{
KRATOS_TRY
unsigned int number_of_nodes = GetGeometry().size();
unsigned int dof = number_of_nodes * 3;
if ( rResult.size() != dof )
rResult.resize( dof );
for ( unsigned int i = 0; i < number_of_nodes; i++ )
{
int index = i * 3;
rResult[index] = GetGeometry()[i].GetDof( DISPLACEMENT_X ).EquationId();
rResult[index+1] = GetGeometry()[i].GetDof( DISPLACEMENT_Y ).EquationId();
rResult[index+2] = GetGeometry()[i].GetDof( DISPLACEMENT_Z ).EquationId();
}
KRATOS_CATCH( "" )
}
//***********************************************************************************
void FaceLoadPressure::GetDofList(DofsVectorType& ElementalDofList, ProcessInfo& rCurrentProcessInfo)
{
ElementalDofList.resize(0);
for ( unsigned int i = 0; i < GetGeometry().size(); i++ )
{
ElementalDofList.push_back( GetGeometry()[i].pGetDof( DISPLACEMENT_X ) );
ElementalDofList.push_back( GetGeometry()[i].pGetDof( DISPLACEMENT_Y ) );
ElementalDofList.push_back( GetGeometry()[i].pGetDof( DISPLACEMENT_Z ) );
}
}
//***********************************************************************************
void FaceLoadPressure::CalculateRightHandSide(VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo)
{
//calculation flags
bool CalculateStiffnessMatrixFlag = false;
bool CalculateResidualVectorFlag = true;
MatrixType temp = Matrix();
CalculateAll(temp, rRightHandSideVector, rCurrentProcessInfo, CalculateStiffnessMatrixFlag, CalculateResidualVectorFlag);
}
//***********************************************************************************
void FaceLoadPressure::CalculateLocalSystem(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, ProcessInfo& rCurrentProcessInfo)
{
//calculation flags
bool CalculateStiffnessMatrixFlag = true;
bool CalculateResidualVectorFlag = true;
CalculateAll(rLeftHandSideMatrix, rRightHandSideVector, rCurrentProcessInfo, CalculateStiffnessMatrixFlag, CalculateResidualVectorFlag);
}
//***********************************************************************************
void FaceLoadPressure::MassMatrix(MatrixType& rMassMatrix, ProcessInfo& rCurrentProcessInfo)
{
KRATOS_TRY
rMassMatrix.resize(0,0,false);
KRATOS_CATCH("")
}
//***********************************************************************************
void FaceLoadPressure::DampMatrix(MatrixType& rDampMatrix, ProcessInfo& rCurrentProcessInfo)
{
KRATOS_TRY
rDampMatrix.resize(0,0,false);
KRATOS_CATCH("")
}
//***********************************************************************************
void FaceLoadPressure::GetValuesVector(Vector& values, int Step)
{
unsigned int number_of_nodes = GetGeometry().size();
unsigned int MatSize = number_of_nodes * 3;
if (values.size() != MatSize)
values.resize(MatSize);
for (unsigned int i=0;i<number_of_nodes;i++)
{
const array_1d<double, 3>& disp = GetGeometry()[i].FastGetSolutionStepValue( DISPLACEMENT, Step );
unsigned int index = i * 3;
values[index] = disp[0];
values[index+1] = disp[1];
values[index+2] = disp[2];
}
}
//----------------------
//----- PRIVATE ------
//----------------------
//***********************************************************************************
void FaceLoadPressure::CalculateAll(MatrixType& rLeftHandSideMatrix, VectorType& rRightHandSideVector, const ProcessInfo& rCurrentProcessInfo, bool CalculateStiffnessMatrixFlag, bool CalculateResidualVectorFlag)
{
KRATOS_TRY
const unsigned int number_of_nodes = GetGeometry().size();
unsigned int MatSize = number_of_nodes * 3;
const unsigned int dim = 3;
//resizing as needed the LHS
if (CalculateStiffnessMatrixFlag == true) //calculation of the matrix is required
{
if (rLeftHandSideMatrix.size1() != MatSize)
rLeftHandSideMatrix.resize(MatSize,MatSize,false);
noalias(rLeftHandSideMatrix) = ZeroMatrix(MatSize,MatSize); //resetting LHS
}
//resizing as needed the RHS
if (CalculateResidualVectorFlag == true) //calculation of the matrix is required
{
if (rRightHandSideVector.size() != MatSize)
rRightHandSideVector.resize(MatSize);
rRightHandSideVector = ZeroVector(MatSize); //resetting RHS
}
//reading integration points and local gradients
const GeometryType::IntegrationPointsArrayType& integration_points = GetGeometry().IntegrationPoints();
const GeometryType::ShapeFunctionsGradientsType& DN_DeContainer = GetGeometry().ShapeFunctionsLocalGradients();
const Matrix& Ncontainer = GetGeometry().ShapeFunctionsValues();
//calculating actual jacobian
GeometryType::JacobiansType J;
J = GetGeometry().Jacobian(J);
// for ( unsigned int n = 0; n < number_of_nodes; n++ )
// std::cout << "+++ node "<<n<<": face_load= "<<( GetGeometry()[n] ).GetSolutionStepValue( FACE_LOAD_PRESSURE )<<" +++" << std::endl;
//auxiliary terms
for (unsigned int PointNumber=0; PointNumber<integration_points.size(); PointNumber++)
{
Vector Load( 3 );
noalias( Load ) = ZeroVector( 3 );
Vector temp( 3 );
for ( unsigned int n = 0; n < number_of_nodes; n++ )
{
// noalias( temp ) = ( GetGeometry()[n] ).GetSolutionStepValue( FACE_LOAD_PRESSURE );
// for ( unsigned int i = 0; i < 3; i++ )
// Load( i ) += temp( i ) * Ncontainer( PointNumber, n );
Load[0] += ( GetGeometry()[n] ).FastGetSolutionStepValue( FACE_LOAD_PRESSURE_X ) * Ncontainer( PointNumber, n );
Load[1] += ( GetGeometry()[n] ).FastGetSolutionStepValue( FACE_LOAD_PRESSURE_Y ) * Ncontainer( PointNumber, n );
Load[2] += ( GetGeometry()[n] ).FastGetSolutionStepValue( FACE_LOAD_PRESSURE_Z ) * Ncontainer( PointNumber, n );
}
// if ( PointNumber == 1 )
// std::cout << "CONDITION ### FaceLoadPressure: load= " << Load << std::endl;
double IntegrationWeight = GetGeometry().IntegrationPoints()[PointNumber].Weight();
//to be replaced by the formulation in Face3D
Vector t1 = ZeroVector( 3 );//first tangential vector
Vector t2 = ZeroVector( 3 );//second tangential vector
for ( unsigned int n = 0; n < number_of_nodes; n++ )
{
t1[0] += GetGeometry().GetPoint( n ).X0() * DN_DeContainer[PointNumber]( n, 0 );
t1[1] += GetGeometry().GetPoint( n ).Y0() * DN_DeContainer[PointNumber]( n, 0 );
t1[2] += GetGeometry().GetPoint( n ).Z0() * DN_DeContainer[PointNumber]( n, 0 );
t2[0] += GetGeometry().GetPoint( n ).X0() * DN_DeContainer[PointNumber]( n, 1 );
t2[1] += GetGeometry().GetPoint( n ).Y0() * DN_DeContainer[PointNumber]( n, 1 );
t2[2] += GetGeometry().GetPoint( n ).Z0() * DN_DeContainer[PointNumber]( n, 1 );
}
//calculating normal
Vector v3 = ZeroVector( 3 );
v3[0] = t1[1] * t2[2] - t1[2] * t2[1];
v3[1] = t1[2] * t2[0] - t1[0] * t2[2];
v3[2] = t1[0] * t2[1] - t1[1] * t2[0];
double dA = sqrt( v3[0] * v3[0] + v3[1] * v3[1] + v3[2] * v3[2] );
// RIGHT HAND SIDE VECTOR
if ( CalculateResidualVectorFlag == true ) //calculation of the matrix is required
{
for ( unsigned int prim = 0; prim < number_of_nodes; prim++ )
for ( unsigned int i = 0; i < 3; i++ )
rRightHandSideVector( prim*dim + i ) +=
Ncontainer( PointNumber, prim ) * Load( i ) * IntegrationWeight * dA;
}
}
KRATOS_CATCH("")
}
} // Namespace Kratos.
| 11,580 | 3,580 |
#include "glog/logging.h"
#include "gtest/gtest.h"
#include "comm/sender.hpp"
#include <iostream>
#include <vector>
namespace minips {
namespace {
class TestSender : public testing::Test {
public:
TestSender() {}
~TestSender() {}
protected:
void SetUp() {}
void TearDown() {}
};
class FakeMailbox : public AbstractMailbox {
public:
virtual int Send(const Message &msg) override {
to_send_.Push(msg);
return -1;
}
void WaitAndPop(Message *msg) {
to_send_.WaitAndPop(msg);
}
private:
ThreadsafeQueue<Message> to_send_;
};
TEST_F(TestSender, StartStop) {
FakeMailbox mailbox;
Sender sender(&mailbox);
sender.Start();
sender.Stop();
}
TEST_F(TestSender, Send) {
FakeMailbox mailbox;
Sender sender(&mailbox);
sender.Start();
auto *send_queue = sender.GetMessageQueue();
// Msg
Message msg;
msg.meta.sender = 123;
msg.meta.recver = 0;
msg.meta.model_id = 0;
msg.meta.flag = Flag::kGet;
third_party::SArray<Key> keys{1};
third_party::SArray<float> vals{0.1};
msg.AddData(keys);
msg.AddData(vals);
// Push the firstbmsg
send_queue->Push(msg);
Message res;
mailbox.WaitAndPop(&res);
EXPECT_EQ(res.meta.sender, msg.meta.sender);
// Push the second msg
msg.meta.sender = 543;
send_queue->Push(msg);
mailbox.WaitAndPop(&res);
EXPECT_EQ(res.meta.sender, msg.meta.sender);
sender.Stop();
}
} // namespace
} // namespace minips
| 1,940 | 566 |
/****************************************************************************
* Copyright (c) 2019-2020 by the Cajita authors *
* All rights reserved. *
* *
* This file is part of the Cajita library. Cajita is distributed under a *
* BSD 3-clause license. For the licensing terms see the LICENSE file in *
* the top-level directory. *
* *
* SPDX-License-Identifier: BSD-3-Clause *
****************************************************************************/
#ifndef CAJITA_HPP
#define CAJITA_HPP
#include <Cajita_Array.hpp>
#include <Cajita_BovWriter.hpp>
#include <Cajita_Config.hpp>
#include <Cajita_GlobalGrid.hpp>
#include <Cajita_GlobalMesh.hpp>
#include <Cajita_Halo.hpp>
#include <Cajita_IndexSpace.hpp>
#include <Cajita_Interpolation.hpp>
#include <Cajita_LocalGrid.hpp>
#include <Cajita_LocalMesh.hpp>
#include <Cajita_ManualPartitioner.hpp>
#include <Cajita_MpiTraits.hpp>
#include <Cajita_Partitioner.hpp>
#include <Cajita_ReferenceStructuredSolver.hpp>
#include <Cajita_Splines.hpp>
#include <Cajita_Types.hpp>
#include <Cajita_UniformDimPartitioner.hpp>
#include <Cajita_Version.hpp>
#ifdef CAJITA_HAVE_HYPRE
#include <Cajita_HypreStructuredSolver.hpp>
#endif
#ifdef CAJITA_HAVE_HEFFTE
#include <Cajita_FastFourierTransform.hpp>
#endif
#endif // end CAJITA_HPP
| 1,602 | 514 |
// Generated by zsLibEventingTool
#include "impl_org_webRtc_RTCRemoteOutboundRtpStreamStats.h"
using ::zsLib::String;
using ::zsLib::Optional;
using ::zsLib::Any;
using ::zsLib::AnyPtr;
using ::zsLib::AnyHolder;
using ::zsLib::Promise;
using ::zsLib::PromisePtr;
using ::zsLib::PromiseWithHolder;
using ::zsLib::PromiseWithHolderPtr;
using ::zsLib::eventing::SecureByteBlock;
using ::zsLib::eventing::SecureByteBlockPtr;
using ::std::shared_ptr;
using ::std::weak_ptr;
using ::std::make_shared;
using ::std::list;
using ::std::set;
using ::std::map;
// borrow definitions from class
ZS_DECLARE_TYPEDEF_PTR(wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::WrapperImplType, WrapperImplType);
ZS_DECLARE_TYPEDEF_PTR(WrapperImplType::WrapperType, WrapperType);
//------------------------------------------------------------------------------
wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::RTCRemoteOutboundRtpStreamStats() noexcept
{
}
//------------------------------------------------------------------------------
wrapper::org::webRtc::RTCRemoteOutboundRtpStreamStatsPtr wrapper::org::webRtc::RTCRemoteOutboundRtpStreamStats::wrapper_create() noexcept
{
auto pThis = make_shared<wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats>();
pThis->thisWeak_ = pThis;
return pThis;
}
//------------------------------------------------------------------------------
wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::~RTCRemoteOutboundRtpStreamStats() noexcept
{
thisWeak_.reset();
}
//------------------------------------------------------------------------------
::zsLib::Time wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_timestamp() noexcept
{
::zsLib::Time result {};
return result;
}
//------------------------------------------------------------------------------
Optional< wrapper::org::webRtc::RTCStatsType > wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_statsType() noexcept
{
Optional< wrapper::org::webRtc::RTCStatsType > result {};
return result;
}
//------------------------------------------------------------------------------
String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_statsTypeOther() noexcept
{
String result {};
return result;
}
//------------------------------------------------------------------------------
String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_id() noexcept
{
String result {};
return result;
}
//------------------------------------------------------------------------------
Optional< uint32_t > wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_ssrc() noexcept
{
Optional< uint32_t > result {};
return result;
}
//------------------------------------------------------------------------------
String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_kind() noexcept
{
String result {};
return result;
}
//------------------------------------------------------------------------------
String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_transportId() noexcept
{
String result {};
return result;
}
//------------------------------------------------------------------------------
String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_codecId() noexcept
{
String result {};
return result;
}
//------------------------------------------------------------------------------
unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_firCount() noexcept
{
unsigned long result {};
return result;
}
//------------------------------------------------------------------------------
unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_pliCount() noexcept
{
unsigned long result {};
return result;
}
//------------------------------------------------------------------------------
unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_nackCount() noexcept
{
unsigned long result {};
return result;
}
//------------------------------------------------------------------------------
unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_sliCount() noexcept
{
unsigned long result {};
return result;
}
//------------------------------------------------------------------------------
unsigned long long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_qpSum() noexcept
{
unsigned long long result {};
return result;
}
//------------------------------------------------------------------------------
unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_packetsSent() noexcept
{
unsigned long result {};
return result;
}
//------------------------------------------------------------------------------
unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_packetsDiscardedOnSend() noexcept
{
unsigned long result {};
return result;
}
//------------------------------------------------------------------------------
unsigned long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_fecPacketsSent() noexcept
{
unsigned long result {};
return result;
}
//------------------------------------------------------------------------------
unsigned long long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_bytesSent() noexcept
{
unsigned long long result {};
return result;
}
//------------------------------------------------------------------------------
unsigned long long wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_bytesDiscardedOnSend() noexcept
{
unsigned long long result {};
return result;
}
//------------------------------------------------------------------------------
String wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_localId() noexcept
{
String result {};
return result;
}
//------------------------------------------------------------------------------
::zsLib::Time wrapper::impl::org::webRtc::RTCRemoteOutboundRtpStreamStats::get_remoteTimestamp() noexcept
{
::zsLib::Time result {};
return result;
}
| 6,177 | 1,623 |
#pragma once
#include "nwn_api.hpp"
#include "CExoString.hpp"
#include "CExoLocString.hpp"
#include "CExoArrayList.hpp"
#include "Vector.hpp"
#include "CResRef.hpp"
#include "CNWSObject.hpp"
#ifdef NWN_API_PROLOGUE
NWN_API_PROLOGUE(CNWSPlaceable)
#endif
struct CNWSObjectActionNode;
struct CResStruct;
struct CNWSArea;
struct CNWSItem;
struct CItemRepository;
struct CResGFF;
typedef int BOOL;
typedef uint32_t OBJECT_ID;
struct CNWSPlaceable : CNWSObject
{
CExoLocString m_sLocName;
CExoString m_sDisplayName;
int32_t m_nUpdateDisplayNameSeq;
uint16_t m_nAppearance;
CExoLocString m_sDescription;
CExoString m_sDescriptionOverride;
int32_t m_nFactionId;
CResRef m_cDialog;
uint8_t m_nType;
BOOL m_bGroundPile;
OBJECT_ID m_oidSittingCreature;
uint8_t m_nHardness;
float m_fBearing;
BOOL m_bLocked;
CExoString m_sKeyName;
CExoString m_sKeyRequiredFeedbackMessage;
BOOL m_bKeyRequired;
BOOL m_bAutoRemoveKey;
uint8_t m_nOpenLockDC;
uint8_t m_nCloseLockDC;
OBJECT_ID m_oidTrapCreator;
uint8_t m_nTrapDetectionDC;
BOOL m_bTrapFlag;
uint8_t m_nDisarmDC;
BOOL m_bDisarmable;
BOOL m_bDetectable;
BOOL m_bOneShot;
BOOL m_bRecoverable;
BOOL m_bFlagged;
uint8_t m_nBaseType;
BOOL m_bTrapIsActive;
int32_t m_nTrapFaction;
CExoString m_sScripts[16];
uint8_t m_nFortSave;
uint8_t m_nWillSave;
uint8_t m_nReflexSave;
CExoArrayList<OBJECT_ID> m_poidCreatures;
BOOL m_bHasInventory;
BOOL m_bUseable;
BOOL m_bPickable;
BOOL m_bLockable;
BOOL m_bDieWhenEmpty;
uint32_t m_nOpenCount;
int32_t m_nStaticObjectPosition;
OBJECT_ID m_oidLootCreature;
BOOL m_bIsBodyBag;
uint32_t m_nLastHeartbeatScriptCalendarDay;
uint32_t m_nLastHeartbeatScriptTimeOfDay;
OBJECT_ID m_oidLastOpened;
OBJECT_ID m_oidLastClosed;
OBJECT_ID m_oidLastUser;
OBJECT_ID m_oidLastDefaultClickedBy;
OBJECT_ID m_oidLastTriggered;
OBJECT_ID m_oidLastDisarmed;
OBJECT_ID m_oidLastLocked;
OBJECT_ID m_oidLastUnlocked;
CItemRepository * m_pcItemRepository;
uint16_t m_nRepositoryArrayIndex;
uint16_t m_nItemContainerArrayIndex;
OBJECT_ID m_oidCurrentItemContainer;
Vector m_pvActionPoints[2];
CResRef m_cTemplateResRef;
CExoString m_szPortalInfo;
uint32_t m_nEffectSpellId;
BOOL m_bLightIsOn;
BOOL m_bLightStateChange;
uint8_t m_nBodyBag;
BOOL m_bStaticObject;
BOOL m_bNeverMakeIntoStaticObject;
virtual CNWSPlaceable * AsNWSPlaceable();
CNWSPlaceable(OBJECT_ID oidId = 0x7f000000);
~CNWSPlaceable();
void AddToArea(CNWSArea * pArea, float fX, float fY, float fZ, BOOL bRunScripts = true);
void RemoveFromArea();
void SetOrientation(Vector vOrientation);
void AIUpdate();
void DoDamage(int32_t nDamage);
void EventHandler(uint32_t nEventId, OBJECT_ID nCallerObjectId, void * pScript, uint32_t nCalendarDay, uint32_t nTimeOfDay);
BOOL LoadPlaceable(CResGFF * pRes, CResStruct * cPlaceableStruct, CExoString * pTag = nullptr);
BOOL LoadFromTemplate(CResRef cResRef, CExoString * pTag = nullptr);
BOOL LoadBodyBag(uint16_t nAppearance);
BOOL SavePlaceable(CResGFF * pRes, CResStruct * pStruct, BOOL bSaveOIDs);
void PostProcess();
BOOL AcquireItem(CNWSItem * * pItem, OBJECT_ID oidPossessor = 0x7f000000, uint8_t x = 0xff, uint8_t y = 0xff, BOOL bDisplayFeedback = true);
BOOL RemoveItem(CNWSItem * pItem, BOOL bSetPossessor = true);
uint32_t AcquireItemsFromObject(OBJECT_ID oidObject, BOOL bAcquireDroppablesOnly = true);
void OpenInventory(OBJECT_ID oidOpener);
void CloseInventory(OBJECT_ID oidCloser, BOOL bUpdatePlayer = true);
void DropItemsIntoArea();
Vector GetNearestActionPoint(const Vector & vPosition);
BOOL AddCastSpellActions(uint32_t nSpellId, int32_t nMetaType, Vector vTargetLocation, OBJECT_ID oidTarget, BOOL bFake = false, uint8_t nProjectilePathType = 0);
uint32_t AIActionCastSpell(CNWSObjectActionNode * pNode);
BOOL GetLightIsOn();
void SetLightIsOn(BOOL b);
uint16_t GetBodyBagAppearance();
uint32_t GetItemCount(BOOL bDroppableOnly = true);
void ClosePlaceableForAllPlayers();
void CalculateActionPoints();
#ifdef NWN_CLASS_EXTENSION_CNWSPlaceable
NWN_CLASS_EXTENSION_CNWSPlaceable
#endif
};
#ifdef NWN_API_EPILOGUE
NWN_API_EPILOGUE(CNWSPlaceable)
#endif
| 4,433 | 1,820 |
#include <<%= libraryName %>/export.h>
#include <iostream>
<%= LIBRARYNAME %>_API int <%= libraryName %>_api()
{
std::cout << "hello from <%= libraryName %>" << std::endl;
return 12345;
}
| 197 | 72 |
/* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#include <toolkits/feature_engineering/dict_transform_utils.hpp>
#include <core/data/flexible_type/flexible_type.hpp>
#include <core/data/sframe/gl_sarray.hpp>
namespace turi {
/** Index keys come up in a lot of places, e.g. vectors. This deals
* with that. (Also good to have it as it's own function in case
* we want to update it later on).
*/
static inline flexible_type get_index_key(const flex_int& key) {
return flexible_type(key).to<flex_string>();
};
/** The recursion function to actually add everything to the rest of
* new dictionary.
*
* out -- the final dictionary.
* key -- the current key. May be modified.
* v -- the value to add to the dictionary.
* separator -- the separator string.
* undefined_string -- what to call undefined values.
* process_image_value -- how to process images.
* process_datetime_value -- how to process datetime values.
*/
GL_HOT_FLATTEN
static void _to_flat_dict_recursion(
flex_dict& out,
flex_string& key,
const flexible_type& v,
const flex_string& separator,
const flex_string& undefined_string,
const std::function<flexible_type(const flex_image&)>& process_image_value,
const std::function<flexible_type(const flex_date_time&)>& process_datetime_value,
size_t depth) {
// You probably hit errors before this in other areas of the code,
// e.g. flexible type destructors.
////////////////////////////////////////////////////////////////////////////////
/** Checks to error out if we go too deep.
*/
static constexpr size_t MAX_RECURSION_DEPTH = 64;
// Where we recurse on the value, along with error checking as well.
auto recurse_on_value = [&](const flexible_type& recurse_v) GL_GCC_ONLY(GL_HOT_INLINE) {
auto depth_overflow_error = [&]() GL_GCC_ONLY(GL_COLD_NOINLINE) {
// Check to make sure we haven't reached our recursion depth limit.
std::ostringstream ss;
ss << "Maximum nested depth in dictionary of "
<< MAX_RECURSION_DEPTH
<< " exceeded in flattening dictionary/list. "
<< "This is not the type of deep learning we are used to."
<< std::endl;
throw std::runtime_error(ss.str());
};
if(depth > MAX_RECURSION_DEPTH) {
depth_overflow_error();
}
_to_flat_dict_recursion(out, key, recurse_v,
separator, undefined_string,
process_image_value, process_datetime_value, depth + 1);
};
////////////////////////////////////////////////////////////////////////////////
/** Add a new sub-key to the current key string. Put this in a
* central place so that all the different paths have a consistent
* way of handling the key.
*/
auto add_to_key_string = [&](const flexible_type& key_v) {
// Add in the separator if needed.
if(key.size() != 0) {
key.append(separator);
}
// Write out the key
switch(v.get_type()) {
case flex_type_enum::STRING: {
key.append(key_v.get<flex_string>());
break;
}
case flex_type_enum::UNDEFINED: {
key.append(undefined_string);
break;
}
case flex_type_enum::INTEGER: {
flex_string s = get_index_key(key_v.get<flex_int>());
key.append(s);
break;
}
default: {
flex_string s = key_v.to<flex_string>();
key.append(s);
break;
}
}
};
////////////////////////////////////////////////////////////////////////////////
// Now, handle the value.
size_t base_key_size = key.size();
switch(v.get_type()) {
case flex_type_enum::INTEGER:
case flex_type_enum::FLOAT: {
out.push_back({key, v});
break;
}
case flex_type_enum::DICT: {
const flex_dict& d = v.get<flex_dict>();
for(const auto& p : d) {
add_to_key_string(p.first);
recurse_on_value(p.second);
key.resize(base_key_size);
}
break;
}
case flex_type_enum::UNDEFINED:
case flex_type_enum::STRING: {
add_to_key_string(v);
out.push_back({key, 1});
key.resize(base_key_size);
break;
}
case flex_type_enum::LIST: {
const flex_list& fl = v.get<flex_list>();
for(size_t i = 0; i < fl.size(); ++i) {
add_to_key_string(i);
recurse_on_value(fl[i]);
key.resize(base_key_size);
}
break;
}
case flex_type_enum::VECTOR: {
const flex_vec& fv = v.get<flex_vec>();
for(size_t i = 0; i < fv.size(); ++i) {
add_to_key_string(i);
out.push_back({key, fv[i]});
key.resize(base_key_size);
}
break;
}
case flex_type_enum::IMAGE: {
flexible_type ft_out = process_image_value(v.get<flex_image>());
ASSERT_MSG(ft_out.get_type() != flex_type_enum::IMAGE,
"Handling function for image types returned an image type.");
if(ft_out.get_type() != flex_type_enum::UNDEFINED) {
recurse_on_value(ft_out);
}
break;
}
case flex_type_enum::DATETIME: {
flexible_type ft_out = process_datetime_value(v.get<flex_date_time>());
ASSERT_MSG(ft_out.get_type() != flex_type_enum::DATETIME,
"Handling function for datetime types returned an datetime type.");
if(ft_out.get_type() != flex_type_enum::UNDEFINED) {
recurse_on_value(ft_out);
}
break;
}
case flex_type_enum::ND_VECTOR: {
log_and_throw(std::string("Flexible type case currently unsupported: ND_VECTOR"));
ASSERT_UNREACHABLE();
}
default: {
log_and_throw(std::string("Flexible type case not recognized"));
ASSERT_UNREACHABLE();
}
}
}
/** Flattens any types to a non-nested dictionary of (string key :
* numeric value) pairs. Each nested key is a concatenation of the
* keys in the separation with sep_char separating them. For
* example, if sep_char = ".", then
*
* {"a" : {"b" : 1}, "c" : 2}
*
* becomes
*
* {"a.b" : 1, "c" : 2}.
*
* - List and vector elements are handled by converting the index of
* the appropriate element to a string.
*
* - String values are handled by treating them as a single
* {"string_value" : 1} pair.
*
* - numeric values in the original are translated into a {"0" :
* value} dict.
*
* - FLEX_UNDEFINED values are handled by replacing them with the
* string contents of `undefined_string`.
*
* - image and datetime types are handled by calling
* process_image_value and process_datetime_value. These
* functions must either throw an exception, which propegates up,
* return any other flexible type (e.g. dict, list, vector, etc.),
* or return FLEX_UNDEFINED, in which case that value is ignored.
*
*/
GL_HOT flex_dict to_flat_dict(
const flexible_type& input,
const flex_string& separator,
const flex_string& undefined_string,
std::function<flexible_type(const flex_image&)> process_image_value,
std::function<flexible_type(const flex_date_time&)> process_datetime_value) {
////////////////////////////////////////////////////////////////////////////////
// Some utility functions used everywhere -- done here to keep
// things organized and make sure errors are processed correctly.
////////////////////////////////////////////////////////////////////////////////
/** Based on the input type, we do some processing.
*/
switch(input.get_type()) {
case flex_type_enum::DICT: {
bool need_to_flatten = false;
for(const auto& p : input.get<flex_dict>()) {
if(p.first.get_type() != flex_type_enum::STRING) {
need_to_flatten = true;
}
if(p.second.get_type() != flex_type_enum::FLOAT
&& p.second.get_type() != flex_type_enum::INTEGER) {
need_to_flatten = true;
}
if(need_to_flatten) {
break;
}
}
// If we don't need to flatten it, then don't.
if(!need_to_flatten) {
return input.get<flex_dict>();
} else {
break;
}
}
case flex_type_enum::LIST: {
// This will be flattened later on, as it could be arbitrarily
// recursive.
break;
}
case flex_type_enum::VECTOR: {
// Vectors are changed to a dictionary of {"0" : v[0], "1" : v[1], ...}.
const flex_vec& v = input.get<flex_vec>();
flex_dict _out(v.size());
for(size_t i = 0; i < v.size(); ++i) {
_out[i] = {get_index_key(i), v[i]};
}
return _out;
}
case flex_type_enum::STRING: {
return flex_dict{ {input, 1} };
}
case flex_type_enum::INTEGER:
case flex_type_enum::FLOAT: {
return flex_dict{ {get_index_key(0), input} };
}
case flex_type_enum::IMAGE: {
// This can recurse a maximum of once, as the return value of
// process_image_value cannot be an image or datetime type,
// and this is the only place we recurse.
return to_flat_dict(process_image_value(input),
separator, undefined_string,
process_image_value, process_datetime_value);
}
case flex_type_enum::DATETIME: {
// This can recurse a maximum of once, as the return value of
// process_datetime_value cannot be an image or datetime type,
// and this is the only place we recurse.
return to_flat_dict(process_datetime_value(input),
separator, undefined_string,
process_image_value, process_datetime_value);
}
case flex_type_enum::UNDEFINED: {
return flex_dict{ {undefined_string, 1} };
}
case flex_type_enum::ND_VECTOR: {
log_and_throw(std::string("Flexible type case currently unsupported: ND_VECTOR"));
ASSERT_UNREACHABLE();
}
default: {
log_and_throw(std::string("Flexible type case not recognized"));
ASSERT_UNREACHABLE();
}
}
////////////////////////////////////////////////////////////////////////////////
// Reserve the output container.
flex_dict out;
out.reserve(input.size());
// The current key.
flex_string key = "";
key.reserve(256);
_to_flat_dict_recursion(out, key, input,
separator, undefined_string,
process_image_value, process_datetime_value, 0);
return out;
}
////////////////////////////////////////////////////////////////////////////////
static std::function<flexible_type(const flex_image&)> _get_image_handler(
const std::string& image_policy) {
if(image_policy == "error") {
return [](const flex_image&) -> flexible_type {
log_and_throw("Image types are not allowed when flattening dictionaries.");
};
} else if (image_policy == "ignore") {
return [](const flex_image&) -> flexible_type {
return FLEX_UNDEFINED;
};
} else {
log_and_throw("At this time, only \"error\" and \"ignore\" are "
"implemented for handling of image types.");
return [](const flex_image&) -> flexible_type { return FLEX_UNDEFINED; };
}
}
static std::function<flexible_type(const flex_date_time&)> _get_datetime_handler(
const std::string& datetime_policy) {
if(datetime_policy == "error") {
return [](const flex_date_time&) -> flexible_type {
log_and_throw("Datetime types are not allowed when flattening dictionaries.");
};
} else if (datetime_policy == "ignore") {
return [](const flex_date_time&) -> flexible_type {
return FLEX_UNDEFINED;
};
} else {
log_and_throw("At this time, only \"error\" and \"ignore\" are "
"implemented for handling of datetime types.");
return [](const flex_date_time&) -> flexible_type { return FLEX_UNDEFINED; };
}
}
/** Flattens any types to a non-nested dictionary of (string key :
* numeric value) pairs. Each nested key is a concatenation of the
* keys in the separation with sep_char separating them. For
* example, if sep_char = ".", then
*
* {"a" : {"b" : 1}, "c" : 2}
*
* becomes
*
* {"a.b" : 1, "c" : 2}.
*
* - List and vector elements are handled by converting the index of
* the appropriate element to a string.
*
* - String values are handled by treating them as a single
* {"string_value" : 1} pair.
*
* - numeric values in the original are translated into a {"0" :
* value} dict.
*
* - FLEX_UNDEFINED values are handled by replacing them with the
* string contents of `undefined_string`.
*
* - image and datetime types are handled by calling
* process_image_value and process_datetime_value. These
* functions must either throw an exception, which propegates up,
* return any other flexible type (e.g. dict, list, vector, etc.),
* or return FLEX_UNDEFINED, in which case that value is ignored.
*
*/
EXPORT flex_dict to_flat_dict(const flexible_type& input,
const flex_string& separator,
const flex_string& undefined_string,
const std::string& image_policy,
const std::string& datetime_policy) {
return to_flat_dict(input, separator, undefined_string,
_get_image_handler(image_policy),
_get_datetime_handler(datetime_policy));
}
/** Performs dictionary flattening on an SArray.
*/
EXPORT gl_sarray to_sarray_of_flat_dictionaries(gl_sarray input,
const flex_string& sep,
const flex_string& undefined_string,
const std::string& image_policy,
const std::string& datetime_policy) {
auto image_handler = _get_image_handler(image_policy);
auto datetime_handler = _get_datetime_handler(datetime_policy);
std::function<flexible_type(const flexible_type& dt)> flatten_it
= [=](const flexible_type& x) -> flexible_type GL_GCC_ONLY(GL_HOT_FLATTEN) {
return to_flat_dict(x, sep, undefined_string, image_handler, datetime_handler);
};
return input.apply(flatten_it, flex_type_enum::DICT);
}
}
| 14,457 | 4,535 |
//=======================================================================
// Copyright (c) 2014-2020 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
/*!
* \file
* \brief dim_view expression implementation
*/
#pragma once
namespace etl {
/*!
* \brief View that shows one dimension of a matrix
* \tparam T The type of expression on which the view is made
* \tparam D The dimension to show
*/
template <typename T, size_t D>
struct dim_view {
static_assert(D == 1 || D == 2, "Invalid dimension");
using sub_type = T; ///< The sub type
using value_type = value_t<sub_type>; ///< The value contained in the expression
using memory_type = memory_t<sub_type>; ///< The memory acess type
using const_memory_type = const_memory_t<sub_type>; ///< The const memory access type
using return_type = return_helper<sub_type, decltype(std::declval<sub_type>()(0, 0))>; ///< The type returned by the view
using const_return_type = const_return_helper<sub_type, decltype(std::declval<sub_type>()(0, 0))>; ///< The const type return by the view
private:
T sub; ///< The Sub expression
const size_t i; ///< The index
friend struct etl_traits<dim_view>;
public:
/*!
* \brief Construct a new dim_view over the given sub expression
* \param sub The sub expression
* \param i The sub index
*/
dim_view(sub_type sub, size_t i) : sub(sub), i(i) {}
/*!
* \brief Returns the element at the given index
* \param j The index
* \return a reference to the element at the given index.
*/
const_return_type operator[](size_t j) const {
if (D == 1) {
return sub(i, j);
} else { //D == 2
return sub(j, i);
}
}
/*!
* \brief Returns the element at the given index
* \param j The index
* \return a reference to the element at the given index.
*/
return_type operator[](size_t j) {
if (D == 1) {
return sub(i, j);
} else { //D == 2
return sub(j, i);
}
}
/*!
* \brief Returns the value at the given index
* This function never has side effects.
* \param j The index
* \return the value at the given index.
*/
value_type read_flat(size_t j) const noexcept {
if (D == 1) {
return sub(i, j);
} else { //D == 2
return sub(j, i);
}
}
/*!
* \brief Returns the element at the given index
* \param j The index
* \return a reference to the element at the given index.
*/
const_return_type operator()(size_t j) const {
if (D == 1) {
return sub(i, j);
} else { //D == 2
return sub(j, i);
}
}
/*!
* \brief Returns the element at the given index
* \param j The index
* \return a reference to the element at the given index.
*/
return_type operator()(size_t j) {
if (D == 1) {
return sub(i, j);
} else { //D == 2
return sub(j, i);
}
}
/*!
* \brief Test if this expression aliases with the given expression
* \param rhs The other expression to test
* \return true if the two expressions aliases, false otherwise
*/
template <typename E>
bool alias(const E& rhs) const noexcept {
return sub.alias(rhs);
}
/*!
* \brief Returns a pointer to the first element in memory.
* \return a pointer tot the first element in memory.
*/
memory_type memory_start() noexcept {
static_assert(is_dma<T> && D == 1, "This expression does not have direct memory access");
return sub.memory_start() + i * subsize(sub);
}
/*!
* \brief Returns a pointer to the first element in memory.
* \return a pointer tot the first element in memory.
*/
const_memory_type memory_start() const noexcept {
static_assert(is_dma<T> && D == 1, "This expression does not have direct memory access");
return sub.memory_start() + i * subsize(sub);
}
/*!
* \brief Returns a pointer to the past-the-end element in memory.
* \return a pointer tot the past-the-end element in memory.
*/
memory_type memory_end() noexcept {
static_assert(is_dma<T> && D == 1, "This expression does not have direct memory access");
return sub.memory_start() + (i + 1) * subsize(sub);
}
/*!
* \brief Returns a pointer to the past-the-end element in memory.
* \return a pointer tot the past-the-end element in memory.
*/
const_memory_type memory_end() const noexcept {
static_assert(is_dma<T> && D == 1, "This expression does not have direct memory access");
return sub.memory_start() + (i + 1) * subsize(sub);
}
// Assignment functions
/*!
* \brief Assign to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_to(L&& lhs) const {
std_assign_evaluate(*this, lhs);
}
/*!
* \brief Add to the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_add_to(L&& lhs) const {
std_add_evaluate(*this, lhs);
}
/*!
* \brief Sub from the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_sub_to(L&& lhs) const {
std_sub_evaluate(*this, lhs);
}
/*!
* \brief Multiply the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_mul_to(L&& lhs) const {
std_mul_evaluate(*this, lhs);
}
/*!
* \brief Divide the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_div_to(L&& lhs) const {
std_div_evaluate(*this, lhs);
}
/*!
* \brief Modulo the given left-hand-side expression
* \param lhs The expression to which assign
*/
template <typename L>
void assign_mod_to(L&& lhs) const {
std_mod_evaluate(*this, lhs);
}
// Internals
/*!
* \brief Apply the given visitor to this expression and its descendants.
* \param visitor The visitor to apply
*/
void visit(detail::evaluator_visitor& visitor) const {
sub.visit(visitor);
}
/*!
* \brief Ensures that the GPU memory is allocated and that the GPU memory
* is up to date (to undefined value).
*/
void ensure_cpu_up_to_date() const {
// Need to ensure sub value
sub.ensure_cpu_up_to_date();
}
/*!
* \brief Copy back from the GPU to the expression memory if
* necessary.
*/
void ensure_gpu_up_to_date() const {
// Need to ensure both LHS and RHS
sub.ensure_gpu_up_to_date();
}
/*!
* \brief Print a representation of the view on the given stream
* \param os The output stream
* \param v The view to print
* \return the output stream
*/
friend std::ostream& operator<<(std::ostream& os, const dim_view& v) {
return os << "dim[" << D << "](" << v.sub << ", " << v.i << ")";
}
};
/*!
* \brief Specialization for dim_view
*/
template <typename T, size_t D>
struct etl_traits<etl::dim_view<T, D>> {
using expr_t = etl::dim_view<T, D>; ///< The expression type
using sub_expr_t = std::decay_t<T>; ///< The sub expression type
using value_type = typename etl_traits<sub_expr_t>::value_type; ///< The value type
static constexpr bool is_etl = true; ///< Indicates if the type is an ETL expression
static constexpr bool is_transformer = false; ///< Indicates if the type is a transformer
static constexpr bool is_view = true; ///< Indicates if the type is a view
static constexpr bool is_magic_view = false; ///< Indicates if the type is a magic view
static constexpr bool is_fast = etl_traits<sub_expr_t>::is_fast; ///< Indicates if the expression is fast
static constexpr bool is_linear = false; ///< Indicates if the expression is linear
static constexpr bool is_thread_safe = etl_traits<sub_expr_t>::is_thread_safe; ///< Indicates if the expression is thread safe
static constexpr bool is_value = false; ///< Indicates if the expression is of value type
static constexpr bool is_direct = etl_traits<sub_expr_t>::is_direct && D == 1; ///< Indicates if the expression has direct memory access
static constexpr bool is_generator = false; ///< Indicates if the expression is a generator
static constexpr bool is_padded = false; ///< Indicates if the expression is padded
static constexpr bool is_aligned = false; ///< Indicates if the expression is padded
static constexpr bool is_temporary = etl_traits<sub_expr_t>::is_temporary; ///< Indicates if the exxpression needs a evaluator visitor
static constexpr bool gpu_computable = false; ///< Indicates if the expression can be computed on GPU
static constexpr order storage_order = etl_traits<sub_expr_t>::storage_order; ///< The expression's storage order
/*!
* \brief Indicates if the expression is vectorizable using the
* given vector mode
* \tparam V The vector mode
*/
template <vector_mode_t V>
static constexpr bool vectorizable = false;
/*!
* \brief Returns the size of the given expression
* \param v The expression to get the size for
* \returns the size of the given expression
*/
static size_t size(const expr_t& v) {
if (D == 1) {
return etl_traits<sub_expr_t>::dim(v.sub, 1);
} else {
return etl_traits<sub_expr_t>::dim(v.sub, 0);
}
}
/*!
* \brief Returns the dth dimension of the given expression
* \param v The expression
* \param d The dimension to get
* \return The dth dimension of the given expression
*/
static size_t dim(const expr_t& v, [[maybe_unused]] size_t d) {
cpp_assert(d == 0, "Invalid dimension");
return size(v);
}
/*!
* \brief Returns the size of an expression of this fast type.
* \returns the size of an expression of this fast type.
*/
static constexpr size_t size() {
return D == 1 ? etl_traits<sub_expr_t>::template dim<1>() : etl_traits<sub_expr_t>::template dim<0>();
}
/*!
* \brief Returns the D2th dimension of an expression of this type
* \tparam D2 The dimension to get
* \return the D2th dimension of an expression of this type
*/
template <size_t D2>
static constexpr size_t dim() {
static_assert(D2 == 0, "Invalid dimension");
return size();
}
/*!
* \brief Returns the number of expressions for this type
* \return the number of dimensions of this type
*/
static constexpr size_t dimensions() {
return 1;
}
/*!
* \brief Estimate the complexity of computation
* \return An estimation of the complexity of the expression
*/
static constexpr int complexity() noexcept {
return -1;
}
};
} //end of namespace etl
| 12,208 | 3,577 |
#include "student.h"
#include <iostream>
using namespace std;
void Student::input (void) {
cout << "\n\nRoll No: ";
cin >> rollno;
cout << "Name: ";
cin.ignore();
cin.getline(name, 20);
cout << "MARKS" << endl;
cout << "Phy: "; cin >> marks[phy];
cout << "Chem: "; cin >> marks[chem];
cout << "Math: "; cin >> marks[math];
}
void Student::output (void) {
cout << "\n\nRoll No: " << rollno << endl;
cout << "Name: " << name << endl;
cout << "MARKS" << endl << "Phy: " << marks[phy] << endl
<< "Chem: " << marks[chem] << endl
<< "Math: " << marks[math];
}
float Student::totalMarks (void) {
return (marks[phy] + marks[chem] + marks[math]);
}
| 715 | 264 |
//
// Umbrela for the the Mu2e G4 world classes
//
// $Id: Mu2eUniverse.cc,v 1.2 2012/11/19 23:03:49 genser Exp $
// $Author: genser $
// $Date: 2012/11/19 23:03:49 $
//
// Original author Rob Kutschke
//
//
// C++ includes
#include <iostream>
#include <vector>
#include <iomanip>
// Framework includes
#include "art/Framework/Services/Registry/ServiceHandle.h"
#include "cetlib_except/exception.h"
// Mu2e includes
#include "G4Helper/inc/G4Helper.hh"
#include "Mu2eG4/inc/Mu2eUniverse.hh"
// G4 includes
#include "G4PhysicalVolumeStore.hh"
using namespace std;
namespace mu2e {
Mu2eUniverse::Mu2eUniverse():
_geom(*(art::ServiceHandle<GeometryService>())),
_config(_geom.config()),
_helper(&(*(art::ServiceHandle<G4Helper>())))
{} // beware of the order of initialization/declarations
Mu2eUniverse::~Mu2eUniverse(){
}
// Convert to base units for all of the items in the vector.
void Mu2eUniverse::setUnits( vector<double>& V, G4double unit ){
for ( vector<double>::iterator b=V.begin(), e=V.end();
b!=e; ++b){
*b *= unit;
}
}
// A helper function for debugging. Print a subset of the physical volume store.
void Mu2eUniverse::printPhys() {
G4PhysicalVolumeStore* pstore = G4PhysicalVolumeStore::GetInstance();
int n(0);
for ( std::vector<G4VPhysicalVolume*>::const_iterator i=pstore->begin(); i!=pstore->end(); i++){
cout << "Physical Volume: "
<< setw(5) << n++
<< (*i)->GetName()
<< endl;
if ( n > 25 ) break;
}
}
} // end namespace mu2e
| 1,573 | 591 |
#include "stdafx.h"
#include "KMath.h"
#include "Global.h"
#include "KNpcOrderList.h"
using namespace std;
BOOL KNpcOrderManager::Init()
{
BOOL bResult = false;
int nRetCode = false;
ITabFile* piTabFile = NULL;
char szFileName[MAX_PATH];
int nTableHeight = 0;
snprintf(szFileName, MAX_PATH, "%s/NpcOrder/%s", SETTING_DIR, "OrderList.tab");
szFileName[MAX_PATH - 1] = '\0';
piTabFile = g_OpenTabFile(szFileName);
if (!piTabFile)
{
KGLogPrintf(KGLOG_ERR, "[KNpcOrderManager] Failed to open tab file: \"%s\".\n", szFileName);
goto Exit0;
}
nTableHeight = piTabFile->GetHeight();
KGLOG_PROCESS_ERROR(nTableHeight >= 1);
for (int i = 0; i < nTableHeight - 1; ++i)
{
KORDER Order;
DWORD dwID = 0;
float fZoom = 0.0f;
nRetCode = piTabFile->GetInteger(2 + i, "ID", 0, (int*)&dwID);
KGLOG_PROCESS_ERROR(nRetCode == 1);
nRetCode = piTabFile->GetString(2 + i, "File", "", szFileName, MAX_PATH);
KGLOG_PROCESS_ERROR(nRetCode == 1);
nRetCode = piTabFile->GetFloat(2 + i, "Zoom", 0.0f, &fZoom);
KGLOG_PROCESS_ERROR(nRetCode == 1);
KGLOG_PROCESS_ERROR(fZoom != 0.0f);
nRetCode = LoadOrder(Order, szFileName, fZoom);
KGLOG_PROCESS_ERROR(nRetCode);
m_OrderList[dwID] = Order;
}
bResult = true;
Exit0:
if (!bResult)
{
m_OrderList.clear();
}
KG_COM_RELEASE(piTabFile);
return bResult;
}
void KNpcOrderManager::UnInit()
{
m_OrderList.clear();
}
const KORDER* KNpcOrderManager::GetOrder(DWORD dwID)
{
KORDER_LIST::iterator it = m_OrderList.find(dwID);
if (it == m_OrderList.end())
return NULL;
return &it->second;
}
BOOL KNpcOrderManager::LoadOrder(KORDER& rOrder, const char cszFileName[], float fZoom)
{
BOOL bResult = false;
int nRetCode = false;
ITabFile* piTabFile = NULL;
char szFullName[MAX_PATH];
int nTableHeight = 0;
snprintf(szFullName, MAX_PATH, "%s/NpcOrder/%s", SETTING_DIR, cszFileName);
szFullName[MAX_PATH - 1] = '\0';
piTabFile = g_OpenTabFile(szFullName);
if (!piTabFile)
{
KGLogPrintf(KGLOG_ERR, "[KNpcOrderManager] Failed to open tab file: \"%s\".\n", szFullName);
goto Exit0;
}
nTableHeight = piTabFile->GetHeight();
KGLOG_PROCESS_ERROR(nTableHeight > 1);
for (int i = 0; i < nTableHeight - 1; ++i)
{
int nIndex = 0;
float fRadius = 0.0f;
float fAngel = 0.0f;
KORDER_NODE Node;
nRetCode = piTabFile->GetInteger(2 + i, "Index", 0, &nIndex);
KG_PROCESS_ERROR(nRetCode == 1);
nRetCode = piTabFile->GetFloat(2 + i, "Radius", 0, &fRadius);
KG_PROCESS_ERROR(nRetCode == 1);
nRetCode = piTabFile->GetFloat(2 + i, "Angel", 0, &fAngel);
KG_PROCESS_ERROR(nRetCode == 1);
KG_PROCESS_ERROR(nIndex == i + 1);
Node.nRadius = (int)(fRadius * fZoom);
Node.nAngel = (int)(fAngel * DIRECTION_COUNT / (2 * SO3WORLD_PI));
if (Node.nAngel < 0)
{
Node.nAngel += DIRECTION_COUNT;
}
KGLOG_PROCESS_ERROR(Node.nAngel < DIRECTION_COUNT);
rOrder.push_back(Node);
}
bResult = true;
Exit0:
KG_COM_RELEASE(piTabFile);
return bResult;
}
| 3,570 | 1,378 |
#include "bimage.hh"
#include <math.h>
#include <fstream>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]){
BImage image(257,256) ;
image.clear(255,255,255) ;
image.text(10,10,"abc ABC 123 @$%& ][{}.,:") ; // fghijklmnopquvwxyz") ;
for(int i = 0 ; i < 16 ; i++) {
for(int j = 2 ; j < 8 ; j++)
cout << (char)(j*16+i) << "\t" ;
cout << endl ;
}
image.writeImage("a.bmp") ;
image.show() ;
//image.close() ;
return 0 ;
}
| 507 | 246 |
/********************************************************************
* COPYRIGHT:
* Copyright (C) 2001-2011 IBM, Inc. All Rights Reserved.
*
********************************************************************/
/********************************************************************************
*
* File dumpce.cpp
*
* Modification History:
* Name Date Description
* synwee May 31 2001 Creation
*
*********************************************************************************
*/
/**
* This program outputs the collation elements used for a requested tailoring.
*
* Usage:
* dumpce options... please check main function.
*/
#include <unicode/utypes.h>
#include <unicode/ucol.h>
#include <unicode/uloc.h>
#include <unicode/ucoleitr.h>
#include <unicode/uchar.h>
#include <unicode/uscript.h>
#include <unicode/utf16.h>
#include <unicode/putil.h>
#include <unicode/ustring.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "ucol_tok.h"
#include "cstring.h"
#include "uoptions.h"
#include "ucol_imp.h"
#include <unicode/ures.h>
#include <unicode/uniset.h>
#include <unicode/usetiter.h>
/**
* Command line option variables.
* These global variables are set according to the options specified on the
* command line by the user.
*/
static UOption options[]={
/* 00 */ UOPTION_HELP_H,
/* 01 */ UOPTION_HELP_QUESTION_MARK,
/* 02 */ {"locale", NULL, NULL, NULL, 'l', UOPT_REQUIRES_ARG, 0},
/* 03 */ {"serialize", NULL, NULL, NULL, 'z', UOPT_NO_ARG, 0},
/* 04 */ UOPTION_DESTDIR,
/* 05 */ UOPTION_SOURCEDIR,
/* 06 */ {"attribute", NULL, NULL, NULL, 'a', UOPT_REQUIRES_ARG, 0},
/* 07 */ {"rule", NULL, NULL, NULL, 'r', UOPT_REQUIRES_ARG, 0},
/* 08 */ {"normalization", NULL, NULL, NULL, 'n', UOPT_REQUIRES_ARG, 0},
/* 09 */ {"scripts", NULL, NULL, NULL, 't', UOPT_NO_ARG, 0},
/* 10 */ {"reducehan", NULL, NULL, NULL, 'e', UOPT_NO_ARG, 0},
/* 11 */ UOPTION_VERBOSE,
/* 12 */ {"wholescripts", NULL, NULL, NULL, 'W', UOPT_NO_ARG, 0}
};
/**
* Collator used in this program
*/
static UCollator *COLLATOR_;
/**
* Output strea, used in this program
*/
static FILE *OUTPUT_;
static UColAttributeValue ATTRIBUTE_[UCOL_ATTRIBUTE_COUNT] = {
UCOL_DEFAULT, UCOL_DEFAULT, UCOL_DEFAULT, UCOL_DEFAULT, UCOL_DEFAULT,
UCOL_DEFAULT, UCOL_DEFAULT, UCOL_DEFAULT,
};
typedef struct {
int value;
char *name;
} EnumNameValuePair;
static const EnumNameValuePair ATTRIBUTE_NAME_[] = {
{UCOL_FRENCH_COLLATION, "UCOL_FRENCH_COLLATION"},
{UCOL_ALTERNATE_HANDLING, "UCOL_ALTERNATE_HANDLING"},
{UCOL_CASE_FIRST, "UCOL_CASE_FIRST"},
{UCOL_CASE_LEVEL, "UCOL_CASE_LEVEL"},
{UCOL_NORMALIZATION_MODE,
"UCOL_NORMALIZATION_MODE|UCOL_DECOMPOSITION_MODE"},
{UCOL_STRENGTH, "UCOL_STRENGTH"},
{UCOL_HIRAGANA_QUATERNARY_MODE, "UCOL_HIRAGANA_QUATERNARY_MODE"},
{UCOL_NUMERIC_COLLATION, "UCOL_NUMERIC_COLLATION"},
NULL
};
static const EnumNameValuePair ATTRIBUTE_VALUE_[] = {
{UCOL_PRIMARY, "UCOL_PRIMARY"},
{UCOL_SECONDARY, "UCOL_SECONDARY"},
{UCOL_TERTIARY, "UCOL_TERTIARY|UCOL_DEFAULT_STRENGTH"},
{UCOL_QUATERNARY, "UCOL_QUATERNARY"},
{UCOL_IDENTICAL, "UCOL_IDENTICAL"},
{UCOL_OFF, "UCOL_OFF"},
{UCOL_ON, "UCOL_ON"},
{UCOL_SHIFTED, "UCOL_SHIFTED"},
{UCOL_NON_IGNORABLE, "UCOL_NON_IGNORABLE"},
{UCOL_LOWER_FIRST, "UCOL_LOWER_FIRST"},
{UCOL_UPPER_FIRST, "UCOL_UPPER_FIRST"},
NULL
};
typedef struct {
UChar ch[32];
int count; // number of codepoint
UBool tailored;
} ScriptElement;
/**
* Writes the hexadecimal of a null-terminated array of codepoints into a
* file
* @param f UFILE instance to store
* @param c codepoints array
*/
void serialize(FILE *f, const UChar *c)
{
UChar cp = *(c ++);
fprintf(f, " %04x", cp);
while (*c != 0) {
cp = *(c ++);
fprintf(f, " %04x", cp);
}
}
/**
* Writes the hexadecimal of a non-null-terminated array of codepoints into a
* file
* @param f UFILE instance to store
* @param c codepoints array
* @param l codepoints array length
*/
void serialize(FILE *f, const UChar *c, int l)
{
int count = 1;
UChar cp = *(c ++);
fprintf(f, " %04x", cp);
while (count < l) {
cp = *(c ++);
fprintf(f, " %04x", cp);
count ++;
}
}
/**
* Sets the iterator to the argument string and outputs the collation elements.
* @param f file output stream
* @param iter collation element iterator
*/
void serialize(FILE *f, UCollationElements *iter) {
UChar *codepoint = iter->iteratordata_.string;
// unlikely that sortkeys will be over this size
uint8_t sortkey[64];
uint8_t *psortkey = sortkey;
int sortkeylength = 0;
if (iter->iteratordata_.flags & UCOL_ITER_HASLEN) {
serialize(f, codepoint, iter->iteratordata_.endp - codepoint);
sortkeylength = ucol_getSortKey(iter->iteratordata_.coll, codepoint,
iter->iteratordata_.endp - codepoint, sortkey, 64);
}
else {
serialize(f, codepoint);
sortkeylength = ucol_getSortKey(iter->iteratordata_.coll, codepoint,
-1, sortkey, 64);
}
if (options[11].doesOccur) {
serialize(stdout, codepoint);
fprintf(stdout, "\n");
}
fprintf(f, "; ");
UErrorCode error = U_ZERO_ERROR;
uint32_t ce = ucol_next(iter, &error);
if (U_FAILURE(error)) {
fprintf(f, "Error retrieving collation elements\n");
return;
}
while (TRUE) {
fprintf(f, "[");
if (UCOL_PRIMARYORDER(ce) != 0) {
fprintf(f, "%04x", UCOL_PRIMARYORDER(ce));
}
fprintf(f, ",");
if (UCOL_SECONDARYORDER(ce) != 0) {
fprintf(f, " %02x", UCOL_SECONDARYORDER(ce));
}
fprintf(f, ",");
if (UCOL_TERTIARYORDER(ce) != 0) {
fprintf(f, " %02x", UCOL_TERTIARYORDER(ce));
}
fprintf(f, "] ");
ce = ucol_next(iter, &error);
if (ce == UCOL_NULLORDER) {
break;
}
if (U_FAILURE(error)) {
fprintf(stdout, "Error retrieving collation elements");
return;
}
}
if (sortkeylength > 64) {
fprintf(f, "Sortkey exceeds pre-allocated size");
}
fprintf(f, "[");
while (TRUE) {
fprintf(f, "%02x", *psortkey);
psortkey ++;
if ((*psortkey) == 0) {
break;
}
fprintf(f, " ");
}
fprintf(f, "]\n");
}
/**
* Serializes the contraction within the given argument rule
* @param f file output stream
* @param r rule
* @param rlen rule length
* @param contractionsonly flag to indicate if only contractions are to be
* output or all collation elements
* @param iter iterator to iterate over collation elements
*/
void serialize(FILE *f, UChar *rule, int rlen, UBool contractiononly,
UCollationElements *iter) {
const UChar *current = NULL;
uint32_t strength = 0;
uint32_t chOffset = 0;
uint32_t chLen = 0;
uint32_t exOffset = 0;
uint32_t exLen = 0;
uint32_t prefixOffset = 0;
uint32_t prefixLen = 0;
uint8_t specs = 0;
UBool rstart = TRUE;
UColTokenParser src;
UColOptionSet opts;
UParseError parseError;
UErrorCode error = U_ZERO_ERROR;
src.opts = &opts;
src.source = rule;
src.current = rule;
src.end = rule + rlen;
src.extraCurrent = src.end;
src.extraEnd = src.end + UCOL_TOK_EXTRA_RULE_SPACE_SIZE;
while ((current = ucol_tok_parseNextToken(&src, rstart, &parseError,
&error)) != NULL) {
chOffset = src.parsedToken.charsOffset;
chLen = src.parsedToken.charsLen;
// contractions handled here
if (!contractiononly || chLen > 1) {
ucol_setText(iter, rule + chOffset, chLen, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error setting text in iterator\n");
return;
}
serialize(f, iter);
}
rstart = FALSE;
}
}
/**
* Prints the attribute values in the argument collator into the output stream
* @param collator
*/
void outputAttribute(UCollator *collator, UErrorCode *error)
{
UColAttribute attribute = UCOL_FRENCH_COLLATION;
while (attribute < UCOL_ATTRIBUTE_COUNT) {
int count = 0;
while (TRUE) {
// getting attribute name
if (ATTRIBUTE_NAME_[count].value == attribute) {
fprintf(OUTPUT_, "%s = ", ATTRIBUTE_NAME_[count].name);
break;
}
count ++;
}
count = 0;
int attributeval = ucol_getAttribute(collator, attribute, error);
if (U_FAILURE(*error)) {
fprintf(stdout, "Failure in reading collator attribute\n");
return;
}
while (TRUE) {
// getting attribute value
if (ATTRIBUTE_VALUE_[count].value == attributeval) {
fprintf(OUTPUT_, "%s\n", ATTRIBUTE_VALUE_[count].name);
break;
}
count ++;
}
attribute = (UColAttribute)(attribute + 1);
}
}
/**
* Prints the normalization mode in the argument collator into the output stream
* @param collator
*/
void outputNormalization(UCollator *collator)
{
UErrorCode status = U_ZERO_ERROR;
int normmode = ucol_getAttribute(collator, UCOL_NORMALIZATION_MODE, &status);
int count = 0;
while (TRUE) {
// getting attribute name
if (ATTRIBUTE_VALUE_[count].value == normmode) {
break;
}
count ++;
}
fprintf(OUTPUT_, "NORMALIZATION MODE = %s\n",
ATTRIBUTE_VALUE_[count].name);
}
/**
* Output the collation element belonging to the locale into a file
* @param locale string
* @param fullrules flag to indicate if only tailored collation elements are to
* be output or all collation elements
*/
void serialize(const char *locale, UBool tailoredonly) {
UErrorCode error = U_ZERO_ERROR;
UChar str[128];
int strlen = 0;
fprintf(OUTPUT_, "# This file contains the serialized collation elements\n");
fprintf(OUTPUT_, "# as of the collation version indicated below.\n");
fprintf(OUTPUT_, "# Data format: xxxx xxxx..; [yyyy, yy, yy] [yyyy, yy, yy] ... [yyyy, yy, yy] [zz zz..\n");
fprintf(OUTPUT_, "# where xxxx are codepoints in hexadecimals,\n");
fprintf(OUTPUT_, "# yyyyyyyy are the corresponding\n");
fprintf(OUTPUT_, "# collation elements in hexadecimals\n");
fprintf(OUTPUT_, "# and zz are the sortkey values in hexadecimals\n");
fprintf(OUTPUT_, "\n# Collator information\n");
fprintf(OUTPUT_, "\nLocale: %s\n", locale);
fprintf(stdout, "Locale: %s\n", locale);
UVersionInfo version;
ucol_getVersion(COLLATOR_, version);
fprintf(OUTPUT_, "Version number: %d.%d.%d.%d\n",
version[0], version[1], version[2], version[3]);
outputAttribute(COLLATOR_, &error);
outputNormalization(COLLATOR_);
UCollationElements *iter = ucol_openElements(COLLATOR_, str, strlen,
&error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error creating iterator\n");
return;
}
if (!tailoredonly) {
fprintf(OUTPUT_, "\n# Range of unicode characters\n\n");
UChar32 codepoint = 0;
while (codepoint <= UCHAR_MAX_VALUE) {
if (u_isdefined(codepoint)) {
strlen = 0;
UTF16_APPEND_CHAR_UNSAFE(str, strlen, codepoint);
str[strlen] = 0;
ucol_setText(iter, str, strlen, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error setting text in iterator\n");
return;
}
serialize(OUTPUT_, iter);
}
codepoint ++;
}
}
UChar ucarules[0x10000];
UChar *rules;
int32_t rulelength = 0;
rules = ucarules;
if (tailoredonly) {
int32_t rulelength = 0;
const UChar *temp = ucol_getRules(COLLATOR_, &rulelength);
if (rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE > 0x10000) {
rules = (UChar *)malloc(sizeof(UChar) *
(rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE));
}
memcpy(rules, temp, rulelength * sizeof(UChar));
rules[rulelength] = 0;
fprintf(OUTPUT_, "\n# Tailorings\n\n");
serialize(OUTPUT_, rules, rulelength, FALSE, iter);
if (rules != ucarules) {
free(rules);
}
}
else {
rulelength = ucol_getRulesEx(COLLATOR_, UCOL_FULL_RULES, ucarules,
0x10000);
if (rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE > 0x10000) {
rules = (UChar *)malloc(sizeof(UChar) *
(rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE));
rulelength = ucol_getRulesEx(COLLATOR_, UCOL_FULL_RULES, rules,
rulelength);
}
fprintf(OUTPUT_, "\n# Contractions\n\n");
serialize(OUTPUT_, rules, rulelength, TRUE, iter);
if (rules != ucarules) {
free(rules);
}
}
ucol_closeElements(iter);
}
/**
* Sets the collator with the attribute values
* @param collator
* @param error status
*/
void setAttributes(UCollator *collator, UErrorCode *error)
{
int count = 0;
while (count < UCOL_ATTRIBUTE_COUNT) {
if (ATTRIBUTE_[count] != UCOL_DEFAULT) {
ucol_setAttribute(collator, (UColAttribute)count,
ATTRIBUTE_[count], error);
if (U_FAILURE(*error)) {
return;
}
}
count ++;
}
}
/**
* Appends directory path with an ending seperator if necessary.
* @param path with enough space to append one seperator
* @return new directory path length
*/
int appendDirSeparator(char *dir)
{
int dirlength = strlen(dir);
char dirending = dir[dirlength - 1];
if (dirending != U_FILE_SEP_CHAR) {
dir[dirlength] = U_FILE_SEP_CHAR;
dir[dirlength + 1] = 0;
return dirlength + 1;
}
return dirlength;
}
/**
* Output the collation element into a file
*/
void serialize() {
char filename[128];
int dirlength = 0;
if (options[4].doesOccur) {
strcpy(filename, options[4].value);
dirlength = appendDirSeparator(filename);
}
if (options[2].doesOccur) {
const char *locale = (char *)options[2].value;
int32_t localeindex = 0;
if (strcmp(locale, "all") == 0) {
if (options[4].doesOccur) {
strcat(filename, "UCA.txt");
OUTPUT_ = fopen(filename, "w");
if (OUTPUT_ == NULL) {
fprintf(stdout, "Cannot open file:%s\n", filename);
return;
}
}
fprintf(stdout, "UCA\n");
UErrorCode error = U_ZERO_ERROR;
COLLATOR_ = ucol_open("en_US", &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Collator creation failed:");
fprintf(stdout, u_errorName(error));
goto CLOSEUCA;
return;
}
setAttributes(COLLATOR_, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Collator attribute setting failed:");
fprintf(stdout, u_errorName(error));
goto CLOSEUCA;
return;
}
serialize("UCA", FALSE);
CLOSEUCA :
if (options[4].doesOccur) {
filename[dirlength] = 0;
fclose(OUTPUT_);
}
ucol_close(COLLATOR_);
localeindex = ucol_countAvailable() - 1;
fprintf(stdout, "Number of locales: %d\n", localeindex + 1);
locale = ucol_getAvailable(localeindex);
}
while (TRUE) {
UErrorCode error = U_ZERO_ERROR;
COLLATOR_ = ucol_open(locale, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Collator creation failed:");
fprintf(stdout, u_errorName(error));
goto CLOSETAILOR;
return;
}
setAttributes(COLLATOR_, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Collator attribute setting failed:");
fprintf(stdout, u_errorName(error));
goto CLOSETAILOR;
return;
}
if (options[4].doesOccur) {
strcat(filename, locale);
strcat(filename, ".txt");
OUTPUT_ = fopen(filename, "w");
if (OUTPUT_ == NULL) {
fprintf(stdout, "Cannot open file:%s\n", filename);
return;
}
}
if (options[3].doesOccur) {
serialize(locale, TRUE);
}
ucol_close(COLLATOR_);
CLOSETAILOR :
if (options[4].doesOccur) {
filename[dirlength] = 0;
fclose(OUTPUT_);
}
localeindex --;
if (localeindex < 0) {
break;
}
locale = ucol_getAvailable(localeindex);
}
}
if (options[7].doesOccur) {
char inputfilename[128] = "";
// rules are to be used
if (options[5].doesOccur) {
strcpy(inputfilename, options[5].value);
appendDirSeparator(inputfilename);
}
strcat(inputfilename, options[7].value);
FILE *input = fopen(inputfilename, "r");
if (input == NULL) {
fprintf(stdout, "Cannot open file:%s\n", filename);
return;
}
char s[1024];
UChar rule[1024];
UChar *prule = rule;
int size = 1024;
// synwee TODO: make this part dynamic
while (fscanf(input, "%[^\n]s", s) != EOF) {
size -= u_unescape(s, prule, size);
prule = prule + u_strlen(prule);
}
fclose(input);
if (options[4].doesOccur) {
strcat(filename, "Rules.txt");
OUTPUT_ = fopen(filename, "w");
if (OUTPUT_ == NULL) {
fprintf(stdout, "Cannot open file:%s\n", filename);
return;
}
}
fprintf(stdout, "Rules\n");
UErrorCode error = U_ZERO_ERROR;
UParseError parseError;
COLLATOR_ = ucol_openRules(rule, u_strlen(rule), UCOL_DEFAULT,
UCOL_DEFAULT_STRENGTH, &parseError, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Collator creation failed:");
fprintf(stdout, u_errorName(error));
goto CLOSERULES;
return;
}
setAttributes(COLLATOR_, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Collator attribute setting failed:");
fprintf(stdout, u_errorName(error));
goto CLOSERULES;
return;
}
serialize("Rule-based", TRUE);
ucol_close(COLLATOR_);
CLOSERULES :
if (options[4].doesOccur) {
filename[dirlength] = 0;
fclose(OUTPUT_);
}
}
}
/**
* Parse for enum values.
* Note this only works for positive enum values.
* @param enumarray array containing names of the enum values in string and
* their corresponding value.
* declared enum value.
* @param str string to be parsed
* @return corresponding integer enum value or -1 if value is not found.
*/
int parseEnums(const EnumNameValuePair enumarray[], const char *str)
{
const char *enumname = enumarray[0].name;
int result = atoi(str);
if (result == 0 && str[0] != '0') {
while (strcmp(enumname, str) != 0) {
// checking for multiple enum names sharing the same values
enumname = strstr(enumname, str);
if (enumname != NULL) {
int size = strchr(enumname, '|') - enumname;
if (size < 0) {
size = strlen(enumname);
}
if (size == (int)strlen(str)) {
return enumarray[result].value;
}
}
result ++;
if (&(enumarray[result]) == NULL) {
return -1;
}
enumname = enumarray[result].name;
}
}
return -1;
}
/**
* Parser for attribute name value pair
*/
void parseAttributes() {
char str[32];
const char *pname = options[6].value;
const char *pend = options[6].value + strlen(options[6].value);
const char *pvalue;
while (pname < pend) {
pvalue = strchr(pname, '=');
if (pvalue == NULL) {
fprintf(stdout,
"No matching value found for attribute argument %s\n",
pname);
return;
}
int count = pvalue - pname;
strncpy(str, pname, count);
str[count] = 0;
int name = parseEnums(ATTRIBUTE_NAME_, str);
if (name == -1) {
fprintf(stdout, "Attribute name not found: %s\n", str);
return;
}
pvalue ++;
// getting corresponding enum value
pname = strchr(pvalue, ',');
if (pname == NULL) {
pname = pend;
}
count = pname - pvalue;
strncpy(str, pvalue, count);
str[count] = 0;
int value = parseEnums(ATTRIBUTE_VALUE_, str);
if (value == -1) {
fprintf(stdout, "Attribute value not found: %s\n", str);
return;
}
ATTRIBUTE_[name] = (UColAttributeValue)value;
pname ++;
}
}
/**
* Checks if the locale argument is a base language
* @param locale to be checked
* @return TRUE if it is a base language
*/
inline UBool checkLocaleForLanguage(const char *locale)
{
return strlen(locale) <= 2;
}
/**
* Converts a UChar array into its string form "xxxx xxxx"
* @param ch array of UChar characters
* @param count number of UChar characters
*/
void outputUChar(UChar ch[], int count)
{
for (int i = 0; i < count; i ++) {
fprintf(OUTPUT_, "%04X ", ch[i]);
}
}
/**
* If it is a primary difference returns -1 or 1.
* If it is a secondary difference returns -2 or 2.
* If it is a tertiary difference returns -3 or 3.
* If equals returns 0.
*/
int compareSortKey(const void *elem1, const void *elem2)
{
// compare the 2 script element sort key
UChar *ch1 = ((ScriptElement *)elem1)->ch;
UChar *ch2 = ((ScriptElement *)elem2)->ch;
int size1 = ((ScriptElement *)elem1)->count;
int size2 = ((ScriptElement *)elem2)->count;
UErrorCode error = U_ZERO_ERROR;
ucol_setStrength(COLLATOR_, UCOL_PRIMARY);
int result = ucol_strcoll(COLLATOR_, ch1, size1, ch2, size2);
if (result == 0) {
ucol_setStrength(COLLATOR_, UCOL_SECONDARY);
result = ucol_strcoll(COLLATOR_, ch1, size1, ch2, size2);
if (result == 0) {
ucol_setStrength(COLLATOR_, UCOL_TERTIARY);
result = ucol_strcoll(COLLATOR_, ch1, size1, ch2, size2);
if (result < 0) {
return -3;
}
if (result > 0) {
return 3;
}
}
if (result < 0) {
return -2;
}
if (result > 0) {
return 2;
}
}
return result;
}
/**
* Output serialized script elements
* @param element the element to output
* @param compare the comparison with the previous element
* @param expansion flags TRUE if element has an expansion
*/
void outputScriptElem(ScriptElement &element, int compare, UBool expansion)
{
switch (compare) {
case 0:
if (expansion) {
fprintf(OUTPUT_, "<tr><td class='eq' title='[");
}
else {
fprintf(OUTPUT_, "<tr><td class='q' title='[");
}
break;
case -1:
if (expansion) {
fprintf(OUTPUT_, "<tr><td class='ep' title='[");
}
else {
fprintf(OUTPUT_, "<tr><td class='p' title='[");
}
break;
case -2:
if (expansion) {
fprintf(OUTPUT_, "<tr><td class='es' title='[");
}
else {
fprintf(OUTPUT_, "<tr><td class='s' title='[");
}
break;
default:
if (expansion) {
fprintf(OUTPUT_, "<tr><td class='et' title='[");
}
else {
fprintf(OUTPUT_, "<tr><td class='t' title='[");
}
}
uint8_t sortkey[32];
ucol_setStrength(COLLATOR_, UCOL_TERTIARY);
ucol_getSortKey(COLLATOR_, element.ch, element.count, sortkey, 32);
int i = 0;
while (sortkey[i] != 0) {
if (sortkey[i] == 1) {
fprintf(OUTPUT_, " | ");
}
else {
fprintf(OUTPUT_, "%02x", sortkey[i]);
}
i ++;
}
fprintf(OUTPUT_, "]'>");
UErrorCode error = U_ZERO_ERROR;
char utf8[64];
UChar nfc[32];
int32_t length = unorm_normalize(element.ch, element.count, UNORM_NFC, 0, nfc,
32, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error normalizing contractions to NFC\n");
}
u_strToUTF8(utf8, 64, &length, nfc, length, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error converting UChar to utf8\n");
return;
}
fprintf(OUTPUT_, "%s<br>", utf8);
fprintf(OUTPUT_, "<tt>");
outputUChar(element.ch, element.count);
if (compare == 0) {
fprintf(OUTPUT_, "</tt></td><td> </td><td> </td><td> </td><td>Q</td><td>");
}
else if (compare == -1) {
fprintf(OUTPUT_, "</tt></td><td>P</td><td> </td><td> </td><td> </td><td>");
}
else if (compare == -2) {
fprintf(OUTPUT_, "</tt></td><td> </td><td>S</td><td> </td><td> </td><td>");
}
else if (compare == -3) {
fprintf(OUTPUT_, "</tt></td><td> </td><td> </td><td>T</td><td> </td><td>");
}
i = 0;
while (i < element.count) {
char str[128];
UChar32 codepoint;
UTF_NEXT_CHAR(element.ch, i, element.count, codepoint);
int32_t temp = u_charName(codepoint, U_UNICODE_CHAR_NAME, str, 128,
&error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error getting character name\n");
return;
}
if (element.tailored) {
fprintf(OUTPUT_, "<b>");
}
fprintf(OUTPUT_, "%s", str);
if (element.tailored) {
fprintf(OUTPUT_, " *</b>");
}
if (i < element.count) {
fprintf(OUTPUT_, "<br>\n");
}
}
fprintf(OUTPUT_, "</td></tr>\n");
}
/**
* Checks if codepoint belongs to scripts
* @param script list
* @param scriptcount number of scripts
* @param codepoint to test
* @return TRUE if codepoint belongs to scripts
*/
UBool checkInScripts(UScriptCode script[], int scriptcount,
UChar32 codepoint)
{
UErrorCode error = U_ZERO_ERROR;
for (int i = 0; i < scriptcount; i ++) {
if (script[i] == USCRIPT_HAN && options[10].doesOccur) {
if ((codepoint >= 0x2E80 && codepoint <= 0x2EE4) ||
(codepoint >= 0x2A672 && codepoint <= 0x2A6D6)) {
// reduce han
return TRUE;
}
}
else if (uscript_getScript(codepoint, &error) == script[i]) {
return TRUE;
}
if (U_FAILURE(error)) {
fprintf(stdout, "Error checking character in scripts\n");
return FALSE;
}
}
return FALSE;
}
/**
* Checks if the set of codepoints belongs to the script
* @param script list
* @param scriptcount number of scripts
* @param scriptelem
* @return TRUE if all codepoints belongs to the script
*/
inline UBool checkInScripts(UScriptCode script[], int scriptcount,
ScriptElement scriptelem)
{
int i = 0;
while (i < scriptelem.count) {
UChar32 codepoint;
UTF_NEXT_CHAR(scriptelem.ch, i, scriptelem.count, codepoint);
UErrorCode error = U_ZERO_ERROR;
if (checkInScripts(script, scriptcount, codepoint)) {
return TRUE;
}
}
return FALSE;
}
/**
* Gets the script elements and contractions belonging to the script
* @param elems output list
* @param locale locale
* @return number of script elements
* Add by Richard
*/
int getScriptElementsFromExemplars(ScriptElement scriptelem[], const char* locale) {
UErrorCode error = U_ZERO_ERROR;
UChar32 codepoint = 0;
UResourceBundle* ures = ures_open(NULL, locale, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Can not find resource bundle for locale: %s\n", locale);
return -1;
}
int32_t length;
const UChar* exemplarChars = ures_getStringByKey(ures, "ExemplarCharacters", &length, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Can not find ExemplarCharacters in resource bundle\n");
return -1;
}
UChar* upperChars = new UChar[length * 2];
if (upperChars == 0) {
fprintf(stdout, "Memory error\n");
return -1;
}
int32_t destLength = u_strToUpper(upperChars, length * 2, exemplarChars, -1, locale, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error when u_strToUpper() \n");
return -1;
}
UChar* pattern = new UChar[length + destLength + 10];
UChar left[2] = {0x005b, 0x0};
UChar right[2] = {0x005d, 0x0};
pattern = u_strcpy(pattern, left);
pattern = u_strcat(pattern, exemplarChars);
pattern = u_strcat(pattern, upperChars);
pattern = u_strcat(pattern, right);
UnicodeSet * uniset = new UnicodeSet(UnicodeString(pattern), error);
if (U_FAILURE(error)) {
fprintf(stdout, "Can not open USet \n");
return -1;
}
UnicodeSetIterator* usetiter = new UnicodeSetIterator(*uniset);
int32_t count = 0;
while (usetiter -> next()) {
if (usetiter -> isString()) {
UnicodeString strItem = usetiter -> getString();
scriptelem[count].count = 0;
for (int i = 0; i < strItem.length(); i++) {
codepoint = strItem.char32At(i);
UTF16_APPEND_CHAR_UNSAFE(scriptelem[count].ch, scriptelem[count].count, codepoint);
scriptelem[count].tailored = FALSE;
}
} else {
codepoint = usetiter -> getCodepoint();
scriptelem[count].count = 0;
UTF16_APPEND_CHAR_UNSAFE(scriptelem[count].ch, scriptelem[count].count, codepoint);
scriptelem[count].tailored = FALSE;
}
delete []pattern;
count++;
}
delete []pattern;
return count;
}
/**
* Gets the script elements and contractions belonging to the script
* @param script list
* @param scriptcount number of scripts
* @param elems output list
* @return number of script elements
*/
int getScriptElements(UScriptCode script[], int scriptcount,
ScriptElement scriptelem[])
{
UErrorCode error = U_ZERO_ERROR;
UChar32 codepoint = 0;
int count = 0;
while (codepoint <= UCHAR_MAX_VALUE) {
if (checkInScripts(script, scriptcount, codepoint)) {
scriptelem[count].count = 0;
UTF16_APPEND_CHAR_UNSAFE(scriptelem[count].ch,
scriptelem[count].count, codepoint);
scriptelem[count].tailored = FALSE;
count ++;
}
if (U_FAILURE(error)) {
fprintf(stdout, "Error determining codepoint in script\n");
return -1;
}
codepoint ++;
}
const UChar *current = NULL;
uint32_t strength = 0;
uint32_t chOffset = 0;
uint32_t chLen = 0;
uint32_t exOffset = 0;
uint32_t exLen = 0;
uint32_t prefixOffset = 0;
uint32_t prefixLen = 0;
uint8_t specs = 0;
UBool rstart = TRUE;
UColTokenParser src;
UColOptionSet opts;
UParseError parseError;
int32_t rulelength = ucol_getRulesEx(COLLATOR_, UCOL_FULL_RULES, NULL, 0);
src.source = (UChar *)malloc(sizeof(UChar) *
(rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE));
rulelength = ucol_getRulesEx(COLLATOR_, UCOL_FULL_RULES, src.source,
rulelength);
src.current = src.source;
src.end = src.source + rulelength;
src.extraCurrent = src.end;
src.extraEnd = src.end + UCOL_TOK_EXTRA_RULE_SPACE_SIZE;
src.opts = &opts;
/*
ucol_tok_parseNextToken(&src, &strength, &chOffset,
&chLen, &exOffset, &exLen,
&prefixOffset, &prefixLen,
&specs, rstart, &parseError,
&error)
*/
while ((current = ucol_tok_parseNextToken(&src, rstart, &parseError,
&error)) != NULL) {
// contractions handled here
if (chLen > 1) {
u_strncpy(scriptelem[count].ch, src.source + chOffset, chLen);
scriptelem[count].count = chLen;
if (checkInScripts(script, scriptcount, scriptelem[count])) {
scriptelem[count].tailored = FALSE;
count ++;
}
}
rstart = FALSE;
}
if (U_FAILURE(error)) {
fprintf(stdout, "Error parsing rules: %s\n", u_errorName(error));
}
// rule might have been reallocated, so delete this instead
free(src.source);
return count;
}
int compareCodepoints(const void *elem1, const void *elem2)
{
UChar *ch1 = ((ScriptElement *)elem1)->ch; // key
UChar *ch2 = ((ScriptElement *)elem2)->ch;
ch1[((ScriptElement *)elem1)->count] = 0;
ch2[((ScriptElement *)elem2)->count] = 0;
// compare the 2 codepoints
return u_strcmp(ch1, ch2);
}
UBool hasSubNFD(ScriptElement &se, ScriptElement &key)
{
UChar *ch1 = se.ch;
UChar *ch2 = key.ch; // key
ch1[se.count] = 0;
ch2[key.count] = 0;
// compare the 2 codepoints
if (u_strstr(ch1, ch2) != NULL) {
return TRUE;
}
// check the decomposition
UChar norm[32];
UErrorCode error = U_ZERO_ERROR;
int size = unorm_normalize(ch1, se.count, UNORM_NFD, 0, norm, 32,
&error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error normalizing\n");
}
if (u_strstr(norm, ch2) != NULL) {
return TRUE;
}
return FALSE;
}
/**
* Marks tailored elements
* @param script list
* @param scriptcount number of scripts
* @param scriptelem script element list
* @param scriptelemlength size of the script element list
*/
void markTailored(UScriptCode script[], int scriptcount,
ScriptElement scriptelem[], int scriptelemlength)
{
int32_t rulelength;
const UChar *rule = ucol_getRules(COLLATOR_, &rulelength);
const UChar *current = NULL;
uint32_t strength = 0;
uint32_t chOffset = 0;
uint32_t chLen = 0;
uint32_t exOffset = 0;
uint32_t exLen = 0;
uint32_t prefixOffset = 0;
uint32_t prefixLen = 0;
uint8_t specs = 0;
UBool rstart = TRUE;
UColTokenParser src;
UColOptionSet opts;
UParseError parseError;
src.opts = &opts;
src.source = (UChar *)malloc(
(rulelength + UCOL_TOK_EXTRA_RULE_SPACE_SIZE) * sizeof(UChar));
memcpy(src.source, rule, rulelength * sizeof(UChar));
src.current = src.source;
src.end = (UChar *)src.source + rulelength;
src.extraCurrent = src.end;
src.extraEnd = src.end + UCOL_TOK_EXTRA_RULE_SPACE_SIZE;
UErrorCode error = U_ZERO_ERROR;
while ((current = ucol_tok_parseNextToken(&src, rstart, &parseError,
&error)) != NULL) {
if (chLen >= 1 && strength != UCOL_TOK_RESET) {
// skipping the reset characters and non useful stuff.
ScriptElement se;
u_strncpy(se.ch, src.source + chOffset, chLen);
se.count = chLen;
if (checkInScripts(script, scriptcount, se)) {
/*
ScriptElement *tse = (ScriptElement *)bsearch(&se, scriptelem,
scriptelemlength,
sizeof(ScriptElement),
compareCodepoints);
*/
for (int i = 0; i < scriptelemlength; i ++) {
if (!scriptelem[i].tailored &&
hasSubNFD(scriptelem[i], se)) {
scriptelem[i].tailored = TRUE;
}
}
}
}
rstart = FALSE;
}
free(src.source);
if (U_FAILURE(error)) {
fprintf(stdout, "Error parsing rules\n");
}
}
/**
* Checks if the collation iterator has more than 1 collation element
* @parem coleiter collation element iterator
* @return TRUE if collation iterator has more than 1 collation element
*/
UBool hasExpansions(UCollationElements *coleiter)
{
UErrorCode error = U_ZERO_ERROR;
int32_t ce = ucol_next(coleiter, &error);
int count = 0;
if (U_FAILURE(error)) {
fprintf(stdout, "Error getting next collation element\n");
}
while (ce != UCOL_NULLORDER) {
if ((UCOL_PRIMARYORDER(ce) != 0) && !isContinuation(ce)) {
count ++;
if (count == 2) {
return TRUE;
}
}
ce = ucol_next(coleiter, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error getting next collation element\n");
}
}
return FALSE;
}
/**
* Prints the footer for index.html
* @param file output file
*/
void outputHTMLFooter()
{
fprintf(OUTPUT_, "</table>\n");
fprintf(OUTPUT_, "</body>\n");
fprintf(OUTPUT_, "</html>\n");
}
/**
* Serialize the codepoints from start to end into an html file.
* Arranging them into ascending collation order.
* @param script code list
* @param scriptcount number of scripts
*/
//void serializeScripts(UScriptCode script[], int scriptcount)
//Richard
void serializeScripts(UScriptCode script[], int scriptcount, const char* locale = NULL)
{
UErrorCode error = U_ZERO_ERROR;
ScriptElement *scriptelem =
(ScriptElement *)malloc(sizeof(ScriptElement) * 0x20000);
if (scriptelem == NULL) {
fprintf(stdout, "Memory error\n");
return;
}
int count = 0;
if(locale) {
count = getScriptElementsFromExemplars(scriptelem, locale);
} else {
count = getScriptElements(script, scriptcount, scriptelem);
}
// Sort script elements using Quicksort algorithm:
qsort(scriptelem, count, sizeof(ScriptElement), compareCodepoints);
markTailored(script, scriptcount, scriptelem, count);
// Sort script elements using Quicksort algorithm:
qsort(scriptelem, count, sizeof(ScriptElement), compareSortKey);
UCollationElements* coleiter = ucol_openElements(COLLATOR_,
scriptelem[0].ch,
scriptelem[0].count,
&error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error creating collation element iterator\n");
return;
}
outputScriptElem(scriptelem[0], -1, hasExpansions(coleiter));
for (int i = 0; i < count - 1; i ++) {
ucol_setText(coleiter, scriptelem[i + 1].ch, scriptelem[i + 1].count,
&error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error setting text in collation element iterator\n");
return;
}
outputScriptElem(scriptelem[i + 1],
compareSortKey(scriptelem + i, scriptelem + i + 1),
hasExpansions(coleiter));
}
free(scriptelem);
outputHTMLFooter();
}
/**
* Prints the header for the html
* @param locale name
* @param script
* @param scriptcount number of scripts
*/
void outputHTMLHeader(const char *locale, UScriptCode script[],
int scriptcount)
{
fprintf(OUTPUT_, "<html>\n");
fprintf(OUTPUT_, "<head>\n");
fprintf(OUTPUT_, "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n");
fprintf(OUTPUT_, "<meta http-equiv=\"Content-Language\" content=\"en-us\">\n");
fprintf(OUTPUT_, "<link rel=\"stylesheet\" href=\"charts.css\" type=\"text/css\">\n");
fprintf(OUTPUT_, "<title>ICU Collation charts</title>\n");
fprintf(OUTPUT_, "<base target=\"main\">\n");
fprintf(OUTPUT_, "</head>\n");
fprintf(OUTPUT_, "<body bgcolor=#FFFFFF>\n");
fprintf(OUTPUT_, "<!--\n");
fprintf(OUTPUT_, "This file contains sorted characters in ascending order according to the locale stated\n");
fprintf(OUTPUT_, "If the character is in red, it is tailored in the collation rules.\n");
fprintf(OUTPUT_, "Background colours have certain meanings:\n");
fprintf(OUTPUT_, "White - equals the previous character\n");
fprintf(OUTPUT_, "dark blue - primary greater than the previous character\n");
fprintf(OUTPUT_, "blue - secondary greater than the previous character\n");
fprintf(OUTPUT_, "light blue - tertiary greater than the previous character\n");
fprintf(OUTPUT_, "--!>\n");
fprintf(OUTPUT_, "<table border=0>\n");
UChar displayname[64];
UErrorCode error = U_ZERO_ERROR;
int32_t size = uloc_getDisplayName(locale, "en_US", displayname, 64, &error);
char utf8displayname[128];
if (U_FAILURE(error)) {
utf8displayname[0] = 0;
}
else {
int32_t utf8size = 0;
u_strToUTF8(utf8displayname, 128, &utf8size, displayname, size, &error);
}
fprintf(OUTPUT_, "<tr><th>Locale</th><td class='noborder'>%s</td></tr>\n", utf8displayname);
fprintf(OUTPUT_, "<tr><th>Script(s)</th>");
fprintf(OUTPUT_, "<td class='noborder'>");
for (int i = 0; i < scriptcount; i ++) {
fprintf(OUTPUT_, "%s", uscript_getName(script[i]));
if (i + 1 != scriptcount) {
fprintf(OUTPUT_, ", ");
}
}
fprintf(OUTPUT_, "</td></tr>\n");
fprintf(OUTPUT_, "<tr><th>Rules</th><td class='noborder'><a href=\"http://dev.icu-project.org/cgi-bin/viewcvs.cgi/*checkout*/icu/source/data/coll/%s.txt\">%s.txt</a></td></tr>\n", locale, locale);
UVersionInfo version;
ucol_getVersion(COLLATOR_, version);
fprintf(OUTPUT_, "<tr><th>Collator version</th><td class='noborder'>%d.%d.%d.%d</td></tr>\n",
version[0], version[1], version[2], version[3]);
UColAttribute attr = UCOL_FRENCH_COLLATION;
while (attr < UCOL_ATTRIBUTE_COUNT) {
UColAttributeValue value = ucol_getAttribute(COLLATOR_, attr, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error getting attribute\n");
return;
}
if (value != UCOL_DEFAULT) {
if (attr == UCOL_FRENCH_COLLATION && value != UCOL_OFF) {
fprintf(OUTPUT_, "<tr><th>French Collation</th><td class='noborder'>on, code %d</td></tr>\n", value);
}
if (attr == UCOL_ALTERNATE_HANDLING && value != UCOL_NON_IGNORABLE) {
fprintf(OUTPUT_, "<tr><th>Alternate Handling</th><td class='noborder'>shifted, code%d</td></tr>\n", value);
}
if (attr == UCOL_CASE_FIRST && value != UCOL_OFF) {
fprintf(OUTPUT_, "<tr><th>Case First</th><td class='noborder'>on, code %d</td></tr>\n", value);
}
if (attr == UCOL_CASE_LEVEL && value != UCOL_OFF) {
fprintf(OUTPUT_, "<tr><th>Case Level</th><td class='noborder'>on, code %d</td></tr>\n", value);
}
if (attr == UCOL_NORMALIZATION_MODE && value != UCOL_OFF) {
fprintf(OUTPUT_, "<tr><th>Normalization</th><td class='noborder'>on, code %d</td></tr>\n", value);
}
if (attr == UCOL_STRENGTH && value != UCOL_TERTIARY) {
fprintf(OUTPUT_, "<tr><th>Strength</th><td class='noborder'>code %d</td></tr>\n", value);
}
if (attr == UCOL_HIRAGANA_QUATERNARY_MODE && value != UCOL_OFF) {
fprintf(OUTPUT_, "<tr><th>Hiragana Quaternary</th><td class='noborder'>on, code %d</td></tr>\n", value);
}
}
attr = (UColAttribute)(attr + 1);
}
// Get UNIX-style time and display as number and string.
time_t ltime;
time( <ime );
fprintf(OUTPUT_, "<tr><th>Date Generated</th><td class='noborder'>%s</td></tr>", ctime(<ime));
fprintf(OUTPUT_, "</table>\n");
fprintf(OUTPUT_, "<p><a href=help.html>How to read the table</a><br>\n");
fprintf(OUTPUT_, "<a href=http://www.jtcsv.com/cgi-bin/icu-bugs/ target=new>Submit a bug</a></p>\n");
fprintf(OUTPUT_, "\n<table>\n");
fprintf(OUTPUT_, "\n<tr><th>Codepoint</th><th>P</th><th>S</th><th>T</th><th>Q</th><th>Name</th></tr>\n");
}
/**
* Prints the header for index.html
* @param file output file
*/
void outputListHTMLHeader(FILE *file)
{
fprintf(file, "<html>\n");
fprintf(file, "<head>\n");
fprintf(file, "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n");
fprintf(file, "<meta http-equiv=\"Content-Language\" content=\"en-us\">\n");
fprintf(file, "<title>ICU Collation Charts</title>\n");
fprintf(file, "<base target=\"main\">\n");
fprintf(file, "</head>\n");
fprintf(file, "<body bgcolor=#FFFFFF>\n");
fprintf(file, "<h2 align=center>ICU Collation Charts</h2>\n");
fprintf(file, "<p align=center>\n");
fprintf(file, "<a href=http://www.unicode.org/charts/collation/ target=new>UCA Charts</a><br>");
}
/**
* Prints the footer for index.html
* @param file output file
*/
void outputListHTMLFooter(FILE *file)
{
fprintf(file, "</p>\n");
//fprintf(file, "<center><image src=http://oss.software.ibm.com/icu/images/w24.gif></center>\n");
fprintf(file, "</body>\n");
fprintf(file, "</html>\n");
}
/**
* Gets all scripts and serialize their codepoints into an html file.
*/
void serializeScripts() {
char filename[128];
int dirlength = 0;
if (options[4].doesOccur) {
strcpy(filename, options[4].value);
dirlength = appendDirSeparator(filename);
} else {
filename[0] = 0;
}
const char *locale;
int32_t localelist = 0;
int32_t localesize;
localesize = ucol_countAvailable();
locale = ucol_getAvailable(localelist);
strcat(filename, "list.html");
FILE *list = fopen(filename, "w");
filename[dirlength] = 0;
if (list == NULL) {
fprintf(stdout, "Cannot open file: %s\n", filename);
return;
}
outputListHTMLHeader(list);
fprintf(list, "<blockquote>\n");
while (TRUE) {
UErrorCode error = U_ZERO_ERROR;
COLLATOR_ = ucol_open(locale, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Collator creation failed:");
fprintf(stdout, u_errorName(error));
break;
}
if ((error != U_USING_FALLBACK_WARNING && // not tailored
error != U_USING_DEFAULT_WARNING) ||
checkLocaleForLanguage(locale)) {
fprintf(list, "<a href=%s.html>%s</a> ", locale, locale);
setAttributes(COLLATOR_, &error);
if (U_FAILURE(error)) {
fprintf(stdout, "Collator attribute setting failed:");
fprintf(stdout, u_errorName(error));
break;
}
UScriptCode scriptcode[32];
uint32_t scriptcount = uscript_getCode(locale, scriptcode, 32,
&error);
if (U_FAILURE(error)) {
fprintf(stdout, "Error getting lcale scripts\n");
break;
}
strcat(filename, locale);
strcat(filename, ".html");
OUTPUT_ = fopen(filename, "w");
if (OUTPUT_ == NULL) {
fprintf(stdout, "Cannot open file:%s\n", filename);
break;
}
outputHTMLHeader(locale, scriptcode, scriptcount);
fprintf(stdout, "%s\n", locale);
if(options[12].doesOccur) {
// use whole scripts
serializeScripts(scriptcode, scriptcount);
} else {
// use exemplar chars
serializeScripts(scriptcode, scriptcount, locale);
}
fclose(OUTPUT_);
}
ucol_close(COLLATOR_);
filename[dirlength] = 0;
localelist ++;
if (localelist == localesize) {
break;
}
locale = ucol_getAvailable(localelist);
}
fprintf(list, "<br><a href=help.html>help</a><br>");
fprintf(list, "</blockquote>\n");
outputListHTMLFooter(list);
fclose(list);
}
/**
* Main -- process command line, read in and pre-process the test file,
* call other functions to do the actual tests.
*/
int main(int argc, char *argv[]) {
argc = u_parseArgs(argc, argv, sizeof(options)/sizeof(options[0]),
options);
// error handling, printing usage message
if (argc < 0) {
fprintf(stdout, "error in command line argument: ");
fprintf(stdout, argv[-argc]);
fprintf(stdout, "\n");
}
if (argc < 0 || options[0].doesOccur || options[1].doesOccur) {
fprintf(stdout, "Usage: dumpce options...\n"
"--help\n"
" Display this message.\n"
"--locale name|all\n"
" ICU locale to use. Default is en_US\n"
"--serialize\n"
" Serializes the collation elements in -locale or all locales available and outputs them into --outputdir/locale_ce.txt\n"
"--destdir dir_name\n"
" Path for outputing the serialized collation elements. Defaults to stdout if no defined\n"
"--sourcedir dir_name\n"
" Path for the input rule file for collation\n"
"--attribute name=value,name=value...\n"
" Pairs of attribute names and values for setting\n"
"--rule filename\n"
" Name of file containing the collation rules.\n"
"--normalizaton mode\n"
" UNormalizationMode mode to be used.\n"
"--scripts\n"
" Codepoints from all scripts are sorted and serialized.\n"
"--reducehan\n"
" Only 200 Han script characters will be displayed with the use of --scripts.\n"
"--wholescripts\n"
" Show collation order for whole scripts instead of just for exemplar characters of a locale\n\n");
fprintf(stdout, "Example to generate *.txt files : dumpce --serialize --locale af --destdir /temp --attribute UCOL_STRENGTH=UCOL_DEFAULT_STRENGTH,4=17\n\n");
fprintf(stdout, "Example to generate *.html files for oss web display: dumpce --scripts --destdir /temp --reducehan\n");
return argc < 0 ? U_ILLEGAL_ARGUMENT_ERROR : U_ZERO_ERROR;
}
OUTPUT_ = stdout;
if (options[6].doesOccur) {
fprintf(stdout, "attributes %s\n", options[6].value);
parseAttributes();
}
if (options[3].doesOccur) {
serialize();
}
if (options[9].doesOccur) {
serializeScripts();
}
return 0;
}
| 53,420 | 17,425 |
// FolderWeapons.cpp: implementation of the CFolderWeapons class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "FolderWeapons.h"
#include "FolderCommands.h"
#include "MissionData.h"
#include "MissionMgr.h"
#include "ClientRes.h"
#include "InterfaceMgr.h"
#include "GameClientShell.h"
extern CGameClientShell* g_pGameClientShell;
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CFolderWeapons::CFolderWeapons()
{
}
CFolderWeapons::~CFolderWeapons()
{
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CFolderWeapons::Build
//
// PURPOSE: Build the folder
//
// ----------------------------------------------------------------------- //
LTBOOL CFolderWeapons::Build()
{
CreateTitle(IDS_TITLE_WEAPONS);
LTBOOL success = CBaseSelectionFolder::Build();
return success;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CFolderWeapons::IsAvailable
//
// PURPOSE: Check to see if there any selections to be made here
//
// ----------------------------------------------------------------------- //
LTBOOL CFolderWeapons::IsAvailable()
{
int missionNum = g_pInterfaceMgr->GetMissionData()->GetMissionNum();
MISSION* pMission = g_pMissionMgr->GetMission(missionNum);
return (pMission->nNumWeapons != 0);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CFolderWeapons::OnFocus
//
// PURPOSE: Handle gaining or losing focus
//
// ----------------------------------------------------------------------- //
void CFolderWeapons::OnFocus(LTBOOL bFocus)
{
if (bFocus)
{
UseBack(LTTRUE);
SetContinue();
m_szModel[0] = '\0';
m_szSkin[0] = '\0';
BuildWeaponsList();
SetSelection(kNoSelection);
}
else
{
SetSelection(kNoSelection);
SaveWeaponData();
ClearWeaponsList();
}
CBaseSelectionFolder::OnFocus(bFocus);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CFolderWeapons::BuildWeaponsList
//
// PURPOSE: Create the list of weapons
//
// ----------------------------------------------------------------------- //
void CFolderWeapons::BuildWeaponsList()
{
//get info from MissionMgr
CMissionData *pData = g_pInterfaceMgr->GetMissionData();
int missionNum = pData->GetMissionNum();
MISSION* pMission = g_pMissionMgr->GetMission(missionNum);
CPlayerStats* pStats = g_pInterfaceMgr->GetPlayerStats();
m_nNumSlots = pMission->nNumWeapons;
if (m_nNumSlots == -1 || m_nNumSlots > MAX_SELECTION_SLOTS)
m_nNumSlots = MAX_SELECTION_SLOTS;
//no choices allowed... don't go here
if (m_nNumSlots <= 0) return;
int nWID = WMGR_INVALID_ID;
WEAPON* pWeapon = LTNULL;
for (int i=0; i< pMission->nNumRequiredWeapons; i++)
{
nWID = pMission->aRequiredWeapons[i];
pWeapon = g_pWeaponMgr->GetWeapon(nWID);
AddToSlot(nWID,pWeapon->nNameId,LTTRUE);
}
for (i=0; i< pMission->nNumOneTimeWeapons; i++)
{
nWID = pMission->aOneTimeWeapons[i];
pWeapon = g_pWeaponMgr->GetWeapon(nWID);
AddToSlot(nWID,pWeapon->nNameId,LTTRUE);
}
int numCurrWeapons = pData->GetNumWeapons();
if (numCurrWeapons)
{
CWeaponData* currWeapons[255];
WEAPON* pWeapon = LTNULL;
numCurrWeapons = pData->GetWeapons(currWeapons,255);
for (i=0; i< numCurrWeapons; i++)
{
nWID = currWeapons[i]->m_nID;
pWeapon = g_pWeaponMgr->GetWeapon(nWID);
if (pWeapon && !pWeapon->IsAGadget())
AddToSlot(nWID,pWeapon->nNameId,LTFALSE);
}
}
else
{
for (i=0; i< pMission->nNumDefaultWeapons; i++)
{
nWID = pMission->aDefaultWeapons[i];
pWeapon = g_pWeaponMgr->GetWeapon(nWID);
AddToSlot(nWID,pWeapon->nNameId,LTFALSE);
}
}
for (i=0; i< pMission->nNumAllowedWeapons; i++)
{
nWID = pMission->aAllowedWeapons[i];
pWeapon = g_pWeaponMgr->GetWeapon(nWID);
AddItem(nWID,pWeapon->nNameId);
}
int numWeapons = g_pWeaponMgr->GetNumWeapons();
for (i=0; i < numWeapons; i++)
{
pWeapon = g_pWeaponMgr->GetWeapon(i);
AMMO *pAmmo = g_pWeaponMgr->GetAmmo(pWeapon->nDefaultAmmoType);
if (pStats->CanUseWeapon(i) && !pWeapon->IsAGadget() && pAmmo->eInstDamageType != DT_MELEE)
{
AddItem(i,pWeapon->nNameId);
}
}
for (i=0; i< pMission->nNumDeniedWeapons; i++)
{
nWID = pMission->aDeniedWeapons[i];
RemoveFromSlot(nWID);
RemoveItem(nWID);
}
int nNumSelectable = (int)m_controlArray.GetSize();
int nNumFree = m_nNumSlots - m_nSlotsFilled;
if (nNumFree > nNumSelectable)
{
nNumFree = nNumSelectable;
m_nNumSlots = m_nSlotsFilled + nNumFree;
while (m_controlArray.GetSize())
{
nNumFree--;
CLTGUICtrl *pCtrl = GetControl(0);
if (pCtrl)
{
int nWID = pCtrl->GetParam1();
WEAPON* pWeapon = g_pWeaponMgr->GetWeapon(nWID);
ItemToSlot(nWID,pWeapon->nNameId);
}
}
}
for (i=0;i < nNumFree;i++)
{
AddEmptySlot();
}
return;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CFolderWeapons::UpdateSelection
//
// PURPOSE: Show info based on current selection
//
// ----------------------------------------------------------------------- //
LTBOOL CFolderWeapons::UpdateSelection()
{
LTBOOL bChanged = CBaseSelectionFolder::UpdateSelection();
if (bChanged)
{
CLTGUICtrl *pCtrl = GetControl(m_nLastListItem);
int weaponId = pCtrl->GetParam1();
WEAPON* pWeapon = g_pWeaponMgr->GetWeapon(weaponId);
if (pWeapon)
{
m_pName->RemoveAll();
m_pName->AddString(pWeapon->nNameId);
m_pDescription->SetString(pWeapon->nDescriptionId);
SAFE_STRCPY(m_szModel, pWeapon->szInterfaceModel);
SAFE_STRCPY(m_szSkin, pWeapon->szInterfaceSkin);
VEC_COPY(m_vOffset, pWeapon->vInterfaceOffset);
m_fScale = pWeapon->fInterfaceScale;
CreateModelSFX();
}
}
return bChanged;
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CFolderWeapons::ClearWeaponsList
//
// PURPOSE: Remove all of the controls
//
// ----------------------------------------------------------------------- //
void CFolderWeapons::ClearWeaponsList()
{
// Terminate the ctrls
RemoveFree();
ClearSlots();
ClearSelection();
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CFolderWeapons::SaveWeaponData
//
// PURPOSE: Save the players selections
//
// ----------------------------------------------------------------------- //
void CFolderWeapons::SaveWeaponData()
{
CMissionData *pData = g_pInterfaceMgr->GetMissionData();
pData->ClearWeapons();
if (m_bSaveSelection)
{
for (int slot = 0; slot < m_nSlotsFilled; slot++)
{
CLTGUICtrl *pCtrl = GetControl(m_nFirstSlot - slot);
if (pCtrl && (int)pCtrl->GetParam1() != kEmptySlot)
pData->AddWeapon(pCtrl->GetParam1());
}
}
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CFolderWeapons::OnCommand
//
// PURPOSE: Handle activation of items
//
// ----------------------------------------------------------------------- //
uint32 CFolderWeapons::OnCommand(uint32 dwCommand, uint32 dwParam1, uint32 dwParam2)
{
switch (dwCommand)
{
case FOLDER_CMD_SELECT_SLOT:
{
if (dwParam2)
{
g_pInterfaceMgr->RequestInterfaceSound(IS_NO_SELECT);
return 0;
}
int nWID = (int)dwParam1;
WEAPON *pWeapon = g_pWeaponMgr->GetWeapon(nWID);
SlotToItem(nWID,pWeapon->nNameId);
return 1;
} break;
case FOLDER_CMD_SELECT_ITEM:
{
int nWID = (int)dwParam1;
WEAPON *pWeapon = g_pWeaponMgr->GetWeapon(nWID);
ItemToSlot(nWID,pWeapon->nNameId);
return 1;
} break;
case FOLDER_CMD_CONTINUE:
{
if (m_pContinue->GetHelpID() == IDS_HELP_START)
{
int missionNum = g_pInterfaceMgr->GetMissionData()->GetMissionNum();
g_pGameClientShell->StartMission(missionNum);
return 1;
}
} break;
}
return CBaseSelectionFolder::OnCommand(dwCommand,dwParam1,dwParam2);
}
HSTRING CFolderWeapons::GetHelpString(uint32 dwHelpId, int nControlIndex)
{
WEAPON* pWeapon = LTNULL;
char pStr[512] = "";
//slots are fixed controls so count negatively ( 0 > first > last )
int nLastSlot = (m_nFirstSlot - m_nNumSlots) + 1;
if (nControlIndex >= 0 || (nControlIndex <= m_nFirstSlot && nControlIndex >= nLastSlot))
{
CLTGUICtrl *pCtrl = GetControl(nControlIndex);
int weaponId = pCtrl->GetParam1();
if (weaponId == kEmptySlot) return CBaseSelectionFolder::GetHelpString(dwHelpId,nControlIndex);
pWeapon = g_pWeaponMgr->GetWeapon(weaponId);
if (!pWeapon) return CBaseSelectionFolder::GetHelpString(dwHelpId,nControlIndex);
int nameId = pWeapon->nNameId;
HSTRING hTemp = g_pLTClient->FormatString(nameId);
char *pName = g_pLTClient->GetStringData(hTemp);
if (nControlIndex < 0)
{
//over a slot
if (pCtrl->GetParam2())
{
sprintf(pStr,"%s %s",pName,m_sRequiredStr);
}
else if (nControlIndex < 0)
{
sprintf(pStr,"%s %s",m_sUnselectStr,pName);
}
}
else
{
sprintf(pStr,"%s %s",m_sSelectStr,pName);
}
g_pLTClient->FreeString(hTemp);
HSTRING hStr = g_pLTClient->CreateString(pStr);
return hStr;
}
else
return CBaseSelectionFolder::GetHelpString(dwHelpId,nControlIndex);
}
void CFolderWeapons::SetContinue()
{
int nHelp = LTNULL;
eFolderID eNext = GetNextSelectionFolder(FOLDER_ID_WEAPONS,&nHelp);
if (eNext != FOLDER_ID_NONE)
{
UseContinue(eNext,nHelp);
}
else
{
UseContinue(g_pInterfaceMgr->GetMainFolder(),IDS_HELP_START,IDS_START_MISSION);
}
}
void CFolderWeapons::CreateModelSFX()
{
// no model = no SFX
if (!strlen(m_szModel)) return;
HOBJECT hCamera = g_pGameClientShell->GetInterfaceCamera();
if (!hCamera) return;
BSCREATESTRUCT bcs;
LTVector vPos, vU, vR, vF, vTemp, vScale(1.0f,1.0f,1.0f);
LTRotation rRot;
g_pLTClient->GetObjectPos(hCamera, &vPos);
g_pLTClient->GetObjectRotation(hCamera, &rRot);
g_pLTClient->GetRotationVectors(&rRot, &vU, &vR, &vF);
g_pLTClient->RotateAroundAxis(&rRot, &vU, MATH_HALFPI);
g_pLTClient->RotateAroundAxis(&rRot, &vR, -0.3f);
VEC_MULSCALAR(vScale, vScale, m_fScale);
LTVector vModPos = g_pLayoutMgr->GetFolderCustomVector((eFolderID)m_nFolderID,"ModelPos");
VEC_ADD(vModPos,vModPos,m_vOffset);
VEC_MULSCALAR(vTemp, vF, vModPos.z);
VEC_MULSCALAR(vTemp, vTemp, 1);//g_pInterfaceResMgr->GetXRatio());
VEC_ADD(vPos, vPos, vTemp);
VEC_MULSCALAR(vTemp, vR, vModPos.x);
VEC_ADD(vPos, vPos, vTemp);
VEC_MULSCALAR(vTemp, vU, vModPos.y);
VEC_ADD(vPos, vPos, vTemp);
VEC_COPY(bcs.vPos, vPos);
bcs.rRot = rRot;
VEC_COPY(bcs.vInitialScale, vScale);
VEC_COPY(bcs.vFinalScale, vScale);
VEC_SET(bcs.vInitialColor, 1.0f, 1.0f, 1.0f);
VEC_SET(bcs.vFinalColor, 1.0f, 1.0f, 1.0f);
bcs.bUseUserColors = LTTRUE;
bcs.pFilename = m_szModel;
bcs.pSkin = m_szSkin;
bcs.dwFlags = FLAG_VISIBLE | FLAG_FOGDISABLE | FLAG_NOLIGHT;
bcs.nType = OT_MODEL;
bcs.fInitialAlpha = 1.0f;
bcs.fFinalAlpha = 1.0f;
bcs.fLifeTime = 1000000.0f;
if (m_ModelSFX.Init(&bcs))
{
m_ModelSFX.CreateObject(g_pLTClient);
g_pInterfaceMgr->AddInterfaceSFX(&m_ModelSFX, IFX_NORMAL);
m_fSFXRot = g_pLayoutMgr->GetFolderCustomFloat((eFolderID)m_nFolderID,"ModelRotSpeed");
}
}
void CFolderWeapons::RemoveInterfaceSFX()
{
CBaseSelectionFolder::RemoveInterfaceSFX();
g_pInterfaceMgr->RemoveInterfaceSFX(&m_ModelSFX);
m_ModelSFX.Term();
}
void CFolderWeapons::UpdateInterfaceSFX()
{
CBaseSelectionFolder::UpdateInterfaceSFX();
if (m_ModelSFX.GetObject())
{
LTFLOAT spin = g_pGameClientShell->GetFrameTime() * m_fSFXRot;
LTVector vU, vR, vF;
LTRotation rRot;
g_pLTClient->GetObjectRotation(m_ModelSFX.GetObject(), &rRot);
g_pLTClient->GetRotationVectors(&rRot, &vU, &vR, &vF);
g_pLTClient->RotateAroundAxis(&rRot, &vU, spin);
g_pLTClient->SetObjectRotation(m_ModelSFX.GetObject(),&rRot);
}
}
void CFolderWeapons::SkipOutfitting()
{
CMissionData *pData = g_pInterfaceMgr->GetMissionData();
int missionNum = pData->GetMissionNum();
MISSION* pMission = g_pMissionMgr->GetMission(missionNum);
pData->ClearWeapons();
int nWID = WMGR_INVALID_ID;
WEAPON* pWeapon = LTNULL;
for (int i=0; i< pMission->nNumRequiredWeapons; i++)
{
nWID = pMission->aRequiredWeapons[i];
pWeapon = g_pWeaponMgr->GetWeapon(nWID);
pData->AddWeapon(nWID);
}
for (i=0; i< pMission->nNumOneTimeWeapons; i++)
{
nWID = pMission->aOneTimeWeapons[i];
pWeapon = g_pWeaponMgr->GetWeapon(nWID);
pData->AddWeapon(nWID);
}
for (i=0; i< pMission->nNumDefaultWeapons; i++)
{
nWID = pMission->aDefaultWeapons[i];
pWeapon = g_pWeaponMgr->GetWeapon(nWID);
pData->AddWeapon(nWID);
}
}
| 12,800 | 5,482 |
/* Copyright (c) 2010-2019, Delft University of Technology
* All rigths reserved
*
* This file is part of the Tudat. Redistribution and use in source and
* binary forms, with or without modification, are permitted exclusively
* under the terms of the Modified BSD license. You should have received
* a copy of the license with this file. If not, please or visit:
* http://tudat.tudelft.nl/LICENSE.
*
*/
#define BOOST_TEST_MAIN
#include <limits>
#include <string>
#include <vector>
#include <boost/test/unit_test.hpp>
#include <boost/make_shared.hpp>
#include <boost/lambda/lambda.hpp>
#include "Tudat/Basics/testMacros.h"
#include "Tudat/InputOutput/basicInputOutput.h"
#include "Tudat/External/SpiceInterface/spiceInterface.h"
#include "Tudat/SimulationSetup/EstimationSetup/createObservationModel.h"
#include "Tudat/Astrodynamics/ObservationModels/oneWayDopplerObservationModel.h"
#include "Tudat/Astrodynamics/OrbitDetermination/EstimatableParameters/constantRotationRate.h"
#include "Tudat/SimulationSetup/EstimationSetup/createObservationPartials.h"
#include "Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/numericalObservationPartial.h"
#include "Tudat/SimulationSetup/EnvironmentSetup/createGroundStations.h"
#include "Tudat/SimulationSetup/EnvironmentSetup/defaultBodies.h"
#include "Tudat/Mathematics/BasicMathematics/numericalDerivative.h"
#include "Tudat/Astrodynamics/OrbitDetermination/ObservationPartials/UnitTests/observationPartialTestFunctions.h"
namespace tudat
{
namespace unit_tests
{
BOOST_AUTO_TEST_SUITE( test_one_way_observation_partials)
Eigen::Vector3d computeUnitVectorToReceiverFromTransmitterState(
const Eigen::Vector3d receiverPosition,
const std::function< Eigen::Vector6d( const double ) > transmitterStateFunction,
const double evaluationTime )
{
return ( receiverPosition - transmitterStateFunction( evaluationTime ).segment( 0, 3 ) ).normalized( );
}
Eigen::Vector3d computeUnitVectorToReceiverFromReceiverState(
const std::function< Eigen::Vector6d( const double ) > receiverStateFunction,
const Eigen::Vector3d transmitterPosition,
const double evaluationTime )
{
return ( receiverStateFunction( evaluationTime ).segment( 0, 3 ) - transmitterPosition ).normalized( );
}
Eigen::VectorXd getProperTimeRateInVectorForm(
std::shared_ptr< DopplerProperTimeRateInterface > properTimeRateCalculator,
const std::vector< double >& linkEndTimes,
const std::vector< Eigen::Matrix< double, 6, 1 > >& linkEndStates,
const LinkEndType linkEndAssociatedWithTime )
{
return ( Eigen::Vector1d( ) << properTimeRateCalculator->getOberverProperTimeDeviation(
linkEndTimes, linkEndStates ) ).finished( );
}
//! Test partial derivatives of one-way doppler observable, using general test suite of observation partials.
BOOST_AUTO_TEST_CASE( testOneWayDopplerPartials )
{
using namespace tudat::gravitation;
using namespace tudat::gravitation;
using namespace tudat::ephemerides;
using namespace tudat::observation_models;
using namespace tudat::simulation_setup;
using namespace tudat::spice_interface;
using namespace tudat::observation_partials;
using namespace tudat::estimatable_parameters;
// Define and create ground stations.
std::vector< std::pair< std::string, std::string > > groundStations;
groundStations.resize( 2 );
groundStations[ 0 ] = std::make_pair( "Earth", "Graz" );
groundStations[ 1 ] = std::make_pair( "Mars", "MSL" );
// Test ancilliary functions
{
double nominalEvaluationTime = 1.1E7;
// Create environment
NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, false );
// Set link ends for observation model
LinkEnds linkEnds;
linkEnds[ transmitter ] = groundStations[ 1 ];
linkEnds[ receiver ] = groundStations[ 0 ];
// Create transmitter/receriver state functions
std::function< Eigen::Vector6d( const double ) > transmitterStateFunction =
getLinkEndCompleteEphemerisFunction< double, double >( linkEnds[ transmitter ], bodyMap );
std::function< Eigen::Vector6d( const double ) > receiverStateFunction =
getLinkEndCompleteEphemerisFunction< double, double >( linkEnds[ receiver ], bodyMap );
// Define (independent!) transmission/reception times
double transmissionTime = nominalEvaluationTime;
double receptionTime = nominalEvaluationTime + 1.0E3;
// Compute associated states
Eigen::Vector6d nominalTransmitterState = transmitterStateFunction( transmissionTime );
Eigen::Vector6d nominalReceiverState = receiverStateFunction( receptionTime );
Eigen::Vector3d nominalVectorToReceiver = ( nominalReceiverState - nominalTransmitterState ).segment( 0, 3 );
double timePerturbation = 100.0;
// Partials for fixed receiver
{
// Compute numerical derivative of transmitter state for acceleration)
Eigen::Vector6d numericalStateDerivative = numerical_derivatives::computeCentralDifferenceFromFunction(
transmitterStateFunction, transmissionTime, timePerturbation, numerical_derivatives::order8 );
// Compute unit vector derivative numerically
std::function< Eigen::Vector3d( const double ) > unitVectorFunction =
std::bind( &computeUnitVectorToReceiverFromTransmitterState,
nominalReceiverState.segment( 0, 3 ), transmitterStateFunction, std::placeholders::_1 );
Eigen::Vector3d numericalUnitVectorDerivative = numerical_derivatives::computeCentralDifferenceFromFunction(
unitVectorFunction, transmissionTime, timePerturbation, numerical_derivatives::order8 );
// Compute projected velocoty vector derivative numerically
std::function< double( const double) > projectedVelocityFunction =
std::bind( &calculateLineOfSightVelocityAsCFractionFromTransmitterStateFunction< double, double >,
nominalReceiverState.segment( 0, 3 ), transmitterStateFunction, std::placeholders::_1 );
double numericalProjectedVelocityDerivative =
numerical_derivatives::computeCentralDifferenceFromFunction(
projectedVelocityFunction, transmissionTime, timePerturbation, numerical_derivatives::order8 );
// Compute analytical partial derivatives
Eigen::Vector3d analyticalUnitVectorDerivative =
-computePartialOfUnitVectorWrtLinkEndTime(
nominalVectorToReceiver, nominalVectorToReceiver.normalized( ),
nominalVectorToReceiver.norm( ), nominalTransmitterState.segment( 3, 3 ) );
double analyticalProjectedVelocityDerivative = computePartialOfProjectedLinkEndVelocityWrtAssociatedTime(
nominalVectorToReceiver,
nominalTransmitterState.segment( 3, 3 ),
nominalTransmitterState.segment( 3, 3 ),
numericalStateDerivative.segment( 3, 3 ), false );
for( unsigned int i = 0; i < 3; i++ )
{
BOOST_CHECK_SMALL( std::fabs( analyticalUnitVectorDerivative( i ) - numericalUnitVectorDerivative( i ) ), 1.0E-16 );
}
BOOST_CHECK_SMALL( std::fabs( analyticalProjectedVelocityDerivative / physical_constants::SPEED_OF_LIGHT -
numericalProjectedVelocityDerivative ), 1.0E-21 );
}
// Partials for fixed transmitter
{
// Compute numerical derivative of receiver state for acceleration)
Eigen::Vector6d numericalStateDerivative = numerical_derivatives::computeCentralDifferenceFromFunction(
receiverStateFunction, receptionTime, timePerturbation, numerical_derivatives::order8 );
// Compute unit vector derivative numerically
std::function< Eigen::Vector3d( const double ) > unitVectorFunction =
std::bind( &computeUnitVectorToReceiverFromReceiverState,
receiverStateFunction, nominalTransmitterState.segment( 0, 3 ), std::placeholders::_1 );
Eigen::Vector3d numericalUnitVectorDerivative = numerical_derivatives::computeCentralDifferenceFromFunction(
unitVectorFunction, receptionTime, timePerturbation, numerical_derivatives::order8 );
// Compute projected velocoty vector derivative numerically
std::function< double( const double) > projectedVelocityFunction =
std::bind( &calculateLineOfSightVelocityAsCFractionFromReceiverStateFunction< double, double >,
receiverStateFunction, nominalTransmitterState.segment( 0, 3 ), std::placeholders::_1 );
double numericalProjectedVelocityDerivative =
numerical_derivatives::computeCentralDifferenceFromFunction(
projectedVelocityFunction, receptionTime, timePerturbation, numerical_derivatives::order8 );
// Compute analytical partial derivatives
Eigen::Vector3d analyticalUnitVectorDerivative =
computePartialOfUnitVectorWrtLinkEndTime(
nominalVectorToReceiver, nominalVectorToReceiver.normalized( ),
nominalVectorToReceiver.norm( ), nominalReceiverState.segment( 3, 3 ) );
double analyticalProjectedVelocityDerivative = computePartialOfProjectedLinkEndVelocityWrtAssociatedTime(
nominalVectorToReceiver,
nominalReceiverState.segment( 3, 3 ),
nominalReceiverState.segment( 3, 3 ),\
numericalStateDerivative.segment( 3, 3 ), true );
for( unsigned int i = 0; i < 3; i++ )
{
BOOST_CHECK_SMALL( std::fabs( analyticalUnitVectorDerivative( i ) - numericalUnitVectorDerivative( i ) ), 1.0E-18 );
}
BOOST_CHECK_SMALL( std::fabs( analyticalProjectedVelocityDerivative / physical_constants::SPEED_OF_LIGHT -
numericalProjectedVelocityDerivative ), 1.0E-22 );
}
}
// Test partials with constant ephemerides (allows test of position partials)
{
// Create environment
NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, true );
// Set link ends for observation model
LinkEnds linkEnds;
linkEnds[ transmitter ] = groundStations[ 1 ];
linkEnds[ receiver ] = groundStations[ 0 ];
for( unsigned int estimationCase = 0; estimationCase < 3; estimationCase ++ )
{
std::cout << "Case " << estimationCase << std::endl;
// Generate one-way doppler model
std::shared_ptr< ObservationModel< 1 > > oneWayDopplerModel;
std::vector< std::string > perturbingBodies;
perturbingBodies.push_back( "Earth" );
if( estimationCase == 0 )
{
oneWayDopplerModel =
observation_models::ObservationModelCreator< 1, double, double >::createObservationModel(
linkEnds, std::make_shared< observation_models::ObservationSettings >(
observation_models::one_way_doppler,
std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >(
perturbingBodies ) ), bodyMap );
}
else
{
oneWayDopplerModel =
observation_models::ObservationModelCreator< 1, double, double >::createObservationModel(
linkEnds, std::make_shared< OneWayDopplerObservationSettings >
( std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >(
perturbingBodies ),
std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Mars" ),
std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Earth" ) ), bodyMap );
}
// Create parameter objects.
std::shared_ptr< EstimatableParameterSet< double > > fullEstimatableParameterSet;
Eigen::VectorXd parameterPerturbationMultipliers = Eigen::Vector4d::Constant( 1.0 );
if( estimationCase < 2 )
{
fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7 );
}
else
{
fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7, true );
parameterPerturbationMultipliers( 2 ) = 1.0E-4;
}
testObservationPartials< 1 >(
oneWayDopplerModel, bodyMap, fullEstimatableParameterSet, linkEnds, one_way_doppler, 1.0E-5,
true, true, 10.0, parameterPerturbationMultipliers );
std::cout << "Case " << estimationCase << std::endl;
}
}
// Test partials with real ephemerides (without test of position partials)
{
// Create environment
NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, false );
// Set link ends for observation model
LinkEnds linkEnds;
linkEnds[ transmitter ] = groundStations[ 1 ];
linkEnds[ receiver ] = groundStations[ 0 ];
for( unsigned int estimationCase = 0; estimationCase < 3; estimationCase ++ )
{
std::cout << "Rates: " << estimationCase << std::endl;
// Generate one-way doppler model
std::shared_ptr< ObservationModel< 1 > > oneWayDopplerModel;
std::vector< std::string > perturbingBodies;
perturbingBodies.push_back( "Earth" );
if( estimationCase == 0 )
{
oneWayDopplerModel =
observation_models::ObservationModelCreator< 1, double, double >::createObservationModel(
linkEnds, std::make_shared< observation_models::ObservationSettings >(
observation_models::one_way_doppler,
std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >(
perturbingBodies ) ), bodyMap );
}
else
{
oneWayDopplerModel =
observation_models::ObservationModelCreator< 1, double, double >::createObservationModel(
linkEnds, std::make_shared< OneWayDopplerObservationSettings >
( std::make_shared< FirstOrderRelativisticLightTimeCorrectionSettings >(
perturbingBodies ),
std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Mars" ),
std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Earth" ) ), bodyMap );
}
// Create parameter objects.
std::shared_ptr< EstimatableParameterSet< double > > fullEstimatableParameterSet;
Eigen::VectorXd parameterPerturbationMultipliers = Eigen::Vector4d::Constant( 1.0 );
if( estimationCase < 2 )
{
fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7 );
}
else
{
fullEstimatableParameterSet = createEstimatableParameters( bodyMap, 1.1E7, true );
parameterPerturbationMultipliers( 2 ) = 1.0E-4;
}
testObservationPartials< 1 >(
oneWayDopplerModel, bodyMap, fullEstimatableParameterSet, linkEnds, one_way_doppler, 1.0E-4, false, true,
1.0, parameterPerturbationMultipliers );
}
}
// Test partials with constant ephemerides (allows test of position partials)
{
// Create environment
NamedBodyMap bodyMap = setupEnvironment( groundStations, 1.0E7, 1.2E7, 1.1E7, true, 1000000.0 );
// Set link ends for observation model (Mars to Earth)
LinkEnds linkEnds;
linkEnds[ transmitter ] = groundStations[ 1 ];
linkEnds[ receiver ] = groundStations[ 0 ];
// Create one-way doppler model
std::shared_ptr< OneWayDopplerObservationModel< > > oneWayDopplerModel =
std::dynamic_pointer_cast< OneWayDopplerObservationModel< > >(
observation_models::ObservationModelCreator< 1, double, double >::createObservationModel(
linkEnds, std::make_shared< OneWayDopplerObservationSettings >
( std::shared_ptr< LightTimeCorrectionSettings >( ),
std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Earth" ),
std::make_shared< DirectFirstOrderDopplerProperTimeRateSettings >( "Mars" ) ), bodyMap ) );
// Extract proper time calculators
std::shared_ptr< DopplerProperTimeRateInterface > receiverProperTimeRateCalculator =
oneWayDopplerModel->getReceiverProperTimeRateCalculator( );
std::shared_ptr< DopplerProperTimeRateInterface > transmitterProperTimeRateCalculator =
oneWayDopplerModel->getTransmitterProperTimeRateCalculator( );
// Create parameter objects.
std::shared_ptr< EstimatableParameterSet< double > > fullEstimatableParameterSet =
createEstimatableParameters( bodyMap, 1.1E7 );
// Create partials for Doppler with proper time rates
std::map< LinkEnds, std::shared_ptr< ObservationModel< 1 > > > observationModelList;
observationModelList[ linkEnds ] = oneWayDopplerModel;
std::map< LinkEnds, std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > > dopplerPartials =
createOneWayDopplerPartials( observationModelList, bodyMap, fullEstimatableParameterSet );
// Retrieve scaling objects and partials with proper time
std::shared_ptr< OneWayDopplerScaling > partialScalingObject =
std::dynamic_pointer_cast< OneWayDopplerScaling >( dopplerPartials.begin( )->second.second );
std::shared_ptr< OneWayDopplerProperTimeComponentScaling > transmitterProperTimePartials =
partialScalingObject->getTransmitterProperTimePartials( );
std::shared_ptr< OneWayDopplerProperTimeComponentScaling > receiverProperTimePartials =
partialScalingObject->getReceiverProperTimePartials( );
std::shared_ptr< OneWayDopplerPartial > earthStatePartial =
std::dynamic_pointer_cast< OneWayDopplerPartial >(
( dopplerPartials.begin( )->second.first ).begin( )->second );
std::shared_ptr< OneWayDopplerPartial > marsStatePartial =
std::dynamic_pointer_cast< OneWayDopplerPartial >(
( ++( ( dopplerPartials.begin( )->second.first ).begin( ) ) )->second );
// Compute nominal observation with proper time
double observationTime = 1.1E7;
std::vector< double > linkEndTimes;
std::vector< Eigen::Vector6d > linkEndStates;
LinkEndType referenceLinkEnd = transmitter;
Eigen::VectorXd nominalObservable = oneWayDopplerModel->computeIdealObservationsWithLinkEndData(
observationTime, referenceLinkEnd, linkEndTimes, linkEndStates );
// Compute partials with proper time.
partialScalingObject->update(
linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable );
std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > earthStatePartialOutput =
earthStatePartial->calculatePartial( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable );
std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > marsStatePartialOutput =
marsStatePartial->calculatePartial( linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable );
// Compute numerical proper time rate partials and compare to analytical results
{
std::function< Eigen::VectorXd( const double ) > transmitterProperTimeRateFunction =
std::bind( &getProperTimeRateInVectorForm,
transmitterProperTimeRateCalculator,
linkEndTimes, linkEndStates, referenceLinkEnd );
Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtMarsPosition =
calculatePartialWrtConstantBodyState(
"Earth", bodyMap, Eigen::Vector3d::Constant( 1000.0E3 ), transmitterProperTimeRateFunction, 1.1E7, 1 );
Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtEarthPosition =
calculatePartialWrtConstantBodyState(
"Mars", bodyMap, Eigen::Vector3d::Constant( 1000.0E3 ), transmitterProperTimeRateFunction, 1.1E7, 1 );
Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtMarsVelocity =
calculatePartialWrtConstantBodyVelocity(
"Earth", bodyMap, Eigen::Vector3d::Constant( 1.0E0 ), transmitterProperTimeRateFunction, 1.1E7, 1 );
Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalTransmitterProperTimePartialsWrtEarthVelocity =
calculatePartialWrtConstantBodyVelocity(
"Mars", bodyMap, Eigen::Vector3d::Constant( 1.0E0 ), transmitterProperTimeRateFunction, 1.1E7, 1 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( transmitterProperTimePartials->getPositionScalingFactor( transmitter ) ),
numericalTransmitterProperTimePartialsWrtMarsPosition, 1.0E-6 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( transmitterProperTimePartials->getPositionScalingFactor( receiver ) ),
numericalTransmitterProperTimePartialsWrtEarthPosition, 1.0E-6 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( transmitterProperTimePartials->getVelocityScalingFactor( transmitter ) ),
numericalTransmitterProperTimePartialsWrtMarsVelocity, 1.0E-6 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( transmitterProperTimePartials->getVelocityScalingFactor( receiver ) ),
numericalTransmitterProperTimePartialsWrtEarthVelocity, 1.0E-6 );
std::function< Eigen::VectorXd( const double ) > receiverProperTimeRateFunction =
std::bind( &getProperTimeRateInVectorForm,
receiverProperTimeRateCalculator,
linkEndTimes, linkEndStates, referenceLinkEnd );
Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtMarsPosition =
calculatePartialWrtConstantBodyState(
"Earth", bodyMap, Eigen::Vector3d::Constant( 10000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 );
Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtEarthPosition =
calculatePartialWrtConstantBodyState(
"Mars", bodyMap, Eigen::Vector3d::Constant( 10000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 );
Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtMarsVelocity =
calculatePartialWrtConstantBodyVelocity(
"Earth", bodyMap, Eigen::Vector3d::Constant( 1000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 );
Eigen::Matrix< double, Eigen::Dynamic, 3 > numericalReceiverProperTimePartialsWrtEarthVelocity =
calculatePartialWrtConstantBodyVelocity(
"Mars", bodyMap, Eigen::Vector3d::Constant( 1000.0 ), receiverProperTimeRateFunction, 1.1E7, 1 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( receiverProperTimePartials->getPositionScalingFactor( receiver ) ),
numericalReceiverProperTimePartialsWrtEarthPosition, 1.0E-6 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( receiverProperTimePartials->getPositionScalingFactor( transmitter ) ),
numericalReceiverProperTimePartialsWrtMarsPosition, 1.0E-6 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( receiverProperTimePartials->getVelocityScalingFactor( transmitter ) ),
numericalReceiverProperTimePartialsWrtMarsVelocity, 1.0E-6 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( receiverProperTimePartials->getVelocityScalingFactor( receiver ) ),
numericalReceiverProperTimePartialsWrtEarthVelocity, 1.0E-6 );
}
// Create one-way doppler model without proper time rates
std::shared_ptr< OneWayDopplerObservationModel< > > oneWayDopplerModelWithoutProperTime =
std::dynamic_pointer_cast< OneWayDopplerObservationModel< > >(
observation_models::ObservationModelCreator< 1, double, double >::createObservationModel(
linkEnds, std::make_shared< ObservationSettings >
( one_way_doppler, std::shared_ptr< LightTimeCorrectionSettings >( ) ), bodyMap ) );
// Create partials for Doppler without proper time rates
observationModelList.clear( );
observationModelList[ linkEnds ] = oneWayDopplerModelWithoutProperTime;
std::map< LinkEnds, std::pair< SingleLinkObservationPartialList, std::shared_ptr< PositionPartialScaling > > > dopplerPartialsWithoutProperTime =
createOneWayDopplerPartials( observationModelList, bodyMap, fullEstimatableParameterSet );
// Retrieve partial object without proper time
std::shared_ptr< OneWayDopplerScaling > partialScalingObjectWithoutProperTime =
std::dynamic_pointer_cast< OneWayDopplerScaling >( dopplerPartialsWithoutProperTime.begin( )->second.second );
std::shared_ptr< OneWayDopplerPartial > earthStatePartialWithoutProperTime =
std::dynamic_pointer_cast< OneWayDopplerPartial >(
( dopplerPartialsWithoutProperTime.begin( )->second.first ).begin( )->second );
std::shared_ptr< OneWayDopplerPartial > marsStatePartialWithoutProperTime =
std::dynamic_pointer_cast< OneWayDopplerPartial >(
( ++( ( dopplerPartialsWithoutProperTime.begin( )->second.first ).begin( ) ) )->second );
// Compute nominal observation without proper time
std::vector< double > linkEndTimesWithoutProperTime;
std::vector< Eigen::Vector6d > linkEndStatesWithoutProperTime;
Eigen::VectorXd nominalObservableWithoutProperTime = oneWayDopplerModelWithoutProperTime->computeIdealObservationsWithLinkEndData(
observationTime, referenceLinkEnd, linkEndTimesWithoutProperTime, linkEndStatesWithoutProperTime );
// Compute partials with proper time.
partialScalingObjectWithoutProperTime->update(
linkEndStatesWithoutProperTime, linkEndTimesWithoutProperTime,
referenceLinkEnd, nominalObservableWithoutProperTime );
std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > earthStatePartialOutputWithoutProperTime =
earthStatePartialWithoutProperTime->calculatePartial(
linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable );
std::vector< std::pair< Eigen::Matrix< double, 1, Eigen::Dynamic >, double > > marsStatePartialOutputWithoutProperTime =
marsStatePartialWithoutProperTime->calculatePartial(
linkEndStates, linkEndTimes, referenceLinkEnd, nominalObservable );
Eigen::MatrixXd partialWrtEarthState = earthStatePartialOutput.at( 0 ).first;
Eigen::MatrixXd partialWrtEarthStateWithoutProperTime = earthStatePartialOutputWithoutProperTime.at( 0 ).first;
Eigen::MatrixXd partialWrtMarsState = marsStatePartialOutput.at( 0 ).first;
Eigen::MatrixXd partialWrtMarsStateWithoutProperTime = marsStatePartialOutputWithoutProperTime.at( 0 ).first;
Eigen::MatrixXd properTimePartialWrtMarsPosition = transmitterProperTimePartials->getPositionScalingFactor( transmitter );
Eigen::MatrixXd properTimePartialWrtEarthPosition = receiverProperTimePartials->getPositionScalingFactor( receiver );
Eigen::MatrixXd properTimePartialWrtMarsVelocity = transmitterProperTimePartials->getVelocityScalingFactor( transmitter );
Eigen::MatrixXd properTimePartialWrtEarthVelocity = receiverProperTimePartials->getVelocityScalingFactor( receiver );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( ( partialWrtMarsState - partialWrtMarsStateWithoutProperTime ).block( 0, 0, 1, 3 ) ),
properTimePartialWrtMarsPosition, 1.0E-9 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( -( partialWrtEarthState - partialWrtEarthStateWithoutProperTime ).block( 0, 0, 1, 3 ) ),
properTimePartialWrtEarthPosition, 1.0E-9 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( ( partialWrtMarsState - partialWrtMarsStateWithoutProperTime ).block( 0, 3, 1, 3 ) ),
properTimePartialWrtMarsVelocity, 1.0E-8 );
TUDAT_CHECK_MATRIX_CLOSE_FRACTION(
( -( partialWrtEarthState - partialWrtEarthStateWithoutProperTime ).block( 0, 3, 1, 3 ) ),
properTimePartialWrtEarthVelocity, 1.0E-8 );
}
}
BOOST_AUTO_TEST_SUITE_END( )
} // namespace unit_tests
} // namespace tudat
| 30,481 | 8,709 |
#include <bits/stdc++.h>
using namespace std;
template <typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; }
template <typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
using i64 = long long int;
const int INF = INT_MAX, MOD = 1e9 + 7;
const double EPS = 1e-9, PI = acos(-1);
const int dx[] = {0, 0, 0, -1, 1, -1, 1, 1, -1};
const int dy[] = {0, -1, 1, 0, 0, -1, 1, -1, 1};
struct Graph {
vector<vector<int>> adj;
vector<bool> marked;
vector<int> parent, level;
int n, m;
Graph(int _n = 0) {
init(_n);
}
void init(int _n) {
n = _n;
adj.resize(n + 1);
marked.resize(n + 1, false);
}
void addEdge(int u, int v) {
adj[u].push_back(v);
adj[v].push_back(u);
}
int solve() {
int ans = 0;
for (int node = 1; node <= n; node++) {
if (not marked[node]) {
dfs(node);
ans++;
}
}
return ans - 1;
}
void dfs(int node) {
marked[node] = true;
for (auto nei: adj[node])
if (not marked[nei])
dfs(nei);
}
};
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
/// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
ifstream cin("grarb.in");
ofstream cout("grarb.out");
int n, m;
cin >> n >> m;
Graph g(n);
g.m = m;
for (int i = 1; i <= m; i++) {
int u, v;
cin >> u >> v;
g.addEdge(u, v);
}
int add = g.solve();
int rem = m + add - (n - 1);
cout << rem << "\n" << add << "\n";
return 0;
} | 1,845 | 738 |
//#define CATCH_CONFIG_MAIN // This tells Catch to provide a main()
#define CATCH_CONFIG_RUNNER // We will provide a custom main
#include "catch.hpp"
// TODO: this import may ultimately be a bad idea, but it lets you paste an input deck in...
#include "deck/wrapper.h"
#include "src/species_advance/species_advance.h"
#include "src/vpic/vpic.h"
#include "compare_energies.h"
begin_globals {
double energies_interval;
double fields_interval;
double ehydro_interval;
double ihydro_interval;
double eparticle_interval;
double iparticle_interval;
double restart_interval;
};
std::string energy_file_name = "./energies";
std::string energy_gold_file_name = EXPAND_AND_STRINGIFY( GOLD_ENERGY_FILE );
void vpic_simulation::user_diagnostics() {
dump_energies(energy_file_name.c_str(), 1);
}
begin_initialization {
// AKA:
//void
//vpic_simulation::user_initialization( int num_cmdline_arguments,
//char ** cmdline_argument )
//{
// At this point, there is an empty grid and the random number generator is
// seeded with the rank. The grid, materials, species need to be defined.
// Then the initial non-zero fields need to be loaded at time level 0 and the
// particles (position and momentum both) need to be loaded at time level 0.
// Arguments can be passed from the command line to the input deck
// if( num_cmdline_arguments!=3 ) {
// sim_log( "Usage: " << cmdline_argument[0] << " mass_ratio seed" );
// abort(0);
// }
seed_entropy(1); //seed_entropy( atoi( cmdline_argument[2] ) );
// Diagnostic messages can be passed written (usually to stderr)
sim_log( "Computing simulation parameters");
// Define the system of units for this problem (natural units)
//double L = 1; // Length normalization (sheet thickness)
double de = 1; // Length normalization (electron inertial length)
double ec = 1; // Charge normalization
double me = 1; // Mass normalization
double c = 1; // Speed of light
double eps0 = 1; // Permittivity of space
// Physics parameters
double mi_me = 1836; //25; //atof(cmdline_argument[1]); // Ion mass / electron mass
double vthe = 0.25/sqrt(2.0); //0.0424264068711; //0.424264068711; // Electron thermal velocity
double vthi = 0.25/sqrt(2.0); //0.0424264068711; //0.424264068711; // Ion thermal velocity
double vthex =0.05/sqrt(2.0); //0.0141421356237; // 0.141421356237; // Electron thermal velocity in x-direction.
double vthix =0.05/sqrt(2.0); //0.0141421356237; // 0.141421356237;Ion thermal velocity in x-direction.
double n0 = 1.0; // Background plasma density
double b0 = 0.0; // In plane magnetic field.
double tauwpe = 200000; // simulation wpe's to run
// Numerical parameters
double topology_x = nproc(); // Number of domains in x, y, and z
double topology_y = 1;
double topology_z = 1; // For load balance, best to keep "1" or "2" for Harris sheet
double Lx = 2.09439510239320; //4.62*de; //6.7*de; //10.0*de; // How big should the box be in the x direction
double Ly = 1; //0.0721875*de; // How big should the box be in the y direction
double Lz = 1; //0.0721875*de; // How big should the box be in the z direction
double nx = 16; //64; //64; //32; // Global resolution in the x direction
double ny = 1; // Global resolution in the y direction
double nz = 1; //32; // Global resolution in the z direction
double nppc = 200; //800; //200; //2048; //1024; //128; // Average number of macro particles per cell (both species combined!)
double cfl_req = 0.99f; //0.99; // How close to Courant should we try to run
double wpedt_max = 0.36; // How big a timestep is allowed if Courant is not too restrictive
double damp = 0.0; // Level of radiation damping
// Derived quantities
double mi = me*mi_me; // Ion mass
double wpe = c/de; // electron plasma frequency
double wpi = wpe/sqrt(mi_me); // ion plasma frequency
double di = c/wpi; // ion inertial length
double hx = Lx/nx;
double hy = Ly/ny;
double hz = Lz/nz;
double Npe = n0*Ly*Lz*Lx; // Number physical electrons.
double Npi = Npe; // Number of physical ions in box
double Ne = nppc*nx*ny*nz; // total macro electrons in box
Ne = trunc_granular(Ne,nproc());
double Ni = Ne; // Total macro ions in box
double we = Npe/Ne; // Weight of a macro electron
double wi = Npi/Ni; // Weight of a macro ion
// Determine the timestep
double dg = courant_length(Lx,Ly,Lz,nx,ny,nz); // Courant length
double dt = cfl_req*dg/c; // Courant limited time step
// printf("in harris.cxx: dt=%.7f\n", dt);
// exit(1);
if( wpe*dt>wpedt_max ) dt=wpedt_max/wpe; // Override time step if plasma frequency limited
////////////////////////////////////////
// Setup high level simulation parmeters
num_step = 700; //4000; // int(tauwpe/(wpe*dt));
status_interval = 0; //2000;
sync_shared_interval = 0; //status_interval;
clean_div_e_interval = 0; //turn off cleaning (GY)//status_interval;
clean_div_b_interval = 0; //status_interval; //(GY)
global->energies_interval = 1; //status_interval;
global->fields_interval = status_interval;
global->ehydro_interval = status_interval;
global->ihydro_interval = status_interval;
global->eparticle_interval = status_interval; // Do not dump
global->iparticle_interval = status_interval; // Do not dump
global->restart_interval = status_interval; // Do not dump
///////////////////////////
// Setup the space and time
// Setup basic grid parameters
define_units( c, eps0 );
define_timestep( dt );
grid->dx = hx;
grid->dy = hy;
grid->dz = hz;
grid->dt = dt;
grid->cvac = c;
//grid->damp = damp;
// Parition a periodic box among the processors sliced uniformly along y
// define_periodic_grid( -0.5*Lx, 0, 0, // Low corner
// 0.5*Lx, Ly, Lz, // High corner
// nx, ny, nz, // Resolution
// 1, nproc(), 1 ); // Topology
define_periodic_grid( 0, -0.5*Ly, -0.5*Lz, // Low corner
Lx, 0.5*Ly, 0.5*Lz, // High corner
nx, ny, nz, // Resolution
topology_x, topology_y, topology_z); // Topology
// printf("in harris.cxx: g->neighbor[6*265]=%jd\n", grid->neighbor[6*265]);
// Override some of the boundary conditions to put a particle reflecting
// perfect electrical conductor on the -x and +x boundaries
// set_domain_field_bc( BOUNDARY(-1,0,0), pec_fields );
// set_domain_field_bc( BOUNDARY( 1,0,0), pec_fields );
// set_domain_particle_bc( BOUNDARY(-1,0,0), reflect_particles );
// set_domain_particle_bc( BOUNDARY( 1,0,0), reflect_particles );
define_material( "vacuum", 1 );
// Note: define_material defaults to isotropic materials with mu=1,sigma=0
// Tensor electronic, magnetic and conductive materials are supported
// though. See "shapes" for how to define them and assign them to regions.
// Also, space is initially filled with the first material defined.
// If you pass NULL to define field array, the standard field array will
// be used (if damp is not provided, no radiation damping will be used).
define_field_array( NULL, damp );
////////////////////
// Setup the species
// Allow 50% more local_particles in case of non-uniformity
// VPIC will pick the number of movers to use for each species
// Both species use out-of-place sorting
// species_t * ion = define_species( "ion", ec, mi, 1.5*Ni/nproc(), -1, 40, 1 );
// species_t * electron = define_species( "electron", -ec, me, 1.5*Ne/nproc(), -1, 20, 1 );
//species_t *electron = define_species("electron",-ec,me,2.4*Ne/nproc(),-1,25,0);
//species_t *ion = define_species("ion", ec,mi,2.4*Ne/nproc(),-1,25,0);
species_t *electron = define_species("electron",-ec,me,2.4*Ne/nproc(),-1,0,0); //turn off sorting (GY)
species_t *ion = define_species("ion", ec,mi,2.4*Ne/nproc(),-1,0,0); //(GY)
///////////////////////////////////////////////////
// Log diagnostic information about this simulation
sim_log( "***********************************************" );
sim_log ( "mi/me = " << mi_me );
sim_log ( "tauwpe = " << tauwpe );
sim_log ( "num_step = " << num_step );
sim_log ( "Lx/di = " << Lx/di );
sim_log ( "Lx/de = " << Lx/de );
sim_log ( "Ly/di = " << Ly/di );
sim_log ( "Ly/de = " << Ly/de );
sim_log ( "Lz/di = " << Lz/di );
sim_log ( "Lz/de = " << Lz/de );
sim_log ( "nx = " << nx );
sim_log ( "ny = " << ny );
sim_log ( "nz = " << nz );
sim_log ( "damp = " << damp );
sim_log ( "courant = " << c*dt/dg );
sim_log ( "nproc = " << nproc () );
sim_log ( "nppc = " << nppc );
sim_log ( " b0 = " << b0 );
sim_log ( " di = " << di );
sim_log ( " Ne = " << Ne );
sim_log ( "total # of particles = " << 2*Ne );
sim_log ( "dt*wpe = " << wpe*dt );
sim_log ( "dx/de = " << Lx/(de*nx) );
sim_log ( "dy/de = " << Ly/(de*ny) );
sim_log ( "dz/de = " << Lz/(de*nz) );
sim_log ( "dx/debye = " << (Lx/nx)/(vthe/wpe) );
sim_log ( "n0 = " << n0 );
sim_log ( "vthi/c = " << vthi/c );
sim_log ( "vthe/c = " << vthe/c );
sim_log( "" );
////////////////////////////
// Load fields and particles
// sim_log( "Loading fields" );
// set_region_field( everywhere, 0, 0, 0, // Electric field
// 0, -sn*b0*tanh(x/L), cs*b0*tanh(x/L) ); // Magnetic field
// Note: everywhere is a region that encompasses the entire simulation
// In general, regions are specied as logical equations (i.e. x>0 && x+y<2)
sim_log( "Loading particles" );
// Do a fast load of the particles
//seed_rand( rng_seed*nproc() + rank() ); //Generators desynchronized
double xmin = grid->x0 , xmax = grid->x0+(grid->dx)*(grid->nx);
double ymin = grid->y0 , ymax = grid->y0+(grid->dy)*(grid->ny);
double zmin = grid->z0 , zmax = grid->z0+(grid->dz)*(grid->nz);
sim_log( "-> Uniform Bi-Maxwellian" );
double n1,n2,n3;
repeat ( Ne/nproc() ) {
double x = uniform( rng(0), xmin, xmax );
double y = uniform( rng(0), ymin, ymax );
double z = uniform( rng(0), zmin, zmax );
n1 = normal(rng(0),0,vthex);
n2 = normal(rng(0),0,vthe );
n3 = normal(rng(0),0,vthe );
inject_particle( electron, x, y, z,
n1,
n2,
n3,we, 0, 0);
n1 = normal(rng(0),0,vthix);
n2 = normal(rng(0),0,vthi );
n3 = normal(rng(0),0,vthi );
inject_particle( ion, x, y, z,
n1,
n2,
n3,wi, 0 ,0 );
}
sim_log( "Finished loading particles" );
//exit(1);
// Upon completion of the initialization, the following occurs:
// - The synchronization error (tang E, norm B) is computed between domains
// and tang E / norm B are synchronized by averaging where discrepancies
// are encountered.
// - The initial divergence error of the magnetic field is computed and
// one pass of cleaning is done (for good measure)
// - The bound charge density necessary to give the simulation an initially
// clean divergence e is computed.
// - The particle momentum is uncentered from u_0 to u_{-1/2}
// - The user diagnostics are called on the initial state
// - The physics loop is started
//
// The physics loop consists of:
// - Advance particles from x_0,u_{-1/2} to x_1,u_{1/2}
// - User particle injection at x_{1-age}, u_{1/2} (use inject_particles)
// - User current injection (adjust field(x,y,z).jfx, jfy, jfz)
// - Advance B from B_0 to B_{1/2}
// - Advance E from E_0 to E_1
// - User field injection to E_1 (adjust field(x,y,z).ex,ey,ez,cbx,cby,cbz)
// - Advance B from B_{1/2} to B_1
// - (periodically) Divergence clean electric field
// - (periodically) Divergence clean magnetic field
// - (periodically) Synchronize shared tang e and norm b
// - Increment the time step
// - Call user diagnostics
// - (periodically) Print a status message
}
TEST_CASE( "Check if Weibel gives correct energy (within tol)", "[energy]" )
{
// Before we run this, we must make sure we remove the energy file
std::ofstream ofs;
ofs.open(energy_file_name, std::ofstream::out | std::ofstream::trunc);
ofs.close();
// Init and run sim
vpic_simulation simulation = vpic_simulation();
// TODO: We should do this in a safer manner
simulation.initialize( 0, NULL );
while( simulation.advance() );
simulation.finalize();
if( world_rank==0 ) log_printf( "normal exit\n" );
std::cout << "Comparing " << energy_file_name << " to " <<
energy_gold_file_name << std::endl;
// Compare energies to make sure everything worked out OK (within 1%)
const unsigned short e_mask = 0b0000001110;
const unsigned short b_mask = 0b0001110000;
const unsigned short particle_mask = 0b011000000;
SECTION("e_field") {
// Test the sum of the e_field
REQUIRE(
test_utils::compare_energies(energy_file_name, energy_gold_file_name,
0.3, e_mask, test_utils::FIELD_ENUM::Sum, 1, "Weibel.e.out")
);
}
SECTION("b_field") {
// Test the sum of the b_field
REQUIRE(
test_utils::compare_energies(energy_file_name, energy_gold_file_name,
0.03, b_mask, test_utils::FIELD_ENUM::Sum, 1, "Weibel.b.out")
);
}
SECTION("particle_energy") {
// Test particle energies individually
REQUIRE(
test_utils::compare_energies(energy_file_name, energy_gold_file_name,
0.01, particle_mask, test_utils::FIELD_ENUM::Sum, 1, "Weibel.p.out")
);
}
}
begin_particle_injection {
// No particle injection for this simulation
}
begin_current_injection {
// No current injection for this simulation
}
begin_field_injection {
// No field injection for this simulation
}
begin_particle_collisions{
// No collisions for this simulation
}
// Manually implement catch main
int main( int argc, char* argv[] )
{
// Setup
boot_services( &argc, &argv );
int result = Catch::Session().run( argc, argv );
// clean-up...
halt_services();
return result;
}
| 14,597 | 5,311 |
//----------------------------------------------------------------------------//
// Part of the Fox project, licensed under the MIT license.
// See LICENSE.txt in the project root for license information.
// File : Token.hpp
// Author : Pierre van Houtryve
//----------------------------------------------------------------------------//
// This file contains the Token class and TokenKind enum.
//----------------------------------------------------------------------------//
#pragma once
#include "Fox/AST/Identifier.hpp"
#include "Fox/Common/FoxTypes.hpp"
#include "Fox/Common/SourceLoc.hpp"
#include "Fox/Common/LLVM.hpp"
#include "llvm/ADT/SmallVector.h"
#include <cstddef>
#include <iosfwd>
namespace fox {
class ASTContext;
class DiagnosticEngine;
class SourceManager;
/// TokenKind
/// The different kind of tokens that exist
enum class TokenKind : std::uint8_t {
#define TOKEN(ID) ID,
#include "TokenKinds.def"
};
/// Token
/// Provides information about a lexed token: its string, location and kind.
struct Token {
public:
using Kind = TokenKind;
/// Creates an invalid token
Token() = default;
/// Creates a normal token
Token(Kind kind, string_view str, SourceRange range);
/// \returns true if this token's kind != TokenKind::Invalid
bool isValid() const;
/// \returns true if this token is the EOF token
bool isEOF() const;
/// \returns isValid()
operator bool() const;
/// \returns true if this token's kind matches "kind"
bool is(Kind kind) const;
/// dumps this token's data to out (without loc info)
void dump(std::ostream& out) const;
/// dumps this token's data to out (with loc info)
void dump(std::ostream& out, SourceManager& srcMgr,
bool printFileName) const;
/// The SourceRange of this token
const SourceRange range;
/// A string-view (in the file's buffer) of this token.
const string_view str;
/// The Kind of token this is
const Kind kind = Kind::Invalid;
};
/// A Vector of Tokens.
using TokenVector = SmallVector<Token, 4>;
}
| 2,205 | 612 |
#include "player.h"
#include "bmp_man.h"
extern Arduboy mArduboy;
void Player::move(int dx)
{
if (dx < 0) {
x += dx;
if (x <= -16) x = 127;
} else {
x += dx;
if (x >= 128) x = -15;
}
}
void Player::do_state()
{
switch (state) {
case MAN_ST_ATTACK:
count ++;
if (count >= 20) state = MAN_ST_STAND;
break;
case MAN_ST_DAMAGED:
count ++;
if (count >= 40) state = MAN_ST_STAND;
break;
default:
break;
}
}
void Player::draw(uint16_t anim)
{
int draw_x, draw_y;
draw_y = y;
draw_x = x / 4;
if (dir == DIR_RIGHT) {
switch (state) {
case MAN_ST_STAND:
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[0], 16, 16, WHITE);
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[1], 16, 16, BLACK);
break;
case MAN_ST_MOVE:
if ((draw_x & 2) == 0) {
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[0], 16, 16, WHITE);
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[1], 16, 16, BLACK);
} else {
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[2], 16, 16, WHITE);
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[3], 16, 16, BLACK);
}
break;
case MAN_ST_ATTACK:
mArduboy.drawBitmap(draw_x + 8, draw_y, man_bmp[4], 16, 16, WHITE);
mArduboy.drawBitmap(draw_x + 8, draw_y, man_bmp[5], 16, 16, BLACK);
break;
case MAN_ST_DAMAGED:
if ((anim & 8) == 0) {
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[0], 16, 16, WHITE);
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[1], 16, 16, BLACK);
}
break;
default:
break;
}
} else {
switch (state) {
case MAN_ST_STAND:
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[6], 16, 16, WHITE);
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[7], 16, 16, BLACK);
break;
case MAN_ST_MOVE:
if ((draw_x & 2) == 0) {
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[6], 16, 16, WHITE);
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[7], 16, 16, BLACK);
} else {
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[8], 16, 16, WHITE);
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[9], 16, 16, BLACK);
}
break;
case MAN_ST_ATTACK:
mArduboy.drawBitmap(draw_x - 8, draw_y, man_bmp[10], 16, 16, WHITE);
mArduboy.drawBitmap(draw_x - 8, draw_y, man_bmp[11], 16, 16, BLACK);
break;
case MAN_ST_DAMAGED:
if ((anim & 8) == 0) {
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[6], 16, 16, WHITE);
mArduboy.drawBitmap(draw_x, draw_y, man_bmp[7], 16, 16, BLACK);
}
break;
default:
break;
}
}
}
| 2,539 | 1,307 |
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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, version 2.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file build_vehicle_gui.cpp GUI for building vehicles. */
#include "stdafx.h"
#include "engine_base.h"
#include "engine_func.h"
#include "station_base.h"
#include "articulated_vehicles.h"
#include "textbuf_gui.h"
#include "command_func.h"
#include "company_func.h"
#include "vehicle_gui.h"
#include "newgrf_engine.h"
#include "newgrf_text.h"
#include "group.h"
#include "string_func.h"
#include "strings_func.h"
#include "window_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "widgets/dropdown_func.h"
#include "engine_gui.h"
#include "cargotype.h"
#include "core/geometry_func.hpp"
#include "table/strings.h"
/**
* Get the height of a single 'entry' in the engine lists.
* @param type the vehicle type to get the height of
* @return the height for the entry
*/
uint GetEngineListHeight(VehicleType type)
{
return max<uint>(FONT_HEIGHT_NORMAL + WD_MATRIX_TOP + WD_MATRIX_BOTTOM, GetVehicleHeight(type));
}
enum BuildVehicleWidgets {
BUILD_VEHICLE_WIDGET_CAPTION,
BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING,
BUILD_VEHICLE_WIDGET_SORT_DROPDOWN,
BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN,
BUILD_VEHICLE_WIDGET_LIST,
BUILD_VEHICLE_WIDGET_SCROLLBAR,
BUILD_VEHICLE_WIDGET_PANEL,
BUILD_VEHICLE_WIDGET_BUILD,
BUILD_VEHICLE_WIDGET_BUILD_SEL,
BUILD_VEHICLE_WIDGET_RENAME,
BUILD_VEHICLE_WIDGET_END
};
static const NWidgetPart _nested_build_vehicle_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_CLOSEBOX, COLOUR_GREY),
NWidget(WWT_CAPTION, COLOUR_GREY, BUILD_VEHICLE_WIDGET_CAPTION), SetDataTip(STR_WHITE_STRING, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
NWidget(WWT_SHADEBOX, COLOUR_GREY),
NWidget(WWT_STICKYBOX, COLOUR_GREY),
EndContainer(),
NWidget(WWT_PANEL, COLOUR_GREY),
NWidget(NWID_HORIZONTAL),
NWidget(NWID_VERTICAL),
NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING), SetDataTip(STR_BUTTON_SORT_BY, STR_TOOLTIP_SORT_ORDER), SetFill(1, 0),
NWidget(NWID_SPACER), SetFill(1, 1),
EndContainer(),
NWidget(NWID_VERTICAL),
NWidget(WWT_DROPDOWN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_SORT_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_SORT_CRITERIA),
NWidget(WWT_DROPDOWN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_FILTER_CRITERIA),
EndContainer(),
EndContainer(),
EndContainer(),
/* Vehicle list. */
NWidget(NWID_HORIZONTAL),
NWidget(WWT_MATRIX, COLOUR_GREY, BUILD_VEHICLE_WIDGET_LIST), SetResize(1, 1), SetFill(1, 0), SetDataTip(0x101, STR_NULL), SetScrollbar(BUILD_VEHICLE_WIDGET_SCROLLBAR),
NWidget(NWID_VSCROLLBAR, COLOUR_GREY, BUILD_VEHICLE_WIDGET_SCROLLBAR),
EndContainer(),
/* Panel with details. */
NWidget(WWT_PANEL, COLOUR_GREY, BUILD_VEHICLE_WIDGET_PANEL), SetMinimalSize(240, 122), SetResize(1, 0), EndContainer(),
/* Build/rename buttons, resize button. */
NWidget(NWID_HORIZONTAL),
NWidget(NWID_SELECTION, INVALID_COLOUR, BUILD_VEHICLE_WIDGET_BUILD_SEL),
NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_BUILD), SetResize(1, 0), SetFill(1, 0),
EndContainer(),
NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, BUILD_VEHICLE_WIDGET_RENAME), SetResize(1, 0), SetFill(1, 0),
NWidget(WWT_RESIZEBOX, COLOUR_GREY),
EndContainer(),
};
/** Special cargo filter criteria */
static const CargoID CF_ANY = CT_NO_REFIT; ///< Show all vehicles independent of carried cargo (i.e. no filtering)
static const CargoID CF_NONE = CT_INVALID; ///< Show only vehicles which do not carry cargo (e.g. train engines)
static bool _internal_sort_order; ///< false = descending, true = ascending
static byte _last_sort_criteria[] = {0, 0, 0, 0};
static bool _last_sort_order[] = {false, false, false, false};
static CargoID _last_filter_criteria[] = {CF_ANY, CF_ANY, CF_ANY, CF_ANY};
/**
* Determines order of engines by engineID
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL EngineNumberSorter(const EngineID *a, const EngineID *b)
{
int r = ListPositionOfEngine(*a) - ListPositionOfEngine(*b);
return _internal_sort_order ? -r : r;
}
/**
* Determines order of engines by introduction date
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL EngineIntroDateSorter(const EngineID *a, const EngineID *b)
{
const int va = Engine::Get(*a)->intro_date;
const int vb = Engine::Get(*b)->intro_date;
const int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/**
* Determines order of engines by name
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL EngineNameSorter(const EngineID *a, const EngineID *b)
{
static EngineID last_engine[2] = { INVALID_ENGINE, INVALID_ENGINE };
static char last_name[2][64] = { "\0", "\0" };
const EngineID va = *a;
const EngineID vb = *b;
if (va != last_engine[0]) {
last_engine[0] = va;
SetDParam(0, va);
GetString(last_name[0], STR_ENGINE_NAME, lastof(last_name[0]));
}
if (vb != last_engine[1]) {
last_engine[1] = vb;
SetDParam(0, vb);
GetString(last_name[1], STR_ENGINE_NAME, lastof(last_name[1]));
}
int r = strnatcmp(last_name[0], last_name[1]); // Sort by name (natural sorting).
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/**
* Determines order of engines by reliability
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL EngineReliabilitySorter(const EngineID *a, const EngineID *b)
{
const int va = Engine::Get(*a)->reliability;
const int vb = Engine::Get(*b)->reliability;
const int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/**
* Determines order of engines by purchase cost
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL EngineCostSorter(const EngineID *a, const EngineID *b)
{
Money va = Engine::Get(*a)->GetCost();
Money vb = Engine::Get(*b)->GetCost();
int r = ClampToI32(va - vb);
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/**
* Determines order of engines by speed
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL EngineSpeedSorter(const EngineID *a, const EngineID *b)
{
int va = Engine::Get(*a)->GetDisplayMaxSpeed();
int vb = Engine::Get(*b)->GetDisplayMaxSpeed();
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/**
* Determines order of engines by power
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL EnginePowerSorter(const EngineID *a, const EngineID *b)
{
int va = Engine::Get(*a)->GetPower();
int vb = Engine::Get(*b)->GetPower();
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/**
* Determines order of engines by tractive effort
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL EngineTractiveEffortSorter(const EngineID *a, const EngineID *b)
{
int va = Engine::Get(*a)->GetDisplayMaxTractiveEffort();
int vb = Engine::Get(*b)->GetDisplayMaxTractiveEffort();
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/**
* Determines order of engines by running costs
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL EngineRunningCostSorter(const EngineID *a, const EngineID *b)
{
Money va = Engine::Get(*a)->GetRunningCost();
Money vb = Engine::Get(*b)->GetRunningCost();
int r = ClampToI32(va - vb);
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/**
* Determines order of engines by running costs
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL EnginePowerVsRunningCostSorter(const EngineID *a, const EngineID *b)
{
const Engine *e_a = Engine::Get(*a);
const Engine *e_b = Engine::Get(*b);
/* Here we are using a few tricks to get the right sort.
* We want power/running cost, but since we usually got higher running cost than power and we store the result in an int,
* we will actually calculate cunning cost/power (to make it more than 1).
* Because of this, the return value have to be reversed as well and we return b - a instead of a - b.
* Another thing is that both power and running costs should be doubled for multiheaded engines.
* Since it would be multipling with 2 in both numerator and denumerator, it will even themselves out and we skip checking for multiheaded. */
Money va = (e_a->GetRunningCost()) / max(1U, (uint)e_a->GetPower());
Money vb = (e_b->GetRunningCost()) / max(1U, (uint)e_b->GetPower());
int r = ClampToI32(vb - va);
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/* Train sorting functions */
/**
* Determines order of train engines by capacity
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL TrainEngineCapacitySorter(const EngineID *a, const EngineID *b)
{
const RailVehicleInfo *rvi_a = RailVehInfo(*a);
const RailVehicleInfo *rvi_b = RailVehInfo(*b);
int va = GetTotalCapacityOfArticulatedParts(*a) * (rvi_a->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
int vb = GetTotalCapacityOfArticulatedParts(*b) * (rvi_b->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/**
* Determines order of train engines by engine / wagon
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL TrainEnginesThenWagonsSorter(const EngineID *a, const EngineID *b)
{
int val_a = (RailVehInfo(*a)->railveh_type == RAILVEH_WAGON ? 1 : 0);
int val_b = (RailVehInfo(*b)->railveh_type == RAILVEH_WAGON ? 1 : 0);
int r = val_a - val_b;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/* Road vehicle sorting functions */
/**
* Determines order of road vehicles by capacity
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL RoadVehEngineCapacitySorter(const EngineID *a, const EngineID *b)
{
int va = GetTotalCapacityOfArticulatedParts(*a);
int vb = GetTotalCapacityOfArticulatedParts(*b);
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/* Ship vehicle sorting functions */
/**
* Determines order of ships by capacity
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL ShipEngineCapacitySorter(const EngineID *a, const EngineID *b)
{
const Engine *e_a = Engine::Get(*a);
const Engine *e_b = Engine::Get(*b);
int va = e_a->GetDisplayDefaultCapacity();
int vb = e_b->GetDisplayDefaultCapacity();
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/* Aircraft sorting functions */
/**
* Determines order of aircraft by cargo
* @param *a first engine to compare
* @param *b second engine to compare
* @return for descending order: returns < 0 if a < b and > 0 for a > b. Vice versa for ascending order and 0 for equal
*/
static int CDECL AircraftEngineCargoSorter(const EngineID *a, const EngineID *b)
{
const Engine *e_a = Engine::Get(*a);
const Engine *e_b = Engine::Get(*b);
uint16 mail_a, mail_b;
int va = e_a->GetDisplayDefaultCapacity(&mail_a);
int vb = e_b->GetDisplayDefaultCapacity(&mail_b);
int r = va - vb;
if (r == 0) {
/* The planes have the same passenger capacity. Check mail capacity instead */
r = mail_a - mail_b;
if (r == 0) {
/* Use EngineID to sort instead since we want consistent sorting */
return EngineNumberSorter(a, b);
}
}
return _internal_sort_order ? -r : r;
}
static EngList_SortTypeFunction * const _sorter[][11] = {{
/* Trains */
&EngineNumberSorter,
&EngineCostSorter,
&EngineSpeedSorter,
&EnginePowerSorter,
&EngineTractiveEffortSorter,
&EngineIntroDateSorter,
&EngineNameSorter,
&EngineRunningCostSorter,
&EnginePowerVsRunningCostSorter,
&EngineReliabilitySorter,
&TrainEngineCapacitySorter,
}, {
/* Road vehicles */
&EngineNumberSorter,
&EngineCostSorter,
&EngineSpeedSorter,
&EnginePowerSorter,
&EngineTractiveEffortSorter,
&EngineIntroDateSorter,
&EngineNameSorter,
&EngineRunningCostSorter,
&EnginePowerVsRunningCostSorter,
&EngineReliabilitySorter,
&RoadVehEngineCapacitySorter,
}, {
/* Ships */
&EngineNumberSorter,
&EngineCostSorter,
&EngineSpeedSorter,
&EngineIntroDateSorter,
&EngineNameSorter,
&EngineRunningCostSorter,
&EngineReliabilitySorter,
&ShipEngineCapacitySorter,
}, {
/* Aircraft */
&EngineNumberSorter,
&EngineCostSorter,
&EngineSpeedSorter,
&EngineIntroDateSorter,
&EngineNameSorter,
&EngineRunningCostSorter,
&EngineReliabilitySorter,
&AircraftEngineCargoSorter,
}};
static const StringID _sort_listing[][12] = {{
/* Trains */
STR_SORT_BY_ENGINE_ID,
STR_SORT_BY_COST,
STR_SORT_BY_MAX_SPEED,
STR_SORT_BY_POWER,
STR_SORT_BY_TRACTIVE_EFFORT,
STR_SORT_BY_INTRO_DATE,
STR_SORT_BY_NAME,
STR_SORT_BY_RUNNING_COST,
STR_SORT_BY_POWER_VS_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_SORT_BY_CARGO_CAPACITY,
INVALID_STRING_ID
}, {
/* Road vehicles */
STR_SORT_BY_ENGINE_ID,
STR_SORT_BY_COST,
STR_SORT_BY_MAX_SPEED,
STR_SORT_BY_POWER,
STR_SORT_BY_TRACTIVE_EFFORT,
STR_SORT_BY_INTRO_DATE,
STR_SORT_BY_NAME,
STR_SORT_BY_RUNNING_COST,
STR_SORT_BY_POWER_VS_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_SORT_BY_CARGO_CAPACITY,
INVALID_STRING_ID
}, {
/* Ships */
STR_SORT_BY_ENGINE_ID,
STR_SORT_BY_COST,
STR_SORT_BY_MAX_SPEED,
STR_SORT_BY_INTRO_DATE,
STR_SORT_BY_NAME,
STR_SORT_BY_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_SORT_BY_CARGO_CAPACITY,
INVALID_STRING_ID
}, {
/* Aircraft */
STR_SORT_BY_ENGINE_ID,
STR_SORT_BY_COST,
STR_SORT_BY_MAX_SPEED,
STR_SORT_BY_INTRO_DATE,
STR_SORT_BY_NAME,
STR_SORT_BY_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_SORT_BY_CARGO_CAPACITY,
INVALID_STRING_ID
}};
/** Cargo filter functions */
static bool CDECL CargoFilter(const EngineID *eid, const CargoID cid)
{
if (cid == CF_ANY) return true;
uint32 refit_mask = GetUnionOfArticulatedRefitMasks(*eid, true);
return (cid == CF_NONE ? refit_mask == 0 : HasBit(refit_mask, cid));
}
static GUIEngineList::FilterFunction * const _filter_funcs[] = {
&CargoFilter,
};
static int DrawCargoCapacityInfo(int left, int right, int y, EngineID engine, bool refittable)
{
CargoArray cap = GetCapacityOfArticulatedParts(engine);
for (CargoID c = 0; c < NUM_CARGO; c++) {
if (cap[c] == 0) continue;
SetDParam(0, c);
SetDParam(1, cap[c]);
SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
y += FONT_HEIGHT_NORMAL;
/* Only show as refittable once */
refittable = false;
}
return y;
}
/* Draw rail wagon specific details */
static int DrawRailWagonPurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi)
{
const Engine *e = Engine::Get(engine_number);
/* Purchase cost */
SetDParam(0, e->GetCost());
DrawString(left, right, y, STR_PURCHASE_INFO_COST);
y += FONT_HEIGHT_NORMAL;
/* Wagon weight - (including cargo) */
uint weight = e->GetDisplayWeight();
SetDParam(0, weight);
uint cargo_weight = (e->CanCarryCargo() ? CargoSpec::Get(e->GetDefaultCargoType())->weight * e->GetDisplayDefaultCapacity() >> 4 : 0);
SetDParam(1, cargo_weight + weight);
DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT);
y += FONT_HEIGHT_NORMAL;
/* Wagon speed limit, displayed if above zero */
if (_settings_game.vehicle.wagon_speed_limits) {
uint max_speed = e->GetDisplayMaxSpeed();
if (max_speed > 0) {
SetDParam(0, max_speed);
DrawString(left, right, y, STR_PURCHASE_INFO_SPEED);
y += FONT_HEIGHT_NORMAL;
}
}
/* Running cost */
if (rvi->running_cost_class != INVALID_PRICE) {
SetDParam(0, e->GetRunningCost());
DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
y += FONT_HEIGHT_NORMAL;
}
return y;
}
/* Draw locomotive specific details */
static int DrawRailEnginePurchaseInfo(int left, int right, int y, EngineID engine_number, const RailVehicleInfo *rvi)
{
const Engine *e = Engine::Get(engine_number);
/* Purchase Cost - Engine weight */
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayWeight());
DrawString(left, right, y, STR_PURCHASE_INFO_COST_WEIGHT);
y += FONT_HEIGHT_NORMAL;
/* Max speed - Engine power */
SetDParam(0, e->GetDisplayMaxSpeed());
SetDParam(1, e->GetPower());
DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER);
y += FONT_HEIGHT_NORMAL;
/* Max tractive effort - not applicable if old acceleration or maglev */
if (_settings_game.vehicle.train_acceleration_model != AM_ORIGINAL && GetRailTypeInfo(rvi->railtype)->acceleration_type != 2) {
SetDParam(0, e->GetDisplayMaxTractiveEffort());
DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE);
y += FONT_HEIGHT_NORMAL;
}
/* Running cost */
if (rvi->running_cost_class != INVALID_PRICE) {
SetDParam(0, e->GetRunningCost());
DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
y += FONT_HEIGHT_NORMAL;
}
/* Powered wagons power - Powered wagons extra weight */
if (rvi->pow_wag_power != 0) {
SetDParam(0, rvi->pow_wag_power);
SetDParam(1, rvi->pow_wag_weight);
DrawString(left, right, y, STR_PURCHASE_INFO_PWAGPOWER_PWAGWEIGHT);
y += FONT_HEIGHT_NORMAL;
}
return y;
}
/* Draw road vehicle specific details */
static int DrawRoadVehPurchaseInfo(int left, int right, int y, EngineID engine_number)
{
const Engine *e = Engine::Get(engine_number);
if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) {
/* Purchase Cost */
SetDParam(0, e->GetCost());
DrawString(left, right, y, STR_PURCHASE_INFO_COST);
y += FONT_HEIGHT_NORMAL;
/* Road vehicle weight - (including cargo) */
int16 weight = e->GetDisplayWeight();
SetDParam(0, weight);
uint cargo_weight = CargoSpec::Get(e->GetDefaultCargoType())->weight * GetTotalCapacityOfArticulatedParts(engine_number) / 16;
SetDParam(1, cargo_weight + weight);
DrawString(left, right, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT);
y += FONT_HEIGHT_NORMAL;
/* Max speed - Engine power */
SetDParam(0, e->GetDisplayMaxSpeed());
SetDParam(1, e->GetPower());
DrawString(left, right, y, STR_PURCHASE_INFO_SPEED_POWER);
y += FONT_HEIGHT_NORMAL;
/* Max tractive effort */
SetDParam(0, e->GetDisplayMaxTractiveEffort());
DrawString(left, right, y, STR_PURCHASE_INFO_MAX_TE);
y += FONT_HEIGHT_NORMAL;
} else {
/* Purchase cost - Max speed */
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayMaxSpeed());
DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
y += FONT_HEIGHT_NORMAL;
}
/* Running cost */
SetDParam(0, e->GetRunningCost());
DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
y += FONT_HEIGHT_NORMAL;
return y;
}
/* Draw ship specific details */
static int DrawShipPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable)
{
const Engine *e = Engine::Get(engine_number);
/* Purchase cost - Max speed */
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayMaxSpeed());
DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
y += FONT_HEIGHT_NORMAL;
/* Cargo type + capacity */
SetDParam(0, e->GetDefaultCargoType());
SetDParam(1, e->GetDisplayDefaultCapacity());
SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
y += FONT_HEIGHT_NORMAL;
/* Running cost */
SetDParam(0, e->GetRunningCost());
DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
y += FONT_HEIGHT_NORMAL;
return y;
}
/* Draw aircraft specific details */
static int DrawAircraftPurchaseInfo(int left, int right, int y, EngineID engine_number, bool refittable)
{
const Engine *e = Engine::Get(engine_number);
CargoID cargo = e->GetDefaultCargoType();
/* Purchase cost - Max speed */
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayMaxSpeed());
DrawString(left, right, y, STR_PURCHASE_INFO_COST_SPEED);
y += FONT_HEIGHT_NORMAL;
/* Cargo capacity */
uint16 mail_capacity;
uint capacity = e->GetDisplayDefaultCapacity(&mail_capacity);
if (mail_capacity > 0) {
SetDParam(0, cargo);
SetDParam(1, capacity);
SetDParam(2, CT_MAIL);
SetDParam(3, mail_capacity);
DrawString(left, right, y, STR_PURCHASE_INFO_AIRCRAFT_CAPACITY);
} else {
/* Note, if the default capacity is selected by the refit capacity
* callback, then the capacity shown is likely to be incorrect. */
SetDParam(0, cargo);
SetDParam(1, capacity);
SetDParam(2, refittable ? STR_PURCHASE_INFO_REFITTABLE : STR_EMPTY);
DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
}
y += FONT_HEIGHT_NORMAL;
/* Running cost */
SetDParam(0, e->GetRunningCost());
DrawString(left, right, y, STR_PURCHASE_INFO_RUNNINGCOST);
y += FONT_HEIGHT_NORMAL;
return y;
}
/**
* Display additional text from NewGRF in the purchase information window
* @param left Left border of text bounding box
* @param right Right border of text bounding box
* @param y Top border of text bounding box
* @param engine Engine to query the additional purchase information for
* @return Bottom border of text bounding box
*/
static uint ShowAdditionalText(int left, int right, int y, EngineID engine)
{
uint16 callback = GetVehicleCallback(CBID_VEHICLE_ADDITIONAL_TEXT, 0, 0, engine, NULL);
if (callback == CALLBACK_FAILED) return y;
/* STR_BLACK_STRING is used to start the string with {BLACK} */
SetDParam(0, GetGRFStringID(GetEngineGRFID(engine), 0xD000 + callback));
PrepareTextRefStackUsage(0);
uint result = DrawStringMultiLine(left, right, y, INT32_MAX, STR_BLACK_STRING);
StopTextRefStackUsage();
return result;
}
/**
* Draw the purchase info details of a vehicle at a given location.
* @param left,right,y location where to draw the info
* @param engine_number the engine of which to draw the info of
* @return y after drawing all the text
*/
int DrawVehiclePurchaseInfo(int left, int right, int y, EngineID engine_number)
{
const Engine *e = Engine::Get(engine_number);
YearMonthDay ymd;
ConvertDateToYMD(e->intro_date, &ymd);
bool refittable = IsArticulatedVehicleRefittable(engine_number);
bool articulated_cargo = false;
switch (e->type) {
default: NOT_REACHED();
case VEH_TRAIN:
if (e->u.rail.railveh_type == RAILVEH_WAGON) {
y = DrawRailWagonPurchaseInfo(left, right, y, engine_number, &e->u.rail);
} else {
y = DrawRailEnginePurchaseInfo(left, right, y, engine_number, &e->u.rail);
}
articulated_cargo = true;
break;
case VEH_ROAD:
y = DrawRoadVehPurchaseInfo(left, right, y, engine_number);
articulated_cargo = true;
break;
case VEH_SHIP:
y = DrawShipPurchaseInfo(left, right, y, engine_number, refittable);
break;
case VEH_AIRCRAFT:
y = DrawAircraftPurchaseInfo(left, right, y, engine_number, refittable);
break;
}
if (articulated_cargo) {
/* Cargo type + capacity, or N/A */
int new_y = DrawCargoCapacityInfo(left, right, y, engine_number, refittable);
if (new_y == y) {
SetDParam(0, CT_INVALID);
SetDParam(2, STR_EMPTY);
DrawString(left, right, y, STR_PURCHASE_INFO_CAPACITY);
y += FONT_HEIGHT_NORMAL;
} else {
y = new_y;
}
}
/* Draw details that apply to all types except rail wagons. */
if (e->type != VEH_TRAIN || e->u.rail.railveh_type != RAILVEH_WAGON) {
/* Design date - Life length */
SetDParam(0, ymd.year);
SetDParam(1, e->GetLifeLengthInDays() / DAYS_IN_LEAP_YEAR);
DrawString(left, right, y, STR_PURCHASE_INFO_DESIGNED_LIFE);
y += FONT_HEIGHT_NORMAL;
/* Reliability */
SetDParam(0, ToPercent16(e->reliability));
DrawString(left, right, y, STR_PURCHASE_INFO_RELIABILITY);
y += FONT_HEIGHT_NORMAL;
}
/* Additional text from NewGRF */
y = ShowAdditionalText(left, right, y, engine_number);
if (refittable) y = ShowRefitOptionsList(left, right, y, engine_number);
return y;
}
/**
* Engine drawing loop
* @param type Type of vehicle (VEH_*)
* @param l The left most location of the list
* @param r The right most location of the list
* @param y The top most location of the list
* @param eng_list What engines to draw
* @param min where to start in the list
* @param max where in the list to end
* @param selected_id what engine to highlight as selected, if any
* @param show_count Whether to show the amount of engines or not
* @param selected_group the group to list the engines of
*/
void DrawEngineList(VehicleType type, int l, int r, int y, const GUIEngineList *eng_list, uint16 min, uint16 max, EngineID selected_id, bool show_count, GroupID selected_group)
{
static const int sprite_widths[] = { 60, 60, 76, 67 };
static const int sprite_y_offsets[] = { -1, -1, -2, -2 };
/* Obligatory sanity checks! */
assert((uint)type < lengthof(sprite_widths));
assert_compile(lengthof(sprite_y_offsets) == lengthof(sprite_widths));
assert(max <= eng_list->Length());
bool rtl = _current_text_dir == TD_RTL;
int step_size = GetEngineListHeight(type);
int sprite_width = sprite_widths[type];
int sprite_x = (rtl ? r - sprite_width / 2 : l + sprite_width / 2) - 1;
int sprite_y_offset = sprite_y_offsets[type] + step_size / 2;
int text_left = l + (rtl ? WD_FRAMERECT_LEFT : sprite_width);
int text_right = r - (rtl ? sprite_width : WD_FRAMERECT_RIGHT);
int normal_text_y_offset = (step_size - FONT_HEIGHT_NORMAL) / 2;
int small_text_y_offset = step_size - FONT_HEIGHT_SMALL - WD_FRAMERECT_BOTTOM - 1;
for (; min < max; min++, y += step_size) {
const EngineID engine = (*eng_list)[min];
/* Note: num_engines is only used in the autoreplace GUI, so it is correct to use _local_company here. */
const uint num_engines = GetGroupNumEngines(_local_company, selected_group, engine);
SetDParam(0, engine);
DrawString(text_left, text_right, y + normal_text_y_offset, STR_ENGINE_NAME, engine == selected_id ? TC_WHITE : TC_BLACK);
DrawVehicleEngine(l, r, sprite_x, y + sprite_y_offset, engine, (show_count && num_engines == 0) ? PALETTE_CRASH : GetEnginePalette(engine, _local_company));
if (show_count) {
SetDParam(0, num_engines);
DrawString(text_left, text_right, y + small_text_y_offset, STR_TINY_BLACK_COMA, TC_FROMSTRING, SA_RIGHT);
}
}
}
struct BuildVehicleWindow : Window {
VehicleType vehicle_type;
union {
RailTypeByte railtype;
RoadTypes roadtypes;
} filter;
bool descending_sort_order;
byte sort_criteria;
bool listview_mode;
EngineID sel_engine;
EngineID rename_engine;
GUIEngineList eng_list;
CargoID cargo_filter[NUM_CARGO + 2]; ///< Available cargo filters; CargoID or CF_ANY or CF_NONE
StringID cargo_filter_texts[NUM_CARGO + 3]; ///< Texts for filter_cargo, terminated by INVALID_STRING_ID
byte cargo_filter_criteria; ///< Selected cargo filter
int details_height; ///< Minimal needed height of the details panels (found so far).
Scrollbar *vscroll;
BuildVehicleWindow(const WindowDesc *desc, TileIndex tile, VehicleType type) : Window()
{
this->vehicle_type = type;
this->window_number = tile == INVALID_TILE ? (int)type : tile;
this->sel_engine = INVALID_ENGINE;
this->sort_criteria = _last_sort_criteria[type];
this->descending_sort_order = _last_sort_order[type];
switch (type) {
default: NOT_REACHED();
case VEH_TRAIN:
this->filter.railtype = (tile == INVALID_TILE) ? RAILTYPE_END : GetRailType(tile);
break;
case VEH_ROAD:
this->filter.roadtypes = (tile == INVALID_TILE) ? ROADTYPES_ALL : GetRoadTypes(tile);
case VEH_SHIP:
case VEH_AIRCRAFT:
break;
}
this->listview_mode = (this->window_number <= VEH_END);
this->CreateNestedTree(desc);
this->vscroll = this->GetScrollbar(BUILD_VEHICLE_WIDGET_SCROLLBAR);
/* If we are just viewing the list of vehicles, we do not need the Build button.
* So we just hide it, and enlarge the Rename buton by the now vacant place. */
if (this->listview_mode) this->GetWidget<NWidgetStacked>(BUILD_VEHICLE_WIDGET_BUILD_SEL)->SetDisplayedPlane(SZSP_NONE);
NWidgetCore *widget = this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_LIST);
widget->tool_tip = STR_BUY_VEHICLE_TRAIN_LIST_TOOLTIP + type;
widget = this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_BUILD);
widget->widget_data = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_BUTTON + type;
widget->tool_tip = STR_BUY_VEHICLE_TRAIN_BUY_VEHICLE_TOOLTIP + type;
widget = this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_RENAME);
widget->widget_data = STR_BUY_VEHICLE_TRAIN_RENAME_BUTTON + type;
widget->tool_tip = STR_BUY_VEHICLE_TRAIN_RENAME_TOOLTIP + type;
this->details_height = ((this->vehicle_type == VEH_TRAIN) ? 10 : 9) * FONT_HEIGHT_NORMAL + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM;
this->FinishInitNested(desc, tile == INVALID_TILE ? (int)type : tile);
this->owner = (tile != INVALID_TILE) ? GetTileOwner(tile) : _local_company;
this->eng_list.ForceRebuild();
this->GenerateBuildList(); // generate the list, since we need it in the next line
/* Select the first engine in the list as default when opening the window */
if (this->eng_list.Length() > 0) this->sel_engine = this->eng_list[0];
}
/** Populate the filter list and set the cargo filter criteria. */
void SetCargoFilterArray()
{
uint filter_items = 0;
/* Add item for disabling filtering. */
this->cargo_filter[filter_items] = CF_ANY;
this->cargo_filter_texts[filter_items] = STR_PURCHASE_INFO_ALL_TYPES;
filter_items++;
/* Add item for vehicles not carrying anything, e.g. train engines.
* This could also be useful for eyecandy vehicles of other types, but is likely too confusing for joe, */
if (this->vehicle_type == VEH_TRAIN) {
this->cargo_filter[filter_items] = CF_NONE;
this->cargo_filter_texts[filter_items] = STR_LAND_AREA_INFORMATION_LOCAL_AUTHORITY_NONE;
filter_items++;
}
/* Collect available cargo types for filtering. */
const CargoSpec *cs;
FOR_ALL_SORTED_STANDARD_CARGOSPECS(cs) {
this->cargo_filter[filter_items] = cs->Index();
this->cargo_filter_texts[filter_items] = cs->name;
filter_items++;
}
/* Terminate the filter list. */
this->cargo_filter_texts[filter_items] = INVALID_STRING_ID;
/* If not found, the cargo criteria will be set to all cargos. */
this->cargo_filter_criteria = 0;
/* Find the last cargo filter criteria. */
for (uint i = 0; i < filter_items; i++) {
if (this->cargo_filter[i] == _last_filter_criteria[this->vehicle_type]) {
this->cargo_filter_criteria = i;
break;
}
}
this->eng_list.SetFilterFuncs(_filter_funcs);
this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY);
}
void OnInit()
{
this->SetCargoFilterArray();
}
/** Filter the engine list against the currently selected cargo filter */
void FilterEngineList()
{
this->eng_list.Filter(this->cargo_filter[this->cargo_filter_criteria]);
if (0 == this->eng_list.Length()) { // no engine passed through the filter, invalidate the previously selected engine
this->sel_engine = INVALID_ENGINE;
} else if (!this->eng_list.Contains(this->sel_engine)) { // previously selected engine didn't pass the filter, select the first engine of the list
this->sel_engine = this->eng_list[0];
}
}
/** Filter a single engine */
bool FilterSingleEngine(EngineID eid)
{
CargoID filter_type = this->cargo_filter[this->cargo_filter_criteria];
return (filter_type == CF_ANY || CargoFilter(&eid, filter_type));
}
/* Figure out what train EngineIDs to put in the list */
void GenerateBuildTrainList()
{
EngineID sel_id = INVALID_ENGINE;
int num_engines = 0;
int num_wagons = 0;
this->filter.railtype = (this->listview_mode) ? RAILTYPE_END : GetRailType(this->window_number);
this->eng_list.Clear();
/* Make list of all available train engines and wagons.
* Also check to see if the previously selected engine is still available,
* and if not, reset selection to INVALID_ENGINE. This could be the case
* when engines become obsolete and are removed */
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) {
EngineID eid = e->index;
const RailVehicleInfo *rvi = &e->u.rail;
if (this->filter.railtype != RAILTYPE_END && !HasPowerOnRail(rvi->railtype, this->filter.railtype)) continue;
if (!IsEngineBuildable(eid, VEH_TRAIN, _local_company)) continue;
/* Filter now! So num_engines and num_wagons is valid */
if (!FilterSingleEngine(eid)) continue;
*this->eng_list.Append() = eid;
if (rvi->railveh_type != RAILVEH_WAGON) {
num_engines++;
} else {
num_wagons++;
}
if (eid == this->sel_engine) sel_id = eid;
}
this->sel_engine = sel_id;
/* make engines first, and then wagons, sorted by ListPositionOfEngine() */
_internal_sort_order = false;
EngList_Sort(&this->eng_list, TrainEnginesThenWagonsSorter);
/* and then sort engines */
_internal_sort_order = this->descending_sort_order;
EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], 0, num_engines);
/* and finally sort wagons */
EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], num_engines, num_wagons);
}
/* Figure out what road vehicle EngineIDs to put in the list */
void GenerateBuildRoadVehList()
{
EngineID sel_id = INVALID_ENGINE;
this->eng_list.Clear();
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) {
EngineID eid = e->index;
if (!IsEngineBuildable(eid, VEH_ROAD, _local_company)) continue;
if (!HasBit(this->filter.roadtypes, HasBit(EngInfo(eid)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD)) continue;
*this->eng_list.Append() = eid;
if (eid == this->sel_engine) sel_id = eid;
}
this->sel_engine = sel_id;
}
/* Figure out what ship EngineIDs to put in the list */
void GenerateBuildShipList()
{
EngineID sel_id = INVALID_ENGINE;
this->eng_list.Clear();
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, VEH_SHIP) {
EngineID eid = e->index;
if (!IsEngineBuildable(eid, VEH_SHIP, _local_company)) continue;
*this->eng_list.Append() = eid;
if (eid == this->sel_engine) sel_id = eid;
}
this->sel_engine = sel_id;
}
/* Figure out what aircraft EngineIDs to put in the list */
void GenerateBuildAircraftList()
{
EngineID sel_id = INVALID_ENGINE;
this->eng_list.Clear();
const Station *st = this->listview_mode ? NULL : Station::GetByTile(this->window_number);
/* Make list of all available planes.
* Also check to see if the previously selected plane is still available,
* and if not, reset selection to INVALID_ENGINE. This could be the case
* when planes become obsolete and are removed */
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, VEH_AIRCRAFT) {
EngineID eid = e->index;
if (!IsEngineBuildable(eid, VEH_AIRCRAFT, _local_company)) continue;
/* First VEH_END window_numbers are fake to allow a window open for all different types at once */
if (!this->listview_mode && !CanVehicleUseStation(eid, st)) continue;
*this->eng_list.Append() = eid;
if (eid == this->sel_engine) sel_id = eid;
}
this->sel_engine = sel_id;
}
/* Generate the list of vehicles */
void GenerateBuildList()
{
if (!this->eng_list.NeedRebuild()) return;
switch (this->vehicle_type) {
default: NOT_REACHED();
case VEH_TRAIN:
this->GenerateBuildTrainList();
this->eng_list.Compact();
this->eng_list.RebuildDone();
return; // trains should not reach the last sorting
case VEH_ROAD:
this->GenerateBuildRoadVehList();
break;
case VEH_SHIP:
this->GenerateBuildShipList();
break;
case VEH_AIRCRAFT:
this->GenerateBuildAircraftList();
break;
}
this->FilterEngineList();
_internal_sort_order = this->descending_sort_order;
EngList_Sort(&this->eng_list, _sorter[this->vehicle_type][this->sort_criteria]);
this->eng_list.Compact();
this->eng_list.RebuildDone();
}
void OnClick(Point pt, int widget, int click_count)
{
switch (widget) {
case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING:
this->descending_sort_order ^= true;
_last_sort_order[this->vehicle_type] = this->descending_sort_order;
this->eng_list.ForceRebuild();
this->SetDirty();
break;
case BUILD_VEHICLE_WIDGET_LIST: {
uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, BUILD_VEHICLE_WIDGET_LIST);
size_t num_items = this->eng_list.Length();
this->sel_engine = (i < num_items) ? this->eng_list[i] : INVALID_ENGINE;
this->SetDirty();
if (click_count > 1 && !this->listview_mode) this->OnClick(pt, BUILD_VEHICLE_WIDGET_BUILD, 1);
break;
}
case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN: { // Select sorting criteria dropdown menu
uint32 hidden_mask = 0;
/* Disable sorting by power or tractive effort when the original acceleration model for road vehicles is being used. */
if (this->vehicle_type == VEH_ROAD &&
_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL) {
SetBit(hidden_mask, 3); // power
SetBit(hidden_mask, 4); // tractive effort
SetBit(hidden_mask, 8); // power by running costs
}
/* Disable sorting by tractive effort when the original acceleration model for trains is being used. */
if (this->vehicle_type == VEH_TRAIN &&
_settings_game.vehicle.train_acceleration_model == AM_ORIGINAL) {
SetBit(hidden_mask, 4); // tractive effort
}
ShowDropDownMenu(this, _sort_listing[this->vehicle_type], this->sort_criteria, BUILD_VEHICLE_WIDGET_SORT_DROPDOWN, 0, hidden_mask);
break;
}
case BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN: // Select cargo filtering criteria dropdown menu
ShowDropDownMenu(this, this->cargo_filter_texts, this->cargo_filter_criteria, BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN, 0, 0);
break;
case BUILD_VEHICLE_WIDGET_BUILD: {
EngineID sel_eng = this->sel_engine;
if (sel_eng != INVALID_ENGINE) {
CommandCallback *callback = (this->vehicle_type == VEH_TRAIN && RailVehInfo(sel_eng)->railveh_type == RAILVEH_WAGON) ? CcBuildWagon : CcBuildPrimaryVehicle;
DoCommandP(this->window_number, sel_eng, 0, GetCmdBuildVeh(this->vehicle_type), callback);
}
break;
}
case BUILD_VEHICLE_WIDGET_RENAME: {
EngineID sel_eng = this->sel_engine;
if (sel_eng != INVALID_ENGINE) {
this->rename_engine = sel_eng;
SetDParam(0, sel_eng);
ShowQueryString(STR_ENGINE_NAME, STR_QUERY_RENAME_TRAIN_TYPE_CAPTION + this->vehicle_type, MAX_LENGTH_ENGINE_NAME_CHARS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT | QSF_LEN_IN_CHARS);
}
break;
}
}
}
/**
* Some data on this window has become invalid.
* @param data Information about the changed data.
* @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
*/
virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
{
if (!gui_scope) return;
/* When switching to original acceleration model for road vehicles, clear the selected sort criteria if it is not available now. */
if (this->vehicle_type == VEH_ROAD &&
_settings_game.vehicle.roadveh_acceleration_model == AM_ORIGINAL &&
this->sort_criteria > 7) {
this->sort_criteria = 0;
_last_sort_criteria[VEH_ROAD] = 0;
}
this->eng_list.ForceRebuild();
}
virtual void SetStringParameters(int widget) const
{
switch (widget) {
case BUILD_VEHICLE_WIDGET_CAPTION:
if (this->vehicle_type == VEH_TRAIN && !this->listview_mode) {
const RailtypeInfo *rti = GetRailTypeInfo(this->filter.railtype);
SetDParam(0, rti->strings.build_caption);
} else {
SetDParam(0, (this->listview_mode ? STR_VEHICLE_LIST_AVAILABLE_TRAINS : STR_BUY_VEHICLE_TRAIN_ALL_CAPTION) + this->vehicle_type);
}
break;
case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN:
SetDParam(0, _sort_listing[this->vehicle_type][this->sort_criteria]);
break;
case BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN:
SetDParam(0, this->cargo_filter_texts[this->cargo_filter_criteria]);
}
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
{
switch (widget) {
case BUILD_VEHICLE_WIDGET_LIST:
resize->height = GetEngineListHeight(this->vehicle_type);
size->height = 3 * resize->height;
break;
case BUILD_VEHICLE_WIDGET_PANEL:
size->height = this->details_height;
break;
case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING: {
Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
d.width += padding.width + WD_SORTBUTTON_ARROW_WIDTH * 2; // Doubled since the string is centred and it also looks better.
d.height += padding.height;
*size = maxdim(*size, d);
break;
}
}
}
virtual void DrawWidget(const Rect &r, int widget) const
{
switch (widget) {
case BUILD_VEHICLE_WIDGET_LIST:
DrawEngineList(this->vehicle_type, r.left + WD_FRAMERECT_LEFT, r.right - WD_FRAMERECT_RIGHT, r.top + WD_FRAMERECT_TOP, &this->eng_list, this->vscroll->GetPosition(), min(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->eng_list.Length()), this->sel_engine, false, DEFAULT_GROUP);
break;
case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING:
this->DrawSortButtonState(BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING, this->descending_sort_order ? SBS_DOWN : SBS_UP);
break;
}
}
virtual void OnPaint()
{
this->GenerateBuildList();
this->vscroll->SetCount(this->eng_list.Length());
this->DrawWidgets();
if (!this->IsShaded()) {
int needed_height = this->details_height;
/* Draw details panels. */
if (this->sel_engine != INVALID_ENGINE) {
NWidgetBase *nwi = this->GetWidget<NWidgetBase>(BUILD_VEHICLE_WIDGET_PANEL);
int text_end = DrawVehiclePurchaseInfo(nwi->pos_x + WD_FRAMETEXT_LEFT, nwi->pos_x + nwi->current_x - WD_FRAMETEXT_RIGHT,
nwi->pos_y + WD_FRAMERECT_TOP, this->sel_engine);
needed_height = max(needed_height, text_end - (int)nwi->pos_y + WD_FRAMERECT_BOTTOM);
}
if (needed_height != this->details_height) { // Details window are not high enough, enlarge them.
int resize = needed_height - this->details_height;
this->details_height = needed_height;
this->ReInit(0, resize);
return;
}
}
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
DoCommandP(0, this->rename_engine, 0, CMD_RENAME_ENGINE | CMD_MSG(STR_ERROR_CAN_T_RENAME_TRAIN_TYPE + this->vehicle_type), NULL, str);
}
virtual void OnDropdownSelect(int widget, int index)
{
switch (widget) {
case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN:
if (this->sort_criteria != index) {
this->sort_criteria = index;
_last_sort_criteria[this->vehicle_type] = this->sort_criteria;
this->eng_list.ForceRebuild();
}
break;
case BUILD_VEHICLE_WIDGET_CARGO_FILTER_DROPDOWN: // Select a cargo filter criteria
if (this->cargo_filter_criteria != index) {
this->cargo_filter_criteria = index;
_last_filter_criteria[this->vehicle_type] = this->cargo_filter[this->cargo_filter_criteria];
/* deactivate filter if criteria is 'Show All', activate it otherwise */
this->eng_list.SetFilterState(this->cargo_filter[this->cargo_filter_criteria] != CF_ANY);
this->eng_list.ForceRebuild();
}
break;
}
this->SetDirty();
}
virtual void OnResize()
{
this->vscroll->SetCapacityFromWidget(this, BUILD_VEHICLE_WIDGET_LIST);
this->GetWidget<NWidgetCore>(BUILD_VEHICLE_WIDGET_LIST)->widget_data = (this->vscroll->GetCapacity() << MAT_ROW_START) + (1 << MAT_COL_START);
}
};
static const WindowDesc _build_vehicle_desc(
WDP_AUTO, 240, 268,
WC_BUILD_VEHICLE, WC_NONE,
WDF_UNCLICK_BUTTONS | WDF_CONSTRUCTION,
_nested_build_vehicle_widgets, lengthof(_nested_build_vehicle_widgets)
);
void ShowBuildVehicleWindow(TileIndex tile, VehicleType type)
{
/* We want to be able to open both Available Train as Available Ships,
* so if tile == INVALID_TILE (Available XXX Window), use 'type' as unique number.
* As it always is a low value, it won't collide with any real tile
* number. */
uint num = (tile == INVALID_TILE) ? (int)type : tile;
assert(IsCompanyBuildableVehicleType(type));
DeleteWindowById(WC_BUILD_VEHICLE, num);
new BuildVehicleWindow(&_build_vehicle_desc, tile, type);
}
| 47,941 | 19,081 |
#include "rack.hpp"
using namespace rack;
extern Plugin *pluginInstance;
extern Model *modelBPMLFO;
extern Model *modelBPMLFO2;
extern Model *modelBPMLFOPhaseExpander;
extern Model *modelDamianLillard;
extern Model *modelEverlastingGlottalStopper;
extern Model *modelHairPick;
extern Model *modelLissajousLFO;
extern Model *modelMrBlueSky;
extern Model *modelTheOneRingModulator;
extern Model *modelPhasedLockedLoop;
extern Model *modelPortlandWeather;
extern Model *modelProbablyNote;
//extern Model *modelProbablyNoteArabic;
extern Model *modelProbablyNoteBP;
//extern Model *modelProbablyNoteIndian;
extern Model *modelPNChordExpander;
extern Model *modelQuadAlgorithmicRhythm;
extern Model *modelQARGrooveExpander;
extern Model *modelQARProbabilityExpander;
extern Model *modelQuantussyCell;
extern Model *modelSeedsOfChange;
extern Model *modelSeedsOfChangeCVExpander;
extern Model *modelSeedsOfChangeGateExpander;
extern Model *modelStringTheory;
extern Model *modelRouletteLFO;
extern Model *modelSeriouslySlowLFO;
extern Model *modelVoxInhumana;
extern Model *modelVoxInhumanaExpander;
extern Model *modelCDCSeriouslySlowLFO;
namespace old {
extern Model *modelLissajousLFO_old;
extern Model *modelRouletteLFO_old;
extern Model *modelQuadGolombRulerRhythm_old;
extern Model *modelQuadEuclideanRhythm_old;
} | 1,320 | 470 |
// File implement/oglplus/enums/precision_type_def.ipp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/precision_type.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2017 Matus Chochlik.
// 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
//
#ifdef OGLPLUS_LIST_NEEDS_COMMA
# undef OGLPLUS_LIST_NEEDS_COMMA
#endif
#if defined GL_LOW_FLOAT
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined LowFloat
# pragma push_macro("LowFloat")
# undef LowFloat
OGLPLUS_ENUM_CLASS_VALUE(LowFloat, GL_LOW_FLOAT)
# pragma pop_macro("LowFloat")
# else
OGLPLUS_ENUM_CLASS_VALUE(LowFloat, GL_LOW_FLOAT)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_MEDIUM_FLOAT
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined MediumFloat
# pragma push_macro("MediumFloat")
# undef MediumFloat
OGLPLUS_ENUM_CLASS_VALUE(MediumFloat, GL_MEDIUM_FLOAT)
# pragma pop_macro("MediumFloat")
# else
OGLPLUS_ENUM_CLASS_VALUE(MediumFloat, GL_MEDIUM_FLOAT)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_HIGH_FLOAT
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined HighFloat
# pragma push_macro("HighFloat")
# undef HighFloat
OGLPLUS_ENUM_CLASS_VALUE(HighFloat, GL_HIGH_FLOAT)
# pragma pop_macro("HighFloat")
# else
OGLPLUS_ENUM_CLASS_VALUE(HighFloat, GL_HIGH_FLOAT)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_LOW_INT
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined LowInt
# pragma push_macro("LowInt")
# undef LowInt
OGLPLUS_ENUM_CLASS_VALUE(LowInt, GL_LOW_INT)
# pragma pop_macro("LowInt")
# else
OGLPLUS_ENUM_CLASS_VALUE(LowInt, GL_LOW_INT)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_MEDIUM_INT
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined MediumInt
# pragma push_macro("MediumInt")
# undef MediumInt
OGLPLUS_ENUM_CLASS_VALUE(MediumInt, GL_MEDIUM_INT)
# pragma pop_macro("MediumInt")
# else
OGLPLUS_ENUM_CLASS_VALUE(MediumInt, GL_MEDIUM_INT)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#if defined GL_HIGH_INT
# ifdef OGLPLUS_LIST_NEEDS_COMMA
OGLPLUS_ENUM_CLASS_COMMA
# endif
# if defined HighInt
# pragma push_macro("HighInt")
# undef HighInt
OGLPLUS_ENUM_CLASS_VALUE(HighInt, GL_HIGH_INT)
# pragma pop_macro("HighInt")
# else
OGLPLUS_ENUM_CLASS_VALUE(HighInt, GL_HIGH_INT)
# endif
# ifndef OGLPLUS_LIST_NEEDS_COMMA
# define OGLPLUS_LIST_NEEDS_COMMA 1
# endif
#endif
#ifdef OGLPLUS_LIST_NEEDS_COMMA
# undef OGLPLUS_LIST_NEEDS_COMMA
#endif
| 3,025 | 1,388 |
// Copyright (c) 2018, The TurtleCoin Developers
// Copyright (c) 2020, The Ionize Developers
//
// Please see the included LICENSE file for more information.
////////////////////////
#include <Nigel/Nigel.h>
////////////////////////
#include <config/CryptoNoteConfig.h>
#include <CryptoNoteCore/CryptoNoteTools.h>
#include <Errors/ValidateParameters.h>
#include <Utilities/Utilities.h>
using json = nlohmann::json;
////////////////////////////////
/* Constructors / Destructors */
////////////////////////////////
Nigel::Nigel(
const std::string daemonHost,
const uint16_t daemonPort) :
Nigel(daemonHost, daemonPort, std::chrono::seconds(10))
{
}
Nigel::Nigel(
const std::string daemonHost,
const uint16_t daemonPort,
const std::chrono::seconds timeout) :
m_timeout(timeout),
m_daemonHost(daemonHost),
m_daemonPort(daemonPort),
m_httpClient(std::make_shared<httplib::Client>(daemonHost.c_str(), daemonPort, timeout.count()))
{
}
Nigel::~Nigel()
{
stop();
}
//////////////////////
/* Member functions */
//////////////////////
void Nigel::swapNode(const std::string daemonHost, const uint16_t daemonPort)
{
stop();
m_localDaemonBlockCount = 0;
m_networkBlockCount = 0;
m_peerCount = 0;
m_lastKnownHashrate = 0;
m_daemonHost = daemonHost;
m_daemonPort = daemonPort;
m_httpClient = std::make_shared<httplib::Client>(
daemonHost.c_str(), daemonPort, m_timeout.count()
);
init();
}
std::tuple<bool, std::vector<WalletTypes::WalletBlockInfo>> Nigel::getWalletSyncData(
const std::vector<Crypto::Hash> blockHashCheckpoints,
uint64_t startHeight,
uint64_t startTimestamp) const
{
json j = {
{"blockHashCheckpoints", blockHashCheckpoints},
{"startHeight", startHeight},
{"startTimestamp", startTimestamp}
};
const auto res = m_httpClient->Post(
"/getwalletsyncdata", j.dump(), "application/json"
);
if (res && res->status == 200)
{
try
{
json j = json::parse(res->body);
if (j.at("status").get<std::string>() != "OK")
{
return {false, {}};
}
const auto items = j.at("items").get<std::vector<WalletTypes::WalletBlockInfo>>();
return {true, items};
}
catch (const json::exception &)
{
}
}
return {false, {}};
}
void Nigel::stop()
{
m_shouldStop = true;
if (m_backgroundThread.joinable())
{
m_backgroundThread.join();
}
}
void Nigel::init()
{
m_shouldStop = false;
/* Get the initial daemon info, and the initial fee info before returning.
This way the info is always valid, and there's no race on accessing
the fee info or something */
getDaemonInfo();
getFeeInfo();
/* Now launch the background thread to constantly update the heights etc */
m_backgroundThread = std::thread(&Nigel::backgroundRefresh, this);
}
bool Nigel::getDaemonInfo()
{
const auto res = m_httpClient->Get("/info");
if (res && res->status == 200)
{
try
{
json j = json::parse(res->body);
m_localDaemonBlockCount = j.at("height").get<uint64_t>();
/* Height returned is one more than the current height - but we
don't want to overflow is the height returned is zero */
if (m_localDaemonBlockCount != 0)
{
m_localDaemonBlockCount--;
}
m_networkBlockCount = j.at("network_height").get<uint64_t>();
/* Height returned is one more than the current height - but we
don't want to overflow is the height returned is zero */
if (m_networkBlockCount != 0)
{
m_networkBlockCount--;
}
m_peerCount = j.at("incoming_connections_count").get<uint64_t>()
+ j.at("outgoing_connections_count").get<uint64_t>();
if (m_networkBlockCount >= CryptoNote::parameters::DIFFICULTY_TARGET_V2_HEIGHT)
{
m_lastKnownHashrate = j.at("difficulty").get<uint64_t>()
/ CryptoNote::parameters::DIFFICULTY_TARGET_V2;
}
else
{
m_lastKnownHashrate = j.at("difficulty").get<uint64_t>()
/ CryptoNote::parameters::DIFFICULTY_TARGET;
}
return true;
}
catch (const json::exception &)
{
}
}
return false;
}
bool Nigel::getFeeInfo()
{
const auto res = m_httpClient->Get("/fee");
if (res && res->status == 200)
{
try
{
json j = json::parse(res->body);
std::string tmpAddress = j.at("address").get<std::string>();
uint32_t tmpFee = j.at("amount").get<uint32_t>();
const bool integratedAddressesAllowed = false;
Error error = validateAddresses({tmpAddress}, integratedAddressesAllowed);
if (!error)
{
m_nodeFeeAddress = tmpAddress;
m_nodeFeeAmount = tmpFee;
}
return true;
}
catch (const json::exception &)
{
}
}
return false;
}
void Nigel::backgroundRefresh()
{
while (!m_shouldStop)
{
getDaemonInfo();
Utilities::sleepUnlessStopping(std::chrono::seconds(10), m_shouldStop);
}
}
bool Nigel::isOnline() const
{
return m_localDaemonBlockCount != 0 ||
m_networkBlockCount != 0 ||
m_peerCount != 0 ||
m_lastKnownHashrate != 0;
}
uint64_t Nigel::localDaemonBlockCount() const
{
return m_localDaemonBlockCount;
}
uint64_t Nigel::networkBlockCount() const
{
return m_networkBlockCount;
}
uint64_t Nigel::peerCount() const
{
return m_peerCount;
}
uint64_t Nigel::hashrate() const
{
return m_lastKnownHashrate;
}
std::tuple<uint64_t, std::string> Nigel::nodeFee() const
{
return {m_nodeFeeAmount, m_nodeFeeAddress};
}
std::tuple<std::string, uint16_t> Nigel::nodeAddress() const
{
return {m_daemonHost, m_daemonPort};
}
bool Nigel::getTransactionsStatus(
const std::unordered_set<Crypto::Hash> transactionHashes,
std::unordered_set<Crypto::Hash> &transactionsInPool,
std::unordered_set<Crypto::Hash> &transactionsInBlock,
std::unordered_set<Crypto::Hash> &transactionsUnknown) const
{
json j = {
{"transactionHashes", transactionHashes}
};
const auto res = m_httpClient->Post(
"/get_transactions_status", j.dump(), "application/json"
);
if (res && res->status == 200)
{
try
{
json j = json::parse(res->body);
if (j.at("status").get<std::string>() != "OK")
{
return false;
}
transactionsInPool = j.at("transactionsInPool").get<std::unordered_set<Crypto::Hash>>();
transactionsInBlock = j.at("transactionsInBlock").get<std::unordered_set<Crypto::Hash>>();
transactionsUnknown = j.at("transactionsUnknown").get<std::unordered_set<Crypto::Hash>>();
return true;
}
catch (const json::exception &)
{
}
}
return false;
}
std::tuple<bool, std::vector<CryptoNote::RandomOuts>> Nigel::getRandomOutsByAmounts(
const std::vector<uint64_t> amounts,
const uint64_t requestedOuts) const
{
json j = {
{"amounts", amounts},
{"outs_count", requestedOuts}
};
const auto res = m_httpClient->Post(
"/getrandom_outs", j.dump(), "application/json"
);
if (res && res->status == 200)
{
try
{
json j = json::parse(res->body);
if (j.at("status").get<std::string>() != "OK")
{
return {};
}
const auto outs = j.at("outs").get<std::vector<CryptoNote::RandomOuts>>();
return {true, outs};
}
catch (const json::exception &)
{
}
}
return {false, {}};
}
std::tuple<bool, bool> Nigel::sendTransaction(
const CryptoNote::Transaction tx) const
{
json j = {
{"tx_as_hex", Common::toHex(CryptoNote::toBinaryArray(tx))}
};
const auto res = m_httpClient->Post(
"/sendrawtransaction", j.dump(), "application/json"
);
bool success = false;
bool connectionError = true;
if (res && res->status == 200)
{
connectionError = false;
try
{
json j = json::parse(res->body);
success = j.at("status").get<std::string>() == "OK";
}
catch (const json::exception &)
{
}
}
return {success, connectionError};
}
std::tuple<bool, std::unordered_map<Crypto::Hash, std::vector<uint64_t>>>
Nigel::getGlobalIndexesForRange(
const uint64_t startHeight,
const uint64_t endHeight) const
{
json j = {
{"startHeight", startHeight},
{"endHeight", endHeight}
};
const auto res = m_httpClient->Post(
"/get_global_indexes_for_range", j.dump(), "application/json"
);
if (res && res->status == 200)
{
try
{
std::unordered_map<Crypto::Hash, std::vector<uint64_t>> result;
json j = json::parse(res->body);
if (j.at("status").get<std::string>() != "OK")
{
return {false, {}};
}
/* The daemon doesn't serialize the way nlohmann::json does, so
we can't just .get<std::unordered_map ...> */
json indexes = j.at("indexes");
for (const auto index : indexes)
{
result[index.at("key").get<Crypto::Hash>()] = index.at("value").get<std::vector<uint64_t>>();
}
return {true, result};
}
catch (const json::exception &)
{
}
}
return {false, {}};
}
| 10,072 | 3,254 |
/*
* Copyright 2018-2019 Redis Labs Ltd. and Contributors
*
* This file is available under the Redis Labs Source Available License Agreement
*/
#include "gtest.h"
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include "../../src/execution_plan/record.h"
#include "../../src/util/rmalloc.h"
#include "../../src/value.h"
#ifdef __cplusplus
}
#endif
class RecordTest: public ::testing::Test {
protected:
static void SetUpTestCase() {// Use the malloc family for allocations
Alloc_Reset();
}
};
TEST_F(RecordTest, RecordToString) {
Record r = Record_New(6);
SIValue v_string = SI_ConstStringVal("Hello");
SIValue v_int = SI_LongVal(-24);
SIValue v_uint = SI_LongVal(24);
SIValue v_double = SI_DoubleVal(0.314);
SIValue v_null = SI_NullVal();
SIValue v_bool = SI_BoolVal(1);
Record_AddScalar(r, 0, v_string);
Record_AddScalar(r, 1, v_int);
Record_AddScalar(r, 2, v_uint);
Record_AddScalar(r, 3, v_double);
Record_AddScalar(r, 4, v_null);
Record_AddScalar(r, 5, v_bool);
size_t record_str_cap = 0;
char *record_str = NULL;
size_t record_str_len = Record_ToString(r, &record_str, &record_str_cap);
ASSERT_EQ(strcmp(record_str, "Hello,-24,24,0.314000,NULL,true"), 0);
ASSERT_EQ(record_str_len, 31);
rm_free(record_str);
Record_Free(r);
}
| 1,278 | 543 |
#ifndef MTV_HH
#define MTV_HH
#include <string>
#include "trick/IPPythonEvent.hh"
namespace Trick {
class MTV {
public:
MTV() ;
Trick::IPPythonEvent dummy_event ; /**< trick_io(*io) trick_units(--) */
Trick::IPPythonEvent ** mtv_list ; /**< trick_io(*io) trick_units(--) */
/** Count of user events to be displayed by mtv.\n */
unsigned int mtv_count ; /**< trick_io(*io) trick_units(--) */
/** Running count of last new event or event deletion, so mtv knows when to update.\n */
int mtv_update_ticker; /**< trick_io(*io) trick_units(--) */
int add_event ( Trick::IPPythonEvent * in_event ) ;
int delete_event ( Trick::IPPythonEvent * in_event ) ;
Trick::IPPythonEvent * get_event ( std::string event_name ) ;
int send_event_data() ;
} ;
}
int mtv_add_event(Trick::IPPythonEvent * in_event) ;
int mtv_delete_event(Trick::IPPythonEvent * in_event) ;
Trick::IPPythonEvent * mtv_get_event(std::string event_name) ;
int mtv_send_event_data() ;
#endif
| 1,121 | 380 |
//
// MallocCollectorHelper.hpp
// cfunction
//
// Created by hzduanjiashun on 2018/3/28.
// Copyright © 2018年 Daniel. All rights reserved.
//
#ifndef MallocCollectorHelper_hpp
#define MallocCollectorHelper_hpp
#include <stdio.h>
#include <memory>
#include <malloc/malloc.h>
#include "MallocMemory.hpp"
namespace MD {
namespace CollectorDefault {
template <class _S>
struct CollectorChecker {
static int64_t max() {
return 1024*1024;
}
static void overflow(_S* storage) {
}
};
}
template <class _S, class _I, class _C = CollectorDefault::CollectorChecker<_S>>
class Collector {
public:
typedef _S storage_type;
typedef _I item_type;
typedef _C checker_type;
Collector(storage_type* s) : s_(s) {
i_.start();
}
Collector& setZone(malloc_zone_t *z) {
i_.zone = z;
return *this;
}
Collector& setAction(Action act) {
i_.action = act;
return *this;
}
Collector& setSize(std::int64_t size) {
i_.size = size;
return *this;
}
Collector& set(malloc_zone_t *z, Action act, std::int64_t size) {
i_.zone = z;
i_.action = act;
i_.size = size;
return *this;
}
~Collector() {
i_.stop();
int64_t cnt = s_->collect(std::move(i_));
if (cnt > checker_type::max()) {
checker_type::overflow(s_);
}
}
private:
storage_type* s_;
item_type i_;
};
}
#endif /* MallocCollectorHelper_hpp */
| 1,822 | 577 |
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/************************************
* AliPMD offline calibration task
*
* Satyajit Jena, IIT Bombay
* sjena@cern.ch
* Fri Feb 12 13:30:19 IST 2010
*
************************************/
#include "TChain.h"
#include "TList.h"
#include "TFile.h"
#include "TTree.h"
#include "TH1F.h"
#include "TCanvas.h"
#include "AliAnalysisTask.h"
#include "AliAnalysisManager.h"
#include "AliVEvent.h"
#include "AliESD.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "TObjArray.h"
#include "AliPMDOfflineCalibTask.h"
ClassImp(AliPMDOfflineCalibTask)
//________________________________________________________________________
AliPMDOfflineCalibTask::AliPMDOfflineCalibTask(const char *name)
: AliAnalysisTaskSE(name),
fListOfHistos(0),
fPmdCalibAdcP(0),
fPmdCalibAdcC(0),
fPmdCalibEntP(0),
fPmdCalibEntC(0),
fNEvents(0),
fSelectedTrigger(new TObjArray()),
fRejected(kTRUE)
{
// Constructor
DefineOutput(1, TList::Class());
}
//________________________________________________________________________
void AliPMDOfflineCalibTask::UserCreateOutputObjects()
{
fListOfHistos = new TList();
fNEvents = new TH1I("hNEvents","Events Statistic", 3, 0, 5);
fPmdCalibAdcP = new TH1F("fPmdCalibAdcP", "PMD Calibration ADC fill for PRE", 234795, 0, 234795);
fPmdCalibAdcP->GetYaxis()->SetTitle("ADC");
fPmdCalibAdcP->GetXaxis()->SetTitle("Cells in SMN-ROW-COL");
fPmdCalibAdcC = new TH1F("fPmdCalibAdcC", "PMD Calibration ADC fill for CPV", 234795, 0, 234795);
fPmdCalibAdcC->GetYaxis()->SetTitle("ADC");
fPmdCalibAdcC->GetXaxis()->SetTitle("Cells in SMN-ROW-COL");
fPmdCalibEntP = new TH1F("fPmdCalibEntP", "PMD Calibration Entries fill for PRE", 234795, 0, 234795);
fPmdCalibEntP->GetYaxis()->SetTitle("Frequescy");
fPmdCalibEntP->GetXaxis()->SetTitle("Cells in SMN-ROW-COL");
fPmdCalibEntC = new TH1F("fPmdCalibEntC", "PMD Calibration Entries fill for CPV", 234795, 0, 234795);
fPmdCalibEntC->GetYaxis()->SetTitle("Frequescy ");
fPmdCalibEntC->GetXaxis()->SetTitle("Cells in SMN-ROW-COL");
fListOfHistos->Add(fPmdCalibAdcP);
fListOfHistos->Add(fPmdCalibAdcC);
fListOfHistos->Add(fPmdCalibEntP);
fListOfHistos->Add(fPmdCalibEntC);
fListOfHistos->Add(fNEvents);
}
//________________________________________________________________________
void AliPMDOfflineCalibTask::UserExec(Option_t *)
{
AliVEvent *event = InputEvent();
if (!event) {
Printf("ERROR: Could not retrieve event");
return;
}
fNEvents->Fill(1);
AliESDEvent* pmdesd = dynamic_cast<AliESDEvent*>(event);
if(!pmdesd) return;
fNEvents->Fill(2);
Bool_t pass = kTRUE;
Int_t numberOfTriggerSelected = fSelectedTrigger->GetEntriesFast();
if(fRejected)
{
pass = kTRUE;
for(Int_t k = 0; k < numberOfTriggerSelected; k++)
{
const TObjString *const obString = (TObjString*)fSelectedTrigger->At(k);
const TString tString = obString->GetString();
if(pmdesd->IsTriggerClassFired((const char*)tString))
{
pass = kFALSE;
}
}
}
else
{
pass = kFALSE;
for(Int_t k = 0; k < numberOfTriggerSelected; k++)
{
const TObjString *const obString=(TObjString*)fSelectedTrigger->At(k);
const TString tString = obString->GetString();
if(pmdesd->IsTriggerClassFired((const char*)tString))
{
pass = kTRUE;
}
}
}
if(!pass)
{
PostData(1, fListOfHistos);
return;
}
fNEvents->Fill(3);
Int_t npmdcl = pmdesd->GetNumberOfPmdTracks();
if(npmdcl < 1) fNEvents->Fill(4);
while (npmdcl--)
{
AliESDPmdTrack *pmdtr = pmdesd->GetPmdTrack(npmdcl);
Int_t det = pmdtr->GetDetector();
Int_t smn = pmdtr->GetSmn();
Float_t adc = pmdtr->GetClusterADC();
Float_t sTag = pmdtr->GetClusterSigmaX();
Float_t sRowCol = pmdtr->GetClusterSigmaY();
Float_t rc = smn*10000 + sRowCol;
if(adc > 1200.) continue;
if(sTag > 999. && sTag < 1000.)
{
if(det == 0)
{
fPmdCalibAdcP->Fill(rc,adc);
fPmdCalibEntP->Fill(rc);
}
else if(det == 1)
{
fPmdCalibAdcC->Fill(rc,adc);
fPmdCalibEntC->Fill(rc);
}
}
}
PostData(1, fListOfHistos);
}
//________________________________________________________________________
void AliPMDOfflineCalibTask::Terminate(Option_t *)
{
fListOfHistos = dynamic_cast<TList*>(GetOutputData(1));
fPmdCalibAdcP = dynamic_cast<TH1F*>(fListOfHistos->At(0));
if(!fPmdCalibAdcP) {
printf("ERROR: No ADC File Generated for PMD-PRE ");
return;
}
fPmdCalibAdcC = dynamic_cast<TH1F*>(fListOfHistos->At(1));
if(!fPmdCalibAdcC) {
printf("ERROR: No ADC File Generated for PMD-CPV ");
return;
}
fPmdCalibEntP = dynamic_cast<TH1F*>(fListOfHistos->At(2));
if(!fPmdCalibEntP) {
printf("ERROR: No Entry File Generated for PMD-PRE ");
printf(" No fhXyPRE ");
return;
}
fPmdCalibEntC = dynamic_cast<TH1F*>(fListOfHistos->At(3));
if(!fPmdCalibEntC) {
printf("ERROR: No Entry File Generated for PMD-CPV ");
return;
}
fNEvents = dynamic_cast<TH1I*>(fListOfHistos->At(4));
if(!fNEvents) {
printf("ERROR: No Entry File Generated for Event Counter ");
return;
}
Info("AliPMDOfflineCalibTask","PMD offline Calibration Successfully finished");
}
| 6,504 | 2,465 |
#include <iostream>
struct BitFieldStruct {
unsigned int a : 4;
unsigned int b : 3;
};
int main() {
BitFieldStruct x;
x.a = 06;
x.b = x.a | 3; // | bitwise OR, || logical OR ; & bitwise AND, && logicalwise AND
std::cout << x.a << '\n' << std::endl;// converted to unsigned and then displayed
std::cout << x.b << '\n' << std::endl;// converted to unsigned and then displayed
}
// 0 1 1 is 3
// 1 1 0 is 6 bitwise OR of 3 and 6 is:
// 1 1 1 is 7
//may save space but cost time in comparison to byte alignment
// bitwise logical
// OR | ||
//AND & &&
//XOR ^ !=
//NEG ~ !
| 671 | 245 |
// Libraries
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
// Project headers
#include <client/application/applications/HelloTriangleApplication.hpp>
// C/C++ standard
#include <stdexcept>
int main() {
glfwInit();
HelloTriangleApplication app;
app.init();
while(!glfwWindowShouldClose(app.window))
app.loop();
vkDeviceWaitIdle(app.device);
app.cleanup();
glfwTerminate();
return EXIT_SUCCESS;
} | 417 | 163 |
// User data functions. Modify these functions for your data items.
#include "UserTypes.h"
#include "Wire.h"
#include "I2Cdev.h"
#include "MPU6050.h"
//------------------------------------------------------------------------------
MPU6050 mpu;
static uint32_t startMicros;
// Acquire a data record.
void acquireData(data_t* data) {
data->time = micros();
mpu.getMotion6(&data->ax, &data->ay, &data->az,
&data->gx, &data->gy, &data->gz);
}
// setup AVR I2C
void userSetup() {
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
Wire.begin();
Wire.setClock(400000);
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
Fastwire::setup(400, true);
#endif
mpu.initialize();
}
// Print a data record.
void printData(Print* pr, data_t* data) {
if (startMicros == 0) {
startMicros = data->time;
}
pr->print(data->time- startMicros);
pr->write(',');
pr->print(data->ax);
pr->write(',');
pr->print(data->ay);
pr->write(',');
pr->print(data->az);
pr->write(',');
pr->print(data->gx);
pr->write(',');
pr->print(data->gy);
pr->write(',');
pr->println(data->gz);
}
// Print data header.
void printHeader(Print* pr) {
startMicros = 0;
pr->println(F("micros,ax,ay,az,gx,gy,gz"));
}
| 1,240 | 510 |
#ifndef TP_TALLER_DE_PROGRAMACION_FIUBA_CONSTANTES_HPP
#define TP_TALLER_DE_PROGRAMACION_FIUBA_CONSTANTES_HPP
#include <stdint.h>
const int ANCHO_FONDO = 8177;
#define VALOR_POR_DEFECTO_ANCHO 800
#define VALOR_POR_DEFECTO_ALTO 600
#define TIEMPO_ESPERA_GAME_LOOP 5
#define IZQUIERDA 1
#define DERECHA 2
#define ARRIBA 3
#define ABAJO 4
#define MAX_CONEXIONES 4
#define SIN_JUGAR (-1)
#define LARGO_IP 20
//=======================================================//
//==================== COLISIONES =======================//
#define COLISION_ID_MARIO "Mario"
#define COLISION_ID_KOOPA "Koopa"
#define COLISION_ID_GOOMBA "Goomba"
#define COLISION_ID_MONEDA "Moneda"
#define COLISION_ID_LADRILLO "Ladrillo"
#define COLISION_ID_SORPRESA "Sorpresa"
#define COLISION_ID_FLOR "Flor"
#define COLISION_ID_MONEDA_FLOTANTE "Moneda flotante"
#define COLISION_ID_BOLA_DE_FUEGO "Bola de fuego"
#define COLISION_ID_CHISPA "Chispa"
#define COLISION_ID_NADA "Nada"
#define COLISION_ID_PLATAFORMA "Plataforma"
#define COLISION_ID_PIEZA_TUBERIA "Pieza tuberia"
//=======================================================//
//====================== MEDIDAS ========================//
const int PUNTOS_KOOPA = 1000;
const int PUNTOS_GOOMBA = 500;
const int PUNTOS_POR_MONEDA = 50;
const int ANCHO_POZO = 200, ALTO_POZO = 65;
const int ALTO_MARIO = 80, ANCHO_MARIO = 40, ALTO_MARIO_AGACHADO = 55;
const int ALTO_ENEMIGOS = 40, ANCHO_ENEMIGOS = 40;
const int RANGO_EXTRA_ENEMIGOS = ANCHO_ENEMIGOS*2;
const int LARGO_BLOQUE = 40;
const int LARGO_MONEDA = 40;
const int ALTO_FLOR = 40, ANCHO_FLOR = 40;
const int ALTO_BOLA = 20, ANCHO_BOLA = 20;
const int ALTO_CHISPA = 44, ANCHO_CHISPA = 64;
const int ALTO_TUBERIA_CHICA = 90, ANCHO_TUBERIA_CHICA = 90;
const int ALTO_TUBERIA_GRANDE = ALTO_TUBERIA_CHICA*2, ANCHO_TUBERIA_GRANDE = ANCHO_TUBERIA_CHICA*2;
const uint8_t SIN_MODIFICADOR = 0, MODIFICADOR_FUEGO = 1;
#define TUBERIA_CHICA 0
#define TUBERIA_GRANDE 1
#define COLORES_BLOQUES_POSIBLES 7
#define ESTADOS_BLOQUE 5
#define ESTADOS_MONEDA 4
#define ESTADOS_GOOMBA 3
#define COLORES_GOOMBA_POSIBLES 4
#define ESTADOS_KOOPA 6
#define COLORES_KOOPA_POSIBLES 5
//=======================================================//
//====================== ENTIDADES ======================//
const uint8_t NADA = 0;
const uint8_t GOOMBA = 1;
const uint8_t KOOPA = 2;
const uint8_t BOLA_DE_FUEGO = 3;
const uint8_t CHISPA = 4;
const uint8_t FLOR = 5;
const uint8_t MONEDA_FLOTANTE = 6;
const uint8_t MONEDA = 7;
const uint8_t BLOQUE = 8;
const uint8_t TUBERIA = 9;
const uint8_t POZO = 10;
const uint8_t FONDO_POZO = 11;
const uint8_t MARIO_RECORTE = 12;
const int ENEMIGOS_RECORTE = 12;
const int EFECTOS_RECORTE = 13;
//=======================================================//
//====================== TEXTURAS =======================//
#define CLAVE_TEXTURA_POZO "Pozo"
#define CLAVE_TEXTURA_MONEDA "Moneda"
#define CLAVE_TEXTURA_FONDO_INICIO "FondoInicio"
#define CLAVE_TEXTURA_TITULO "Titulo"
#define CLAVE_TEXTURA_GAMEOVER "FondoGameOver"
#define CLAVE_TEXTURA_COFFIN_MARIO "Coffin"
#define CLAVE_TEXTURA_TUBERIAS "Tuberia"
#define CLAVE_TEXTURA_CORAZON "Corazon"
#define CLAVE_TEXTURA_BOLA_DE_FUEGO "BolaDeFuego"
#define CLAVE_TEXTURA_CHISPA "Chispa"
#define CLAVE_TEXTURA_FLOR "Flor"
#define CLAVE_TEXTURA_MONEDA_FLOTANTE "MonedaFlotante"
#define CLAVE_TEXTURA_BLOQUES "Bloques"
#define CLAVE_TEXTURA_GOOMBA "Goombas"
#define CLAVE_TEXTURA_KOOPAS "Koopas"
#define CLAVE_TEXTURA_PEACH_SALTANDO "PeachSaltando"
#define CLAVE_TEXTURA_TOAD_SALTANDO "ToadSaltando"
#define CLAVE_TEXTURA_YOSHI_SALTANDO "YoshiSaltando"
#define CLAVE_TEXTURA_MARIO_SALTANDO "MarioSaltando"
#define CLAVE_TEXTURA_FONDO_POZO "FondoPozo"
//=======================================================//
//====================== MUSICA =========================//
#define MUSICA_VICTORIA "resources/Musica/MusicaVictoria.mp3"
#define MUSICA_GAMEOVER "resources/Musica/CoffinDance8Bits.mp3"
#define MUSICA_INICIO "resources/Musica/MusicaInicio.mp3"
#define MUSICA_NIVEL1 "resources/Musica/TemaNivel1.mp3"
#define MUSICA_MODO_DIEGO "resources/Musica/LiveisLife.mp3"
//=======================================================//
//====================== SONIDOS ========================//
const uint8_t NO_SONAR = 0;
const uint8_t SONIDO_SALTO = 1;
const uint8_t SONIDO_AGARRAR_MONEDA = 2;
const uint8_t SONIDO_MATAR_GOOMBA = 3;
const uint8_t SONIDO_MATAR_KOOPA = 4;
const uint8_t SONIDO_APARECE_FLOR = 5;
const uint8_t SONIDO_AGARRA_POWERUP = 6;
const uint8_t SONIDO_MORIR = 7;
const uint8_t SONIDO_LANZAR_BOLA_DE_FUEGO = 8;
const uint8_t SONIDO_LANZAR_CHISPA = 9;
const uint8_t SONIDO_REBOTE_BOLA_DE_FUEGO = 10;
const uint8_t SONIDO_EXPLOSION_BOLA_DE_FUEGO = 11;
const uint8_t SONIDO_LLEGAR_A_LA_META = 12;
#define DIRECCION_SONIDO_SALTO "resources/Musica/EfectosSonido/EfectoSalto.wav"
#define DIRECCION_SONIDO_AGARRAR_MONEDA "resources/Musica/EfectosSonido/AgarrarMoneda.wav"
#define DIRECCION_SONIDO_MUERTE_GOOMBA "resources/Musica/EfectosSonido/MarioMataGoomba.wav"
#define DIRECCION_SONIDO_MUERTE_KOOPA "resources/Musica/EfectosSonido/MarioPisaKoopa.wav"
#define DIRECCION_SONIDO_APARECE_PLANTA "resources/Musica/EfectosSonido/AparecePlanta.wav"
#define DIRECCION_SONIDO_MARIO_AGARRA_HONGO "resources/Musica/EfectosSonido/MarioAgarraHongo.wav"
#define DIRECCION_SONIDO_MARIO_MUERE "resources/Musica/EfectosSonido/MarioMorir.wav"
#define DIRECCION_SONIDO_MARIO_LANZA_FUEGO "resources/Musica/EfectosSonido/MarioLanzaFuego.wav"
#define DIRECCION_SONIDO_CHISPA "resources/Musica/EfectosSonido/Chispazo.wav"
#define DIRECCION_SONIDO_REBOTE "resources/Musica/EfectosSonido/ReboteBolaDeFuego.wav"
#define DIRECCION_SONIDO_EXPLOSION "resources/Musica/EfectosSonido/ExplosionBolaDeFuego.wav"
#define DIRECCION_SONIDO_PASAR_NIVEL "resources/Musica/EfectosSonido/PasarDeNivel.wav"
#endif //TP_TALLER_DE_PROGRAMACION_FIUBA_CONSTANTES_HPP
| 5,886 | 2,798 |
#include "mediapipe/framework/calculator_framework.h"
#include "mediapipe/calculators/signn/timed_queue.h"
#include "mediapipe/framework/formats/landmark.pb.h"
#include "mediapipe/calculators/signn/static_dynamic_gate_options.pb.h"
#include <fstream>
namespace mediapipe{
namespace{
constexpr char Landmarks[] = "LANDMARKS";
constexpr char LandmarksHistory[] = "LANDMARKS_HISTORY";
constexpr char Double[] = "DOUBLE";
}
class StaticDynamicGateCalculator: public CalculatorBase {
public:
StaticDynamicGateCalculator(){};
~StaticDynamicGateCalculator(){};
static ::mediapipe::Status GetContract(CalculatorContract* cc){
cc->Inputs().Tag(Landmarks).Set<NormalizedLandmarkList>();
cc->Inputs().Tag(LandmarksHistory).Set<std::vector<NormalizedLandmarkList>>();
cc->Inputs().Tag(Double).Set<double>();
cc->Outputs().Tag(Landmarks).Set<NormalizedLandmarkList>();
cc->Outputs().Tag(LandmarksHistory).Set<std::vector<NormalizedLandmarkList>>();
return ::mediapipe::OkStatus();
}
::mediapipe::Status Open(CalculatorContext* cc){
const auto& options = cc->Options<::mediapipe::StaticDynamicGateOptions>();
DYNAMIC_THRESHOLD = options.dynamic_threshold();
MAXIMUM_EXTRA_DYNAMIC_FRAMES = options.maximum_extra_dynamic_frames();
double velocity_history = options.velocity_history();
history = TimedQueue<double>(velocity_history);
return ::mediapipe::OkStatus();
}
::mediapipe::Status Process(CalculatorContext* cc){
auto static_data = cc->Inputs().Tag(Landmarks).Get<NormalizedLandmarkList>();
auto dynamic_data = cc->Inputs().Tag(LandmarksHistory).Get<std::vector<NormalizedLandmarkList>>();
double hand_velocity = cc->Inputs().Tag(Double).Get<double>();
// if(first_ten_frames_static > 0){
// first_ten_frames_static--;
// hand_velocity = 0;
// }
history.add(hand_velocity);
auto hand_history = history.get();
double average_hand_history = 0;
for(int i = 0; i < hand_history.size(); i++){
if(hand_history.at(i) < 100){ // To prevent inf from being added - I am not sure how inf gets into the systen
average_hand_history += hand_history.at(i);
}
}
average_hand_history /= hand_history.size();
// LOG(INFO) << average_hand_history;
if(average_hand_history < DYNAMIC_THRESHOLD && extra_dynamic_frames < 0){
auto output_data = absl::make_unique<NormalizedLandmarkList>(static_data);
cc->Outputs().Tag(Landmarks).Add(output_data.release(), cc->InputTimestamp());
}else{
if(average_hand_history >= DYNAMIC_THRESHOLD && extra_dynamic_frames < 10){
extra_dynamic_frames += 1;
}else{
extra_dynamic_frames -= 1;
}
auto output_data = absl::make_unique<std::vector<NormalizedLandmarkList>>(dynamic_data);
cc->Outputs().Tag(LandmarksHistory).Add(output_data.release(), cc->InputTimestamp());
}
return ::mediapipe::OkStatus();
}
::mediapipe::Status Close(CalculatorContext* cc){
return ::mediapipe::OkStatus();
}
private:
TimedQueue<double> history;
double extra_dynamic_frames = 0;
int MAXIMUM_EXTRA_DYNAMIC_FRAMES = 0;
int first_ten_frames_static = 10;
double DYNAMIC_THRESHOLD;
};
REGISTER_CALCULATOR(StaticDynamicGateCalculator);
} | 3,800 | 1,105 |
#include "normal3.h"
#include <cmath>
#include <ostream>
namespace eyebeam
{
Normal3 operator+(const Normal3& lhs, const Normal3& rhs)
{
auto result(lhs);
result += rhs;
return result;
}
Normal3 operator-(const Normal3& lhs, const Normal3& rhs)
{
auto result(lhs);
result -= rhs;
return result;
}
Normal3 operator*(const Normal3& lhs, float rhs)
{
auto result(lhs);
result *= rhs;
return result;
}
Normal3 operator*(float lhs, const Normal3& rhs)
{
auto result(rhs);
result *= lhs;
return result;
}
Normal3 operator/(const Normal3& lhs, float rhs)
{
auto result(lhs);
result /= rhs;
return result;
}
float length(const Normal3& normal)
{
return std::sqrt(lengthSquared(normal));
}
void normalize(Normal3& normal)
{
normal /= length(normal);
}
Normal3 norm(Normal3 normal)
{
normalize(normal);
return normal;
}
std::ostream& operator<<(std::ostream& os, const Normal3& out)
{
os << "(" << out.x() << ", " << out.y() << ", " << out.z() << ")";
return os;
}
} // namespace eyebeam
| 1,074 | 388 |
#include "Matrix.h"
#include "../Vector3/Vector3n.h"
#include <iostream>
int MATRIX_MAX_SIZE = 9;
namespace ME
{
// idendity matrix
Matrix::Matrix()
{
for (int i = 0; i < MATRIX_MAX_SIZE; i++)
{
matrixData[i] = 0.0f;
}
matrixData[0] = matrixData[4] = matrixData[8] = 1.0f;
}
Matrix::Matrix(float m0, float m3, float m6, float m1, float m4, float m7, float m2, float m5, float m8)
{
matrixData[0] = m0;
matrixData[3] = m3;
matrixData[6] = m6;
matrixData[1] = m1;
matrixData[4] = m4;
matrixData[7] = m7;
matrixData[2] = m2;
matrixData[5] = m5;
matrixData[8] = m8;
}
Matrix::~Matrix() {}
void Matrix::show()
{
std::cout << "(" << matrixData[0] << " " << matrixData[3] << " " << matrixData[6] << ")" << std::endl;
std::cout << "(" << matrixData[1] << " " << matrixData[4] << " " << matrixData[7] << ")" << std::endl;
std::cout << "(" << matrixData[2] << " " << matrixData[5] << " " << matrixData[8] << ")" << std::endl;
std::cout << std::endl;
}
Matrix& Matrix::operator = (const Matrix& value)
{
for(int i = 0; i < MATRIX_MAX_SIZE; i++)
{
matrixData[i] = value.matrixData[i];
}
return *this;
}
// add matrices
Matrix& Matrix::operator + (const Matrix &v) const
{
Matrix m;
for(int i = 0; i < MATRIX_MAX_SIZE; i++)
{
m.matrixData[i] = matrixData[i] + v.matrixData[i];
}
return m;
}
void Matrix::operator += (const Matrix &v)
{
for (int i = 0; i < MATRIX_MAX_SIZE; i++)
{
matrixData[i] += v.matrixData[i];
}
}
// subtract matrices
Matrix& Matrix::operator - (const Matrix& v) const
{
Matrix m;
for (int i = 0; i < MATRIX_MAX_SIZE; i++)
{
m.matrixData[i] = matrixData[i] - v.matrixData[i];
}
return m;
}
void Matrix::operator -= (const Matrix& v)
{
for (int i = 0; i < MATRIX_MAX_SIZE; i++)
{
matrixData[i] -= v.matrixData[i];
}
}
// multiply by scalar
Matrix& Matrix::operator * (const float s) const
{
Matrix m;
for(int i = 0; i < MATRIX_MAX_SIZE; i++)
{
m.matrixData[i] = matrixData[i] * s;
}
return m;
}
void Matrix::operator *= (const float s)
{
for (int i = 0; i < MATRIX_MAX_SIZE; i++)
{
matrixData[i] *= s;
}
}
// multiply matrices
Matrix Matrix::operator * (const Matrix& m) const
{
return Matrix(matrixData[0] * m.matrixData[0] + matrixData[3] * m.matrixData[1] + matrixData[6] * m.matrixData[2],
matrixData[0] * m.matrixData[3] + matrixData[3] * m.matrixData[4] + matrixData[6] * m.matrixData[5],
matrixData[0] * m.matrixData[6] + matrixData[3] * m.matrixData[7] + matrixData[6] * m.matrixData[8],
matrixData[1] * m.matrixData[0] + matrixData[4] * m.matrixData[1] + matrixData[7] * m.matrixData[2],
matrixData[1] * m.matrixData[3] + matrixData[4] * m.matrixData[4] + matrixData[7] * m.matrixData[5],
matrixData[1] * m.matrixData[6] + matrixData[4] * m.matrixData[7] + matrixData[7] * m.matrixData[8],
matrixData[2] * m.matrixData[0] + matrixData[5] * m.matrixData[1] + matrixData[8] * m.matrixData[2],
matrixData[2] * m.matrixData[3] + matrixData[5] * m.matrixData[4] + matrixData[8] * m.matrixData[5],
matrixData[2] * m.matrixData[6] + matrixData[5] * m.matrixData[7] + matrixData[8] * m.matrixData[8]);
}
void Matrix::operator *= (const Matrix& m)
{
float t1;
float t2;
float t3;
t1 = matrixData[0] * m.matrixData[0] + matrixData[3] * m.matrixData[1] + matrixData[6] * m.matrixData[2];
t2 = matrixData[0] * m.matrixData[3] + matrixData[3] * m.matrixData[4] + matrixData[6] * m.matrixData[5];
t3 = matrixData[0] * m.matrixData[6] + matrixData[3] * m.matrixData[7] + matrixData[6] * m.matrixData[8];
matrixData[0] = t1;
matrixData[3] = t2;
matrixData[6] = t3;
t1 = matrixData[1] * m.matrixData[0] + matrixData[4] * m.matrixData[1] + matrixData[7] * m.matrixData[2];
t2 = matrixData[1] * m.matrixData[3] + matrixData[4] * m.matrixData[4] + matrixData[7] * m.matrixData[5];
t3 = matrixData[1] * m.matrixData[6] + matrixData[4] * m.matrixData[7] + matrixData[7] * m.matrixData[8];
matrixData[1] = t1;
matrixData[4] = t2;
matrixData[7] = t3;
t1 = matrixData[2] * m.matrixData[0] + matrixData[5] * m.matrixData[1] + matrixData[8] * m.matrixData[2];
t2 = matrixData[2] * m.matrixData[3] + matrixData[5] * m.matrixData[4] + matrixData[8] * m.matrixData[5];
t3 = matrixData[2] * m.matrixData[6] + matrixData[5] * m.matrixData[7] + matrixData[8] * m.matrixData[8];
matrixData[2] = t1;
matrixData[5] = t2;
matrixData[8] = t3;
}
// set matrix to identity
void Matrix::setMatrixAsIdentity()
{
for(int i = 0; i < MATRIX_MAX_SIZE; i++)
{
matrixData[i] = 0.0f;
}
matrixData[0] = matrixData[4] = matrixData[8] = 1.0f;
}
// invert matrix
void Matrix::setMatrixAsInvertedMatrix(const Matrix& m)
{
// adjunta
// a = 4 * 8 - 7 * 5 d = -(3 * 8 - 5 * 6) g = 3 * 7 - 6 * 4
// b = -(1 * 8 - 7 * 2) e = 0 * 8 - 6 * 2 h = -(0 * 7 - 6 * 1)
// c = 1 * 5 - 2 * 4 f = -(0 * 5 - 3 * 2) i = 0 * 4 - 1 * 3
//determinante
// (0 * 4 * 8) + (1 * 5 * 6) + (2 * 3 * 7) - (6 * 4 * 2) - (7 * 5 * 0) - (8 * 3 * 1)
//float det = (t1 * m.matrixData[8] - t2 * m.matrixData[5] - t3 * m.matrixData[8] + t4 * m.matrixData[5] + t5 * m.matrixData[7] - t6 * m.matrixData[4]);
float t1 = m.matrixData[0] * m.matrixData[4] * m.matrixData[8];
float t2 = m.matrixData[1] * m.matrixData[5] * m.matrixData[6];
float t3 = m.matrixData[2] * m.matrixData[3] * m.matrixData[7];
float t4 = m.matrixData[6] * m.matrixData[4] * m.matrixData[2];
float t5 = m.matrixData[7] * m.matrixData[5] * m.matrixData[0];
float t6 = m.matrixData[8] * m.matrixData[3] * m.matrixData[1];
float det = t1 + t2 + t3 - t4 - t5 - t6;
if (det == 0.0)
{
std::cout << "The determinant is equal to 0, then there is no inverted matrix." << std::endl;
return;
}
float invD = 1.0f / det;
float a = (m.matrixData[4] * m.matrixData[8] - m.matrixData[7] * m.matrixData[5]) * invD;
float b = -(m.matrixData[1] * m.matrixData[8] - m.matrixData[7] * m.matrixData[2]) * invD;
float c = (m.matrixData[1] * m.matrixData[5] - m.matrixData[2] * m.matrixData[4]) * invD;
float d = -(m.matrixData[3] * m.matrixData[8] - m.matrixData[5] * m.matrixData[6]) * invD;
float e = (m.matrixData[0] * m.matrixData[8] - m.matrixData[6] * m.matrixData[2]) * invD;
float f = -(m.matrixData[0] * m.matrixData[5] - m.matrixData[3] * m.matrixData[2]) * invD;
float g = (m.matrixData[3] * m.matrixData[7] - m.matrixData[6] * m.matrixData[4]) * invD;
float h = -(m.matrixData[0] * m.matrixData[7] - m.matrixData[6] * m.matrixData[1]) * invD;
float i = (m.matrixData[0] * m.matrixData[4] - m.matrixData[1] * m.matrixData[3]) * invD;
matrixData[0] = a;
matrixData[1] = b;
matrixData[2] = c;
matrixData[3] = d;
matrixData[4] = e;
matrixData[5] = f;
matrixData[6] = g;
matrixData[7] = h;
matrixData[8] = i;
}
Matrix Matrix::getInverseOfMatrix() const
{
Matrix result;
result.setMatrixAsInvertedMatrix(*this);
return result;
}
void Matrix::invertMatrix()
{
setMatrixAsInvertedMatrix(*this);
}
// transpose matrix
void Matrix::setMatrixAsTransposedMatrix(const Matrix& m)
{
// 0 3 6 -> 0 1 2
// 1 4 7 3 4 5
// 2 5 8 6 7 8
matrixData[0] = m.matrixData[0];
matrixData[3] = m.matrixData[1];
matrixData[6] = m.matrixData[2];
matrixData[1] = m.matrixData[3];
matrixData[4] = m.matrixData[4];
matrixData[7] = m.matrixData[5];
matrixData[2] = m.matrixData[6];
matrixData[5] = m.matrixData[7];
matrixData[8] = m.matrixData[8];
}
Matrix Matrix::getTransposeOfMatrix() const
{
Matrix result;
result.setMatrixAsTransposedMatrix(*this);
return result;
}
// vector transformation
Vector3n Matrix::operator * (const Vector3n& v) const
{
return Vector3n(
matrixData[0] * v.x + matrixData[3] * v.y + matrixData[6] * v.z,
matrixData[1] * v.x + matrixData[4] * v.y + matrixData[7] * v.z,
matrixData[2] * v.x + matrixData[5] * v.y + matrixData[8] * v.z
);
}
Vector3n Matrix::transformVectorByMatrix(const Vector3n& v) const
{
return (*this) * v;
}
} | 8,161 | 3,775 |
#include <stdio.h>
#include <zlib.h>
#include <string.h>
#include <stdlib.h>
#include "gzip_mem.h"
#define OF(args) args
#define OS_CODE 3 // unix
#if MAX_MEM_LEVEL >= 8
# define DEF_MEM_LEVEL 8
#else
# define DEF_MEM_LEVEL MAX_MEM_LEVEL
#endif
/* default memLevel */
#define Z_BUFSIZE 16384
#define ALLOC(size) malloc( size )
#define TRYFREE(p) free( p )
static int gz_magic[2] = {0x1f, 0x8b}; /* gzip magic header */
/* gzip flag byte */
#define ASCII_FLAG 0x01 /* bit 0 set: file probably ascii text */
#define HEAD_CRC 0x02 /* bit 1 set: header CRC present */
#define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
#define ORIG_NAME 0x08 /* bit 3 set: original file name present */
#define COMMENT 0x10 /* bit 4 set: file comment present */
#define RESERVED 0xE0 /* bits 5..7: reserved */
typedef int ( * XGZFILE_PROC_READ )( void* user_cb , void* , int len );
typedef int ( * XGZFILE_PROC_WRITE )( void* user_cb , const void* , int len );
typedef struct xmem_gzstream {
z_stream stream;
int z_err; /* error code for last stream operation */
int z_eof; /* set if end of input file */
XGZFILE_PROC_READ proc_read ;
XGZFILE_PROC_WRITE proc_write;
void* user_cb ;
Byte *inbuf; /* input buffer */
Byte *outbuf; /* output buffer */
uLong crc; /* crc32 of uncompressed data */
char *msg; /* error message */
int transparent; /* 1 if input file is not a .gz file */
char mode; /* 'w' or 'r' */
long startpos; /* start of compressed data in file (header skipped) */
} xmem_gzstream;
static int get_byte OF((xmem_gzstream *s));
static int check_header OF((xmem_gzstream *s)); /*! return bytes of read. */
static int destroy OF((xmem_gzstream *s));
static void putLong OF((xmem_gzstream *s , uLong x));
static uLong getLong OF((xmem_gzstream *s));
xmem_gzstream* XGZFILE_open(
XGZFILE_PROC_READ proc_read ,
XGZFILE_PROC_WRITE proc_write ,
void* user_cb ,
int create_flag ,
int level )
{
int err;
int strategy = Z_DEFAULT_STRATEGY; /* compression strategy */
static Byte simpleheader[] = {
0x1f, 0x8b, Z_DEFLATED , 0 , 0 , 0 , 0 , 0 , 0 , OS_CODE };
xmem_gzstream *s;
if( (create_flag&&!proc_write) ||
(!create_flag&&!proc_read) )
return Z_NULL;
s = (xmem_gzstream *)ALLOC( sizeof(xmem_gzstream) );
if( !s ) return Z_NULL;
s->stream.zalloc = (alloc_func)0;
s->stream.zfree = (free_func)0;
s->stream.opaque = (voidpf)0;
s->stream.next_in = s->inbuf = Z_NULL;
s->stream.next_out = s->outbuf = Z_NULL;
s->stream.avail_in = s->stream.avail_out = 0;
s->proc_read = proc_read ;
s->proc_write = proc_write;
s->user_cb = user_cb ;
s->z_err = Z_OK;
s->z_eof = 0;
s->crc = crc32(0L, Z_NULL, 0);
s->msg = NULL;
s->transparent = 0;
s->mode = create_flag ? 'w' : 'r';
if( create_flag )
{
err = deflateInit2(&(s->stream), level,
Z_DEFLATED, -MAX_WBITS, DEF_MEM_LEVEL, strategy);
s->stream.next_out = s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
if (err != Z_OK || s->outbuf == Z_NULL) {
return destroy(s), (xmem_gzstream*)Z_NULL;
}
}
else
{
s->stream.next_in = s->inbuf = (Byte*)ALLOC(Z_BUFSIZE);
err = inflateInit2(&(s->stream), -MAX_WBITS);
if (err != Z_OK || s->inbuf == Z_NULL) {
return destroy(s), (xmem_gzstream*)Z_NULL;
}
}
s->stream.avail_out = Z_BUFSIZE;
if( create_flag )
{
s->proc_write( s->user_cb , simpleheader , 10 );
s->startpos = 10L;
}
else
{
s->startpos = check_header(s);
}
return (xmem_gzstream*)s;
}
int XGZFILE_read ( xmem_gzstream* file , void* buf , int len )
{
xmem_gzstream *s = (xmem_gzstream*)file;
Bytef *start = (Bytef*)buf; /* starting point for crc computation */
Byte *next_out; /* == stream.next_out but not forced far (for MSDOS) */
if( !s || s->mode != 'r' ) return Z_STREAM_ERROR;
if (s->z_err == Z_DATA_ERROR || s->z_err == Z_ERRNO) return -1;
if (s->z_err == Z_STREAM_END) return 0; /* -1 */
next_out = (Byte*)buf;
s->stream.next_out = (Bytef*)buf;
s->stream.avail_out = len;
while (s->stream.avail_out != 0) {
if (s->transparent) {
/* Copy first the lookahead bytes: */
uInt n = s->stream.avail_in;
if (n > s->stream.avail_out) n = s->stream.avail_out;
if (n > 0) {
memcpy(s->stream.next_out, s->stream.next_in, n);
next_out += n;
s->stream.next_out = next_out;
s->stream.next_in += n;
s->stream.avail_out -= n;
s->stream.avail_in -= n;
}
if (s->stream.avail_out > 0) {
s->stream.avail_out -= s->proc_read( s->user_cb ,
next_out , s->stream.avail_out );
}
len -= s->stream.avail_out;
s->stream.total_in += (uLong)len;
s->stream.total_out += (uLong)len;
if (len == 0) s->z_eof = 1;
return (int)len;
}
if (s->stream.avail_in == 0 && !s->z_eof) {
/* errno = 0; */
s->stream.avail_in = s->proc_read( s->user_cb ,
s->inbuf , Z_BUFSIZE );
if (s->stream.avail_in == 0) {
s->z_eof = 1;
}
s->stream.next_in = s->inbuf;
}
s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
if (s->z_err == Z_STREAM_END) {
/* Check CRC and original size */
s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
start = s->stream.next_out;
if (getLong(s) != s->crc) {
s->z_err = Z_DATA_ERROR;
} else {
(void)getLong(s);
/* The uncompressed length returned by above getlong() may
* be different from s->stream.total_out) in case of
* concatenated .gz files. Check for such files:
*/
check_header(s);
if (s->z_err == Z_OK) {
uLong total_in = s->stream.total_in;
uLong total_out = s->stream.total_out;
inflateReset(&(s->stream));
s->stream.total_in = total_in;
s->stream.total_out = total_out;
s->crc = crc32(0L, Z_NULL, 0);
}
}
}
if (s->z_err != Z_OK || s->z_eof) break;
}
s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
return len - s->stream.avail_out ;
}
int XGZFILE_write( xmem_gzstream* file , const void* buf , int len )
{
xmem_gzstream *s = (xmem_gzstream*)file;
if (s == NULL || s->mode != 'w') return Z_STREAM_ERROR;
s->stream.next_in = (Bytef*)buf;
s->stream.avail_in = len;
while (s->stream.avail_in != 0) {
if (s->stream.avail_out == 0) {
s->stream.next_out = s->outbuf;
if( s->proc_write( s->user_cb , s->outbuf , Z_BUFSIZE ) != Z_BUFSIZE ) {
s->z_err = Z_ERRNO;
break;
}
s->stream.avail_out = Z_BUFSIZE;
}
s->z_err = deflate(&(s->stream), Z_NO_FLUSH);
if (s->z_err != Z_OK) break;
}
s->crc = crc32(s->crc, (const Bytef *)buf, len);
return (int)(len - s->stream.avail_in);
}
int XGZFILE_flush( xmem_gzstream* file , int flush )
{
xmem_gzstream *s = (xmem_gzstream*)file;
uInt len;
int done = 0;
if( !s || s->mode != 'w' ) return Z_STREAM_ERROR;
s->stream.avail_in = 0; /* should be zero already anyway */
for (;;) {
len = Z_BUFSIZE - s->stream.avail_out;
if (len != 0) {
if( s->proc_write( s->user_cb , s->outbuf , len ) != (int)len ) {
s->z_err = Z_ERRNO;
return Z_ERRNO;
}
s->stream.next_out = s->outbuf;
s->stream.avail_out = Z_BUFSIZE;
}
if (done) break;
s->z_err = deflate(&(s->stream), flush);
/* Ignore the second of two consecutive flushes: */
if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK;
/* deflate has finished flushing only when it hasn't used up
* all the available space in the output buffer:
*/
done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
}
return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
}
int XGZFILE_eof ( xmem_gzstream* file )
{
xmem_gzstream *s = (xmem_gzstream*)file;
return (s == NULL || s->mode != 'r') ? 0 : s->z_eof;
}
int XGZFILE_close( xmem_gzstream* file )
{
int err;
xmem_gzstream *s = (xmem_gzstream*)file;
if (s == NULL) return Z_STREAM_ERROR;
if (s->mode == 'w') {
err = XGZFILE_flush (file, Z_FINISH);
if (err != Z_OK) return destroy((xmem_gzstream*)file);
putLong (s , s->crc);
putLong (s , s->stream.total_in);
}
return destroy((xmem_gzstream*)file);
}
static int get_byte (xmem_gzstream *s)
{
if (s->z_eof) return -1;
if (s->stream.avail_in == 0) {
/* errno = 0; */
s->stream.avail_in = s->proc_read( s->user_cb , s->inbuf , Z_BUFSIZE );
if (s->stream.avail_in == 0) {
s->z_eof = 1;
return -1;
}
s->stream.next_in = s->inbuf;
}
s->stream.avail_in--;
return *(s->stream.next_in)++;
}
static void putLong (xmem_gzstream *s, uLong x)
{
int n;
char ch;
for (n = 0; n < 4; n++) {
ch = (char)(x & 0xff);
s->proc_write( s->user_cb , &ch , 1 );
x >>= 8;
}
}
static uLong getLong (xmem_gzstream *s)
{
uLong x = (uLong)get_byte(s);
int c;
x += ((uLong)get_byte(s))<<8;
x += ((uLong)get_byte(s))<<16;
c = get_byte(s);
if (c == -1) s->z_err = Z_DATA_ERROR;
x += ((uLong)c)<<24;
return x;
}
static int destroy (xmem_gzstream *s)
{
int err = Z_OK;
if (!s) return Z_STREAM_ERROR;
TRYFREE(s->msg);
if (s->stream.state != NULL) {
if (s->mode == 'w') {
err = deflateEnd(&(s->stream));
} else if (s->mode == 'r') {
err = inflateEnd(&(s->stream));
}
}
if (s->z_err < 0) err = s->z_err;
TRYFREE(s->inbuf);
TRYFREE(s->outbuf);
TRYFREE(s);
return err;
}
static int check_header (xmem_gzstream *s) /*! return bytes of read. */
{
int method; /* method byte */
int flags; /* flags byte */
uInt len;
int c;
int lenret;
int ch;
/* Check the gzip magic header */
for (len = 0; len < 2; len++) {
c = get_byte(s);
if (c != gz_magic[len]) {
if (len != 0) s->stream.avail_in++, s->stream.next_in--;
if (c != -1) {
s->stream.avail_in++, s->stream.next_in--;
s->transparent = 1;
}
s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END;
return len;
}
}
lenret = 2;
method = get_byte(s); if( method != -1 ) ++lenret;
flags = get_byte(s); if( flags != -1 ) ++lenret;
if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
s->z_err = Z_DATA_ERROR;
return lenret;
}
/* Discard time, xflags and OS code: */
for (len = 0; len < 6; len++)
{
ch = get_byte(s);
if( ch != -1 ) ++lenret;
else {
s->z_err = Z_DATA_ERROR;
return lenret;
}
}
if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
ch = get_byte(s); if( ch != -1 ) ++lenret;
len = ch;
ch = get_byte(s); if( ch != -1 ) ++lenret;
len += ((uInt)ch)<<8;
/* len is garbage if -1 but the loop below will quit anyway */
while (len-- != 0 && get_byte(s) != -1) ++lenret;
}
if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
while ((c = get_byte(s)) != 0 && c != -1) ++lenret;
}
if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
while ((c = get_byte(s)) != 0 && c != -1) ++lenret;
}
if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
for (len = 0; len < 2; len++) if( get_byte(s) != -1 ) ++lenret;
}
s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
return lenret;
}
typedef unsigned char XU8;
static XU8 z_input[] = {
0x1F,0x8B,0x08,0x08,0x59,0x96,0x9C,0x46,0x00,0x03,0x74,0x35,0x00,0x2B,0xC9,0xC8
,0x2C,0x56,0x00,0xA2,0x44,0x85,0x92,0xD4,0xE2,0x12,0x85,0xB4,0xCC,0x9C,0x54,0x5E
,0xAE,0x12,0x4C,0x41,0x00,0x9A,0xA3,0x62,0x77,0x28,0x00,0x00,0x00
};
static XU8 x_text[] = {
0x74,0x68,0x69,0x73,0x20,0x69,0x73,0x20,0x61,0x20,0x74,0x65,0x73,0x74,0x20,0x66
,0x69,0x6C,0x65,0x0D,0x0A,0x74,0x68,0x69,0x73,0x20,0x69,0x73,0x20,0x61,0x20,0x74
,0x65,0x73,0x74,0x20,0x66,0x69,0x6C,0x65
};
const static string * pstring = NULL;
/*
static int X_test_read( void* user_cb , void* buff , int len )
{
if( *(int*)user_cb >= sizeof( z_input ) || len <= 0 )
return 0;
if( len > (int)(sizeof( z_input ) - *(int*)user_cb) )
len = sizeof( z_input ) - *(int*)user_cb;
memcpy( buff , z_input + *(int*)user_cb , len );
*(int*)user_cb += len;
return len;
}
//*/
static int X_test_read( void* user_cb , void* buff , int len )
{
if(pstring == NULL)
return 0;
if( *(int*)user_cb >= pstring->size() || len <= 0 )
return 0;
if( len > (int)(pstring->size() - *(int*)user_cb) )
len = pstring->size() - *(int*)user_cb;
memcpy( buff , pstring->data() + *(int*)user_cb , len );
*(int*)user_cb += len;
return len;
}
/*
int main()
{
int off = 0 , len;
XU8 buff[100];
xmem_gzstream* strm = XGZFILE_open( X_test_read , NULL , &off , 0 , -1 );
len = XGZFILE_read( strm , buff , sizeof( buff ) );
XGZFILE_close( strm );
if( len != sizeof( x_text ) || memcmp( x_text , buff , len ) )
printf( "error\n" );
return 0;
}
//*/
string GUnzip(const string & zip_mem)
{
int off = 0 , len;
XU8 buff[1024] ;
memset(buff,0,sizeof(buff));
string res;
pstring = &zip_mem;
xmem_gzstream* strm = XGZFILE_open( X_test_read , NULL , &off , 0 , -1 );
while(len = XGZFILE_read( strm , buff , sizeof( buff ) ))
{
res.append((char *)buff,len);
memset(buff,0,sizeof(buff));
}
XGZFILE_close( strm );
return res;
}
| 15,068 | 6,079 |
#include "RecoParticleFlow/PFClusterTools/interface/Utils.h"
#include <stdio.h>
#include <math.h>
#include <regex.h>
#include <glob.h>
#include "TCanvas.h"
#include "TVector3.h"
using namespace std;
using namespace pftools;
bool Utils::StringMatch(const char* str, const char* pattern) {
int status;
regex_t re;
if( regcomp(&re, pattern, REG_EXTENDED|REG_NOSUB) != 0 )
return false;
status = regexec(&re, str, (size_t)0, NULL, 0);
regfree(&re);
if (status != 0)
return false;
return true;
}
TCanvas* Utils::DivideCanvas( TCanvas *cv, int nPads ) {
if( !cv ) return 0;
if( nPads<=1 ) return cv;
int sqnP = (unsigned int) (sqrt( nPads ));
int nC = sqnP;
int nL = sqnP;
while( nC*nL < nPads )
if( nC < nL ) nC++;
else nL++;
cv->Divide( nC, nL, 0.005, 0.005, 0 );
return cv;
}
vector<string> Utils::Glob(const char* pattern) {
glob_t globbuf;
globbuf.gl_offs = 2;
glob(pattern, GLOB_TILDE|GLOB_BRACE|GLOB_MARK, NULL, &globbuf);
vector<string> results;
for(unsigned i=0; i<globbuf.gl_pathc; i++) {
results.push_back(globbuf.gl_pathv[i]);
}
globfree(&globbuf);
return results;
}
string Utils::Date() {
string date("date +%d%b%Y_%H%M%S");
FILE *in = popen(date.c_str(), "r");
char result[100];
if(fscanf(in,"%s",result) != EOF) {
return string(result);
}
else return string("");
}
TVector3 Utils::VectorEPRtoXYZ( const TVector3& posepr ) {
TVector3 posxyz(1,1,1); // to be called before a SetMag
posxyz.SetMag( posepr.Z() );
double theta = 2*atan( exp( - posepr.X() ) );
posxyz.SetTheta( theta );
posxyz.SetPhi( posepr.Y() );
return posxyz;
}
| 1,683 | 748 |
/** \class EcalMaxSampleUncalibRecHitProducer
* produce ECAL uncalibrated rechits from dataframes
*
* \author G. Franzoni, E. Di Marco
*
*/
#include "RecoLocalCalo/EcalRecProducers/plugins/EcalUncalibRecHitWorkerMaxSample.h"
#include "DataFormats/Common/interface/Handle.h"
#include "DataFormats/EcalDigi/interface/EcalDigiCollections.h"
#include "DataFormats/EcalRecHit/interface/EcalUncalibratedRecHit.h"
#include "DataFormats/EcalRecHit/interface/EcalRecHitCollections.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include <FWCore/ParameterSet/interface/ConfigurationDescriptions.h>
#include <FWCore/ParameterSet/interface/ParameterSetDescription.h>
#include <FWCore/ParameterSet/interface/EmptyGroupDescription.h>
#include <cmath>
#include <iomanip>
#include <iostream>
#include <vector>
EcalUncalibRecHitWorkerMaxSample::EcalUncalibRecHitWorkerMaxSample(const edm::ParameterSet& ps,
edm::ConsumesCollector& c)
: EcalUncalibRecHitWorkerRunOneDigiBase(ps, c) {}
void EcalUncalibRecHitWorkerMaxSample::set(const edm::EventSetup& es) {}
bool EcalUncalibRecHitWorkerMaxSample::run(const edm::Event& evt,
const EcalDigiCollection::const_iterator& itdg,
EcalUncalibratedRecHitCollection& result) {
DetId detid(itdg->id());
if (detid.subdetId() == EcalBarrel) {
result.push_back(ebAlgo_.makeRecHit(*itdg, nullptr, nullptr, nullptr, nullptr));
} else {
result.push_back(eeAlgo_.makeRecHit(*itdg, nullptr, nullptr, nullptr, nullptr));
}
return true;
}
edm::ParameterSetDescription EcalUncalibRecHitWorkerMaxSample::getAlgoDescription() {
edm::ParameterSetDescription psd;
return psd; //.addNode(std::unique_ptr<edm::ParameterDescriptionNode>(new edm::EmptyGroupDescription()));
}
#include "FWCore/Framework/interface/MakerMacros.h"
#include "RecoLocalCalo/EcalRecProducers/interface/EcalUncalibRecHitWorkerFactory.h"
DEFINE_EDM_PLUGIN(EcalUncalibRecHitWorkerFactory, EcalUncalibRecHitWorkerMaxSample, "EcalUncalibRecHitWorkerMaxSample");
#include "RecoLocalCalo/EcalRecProducers/interface/EcalUncalibRecHitFillDescriptionWorkerFactory.h"
DEFINE_EDM_PLUGIN(EcalUncalibRecHitFillDescriptionWorkerFactory,
EcalUncalibRecHitWorkerMaxSample,
"EcalUncalibRecHitWorkerMaxSample");
| 2,473 | 838 |
#include "athena/MemoryWriter.hpp"
#include <cstdio>
#include <cstring>
#ifdef HW_RVL
#include <malloc.h>
#endif // HW_RVL
namespace athena::io {
MemoryWriter::MemoryWriter(atUint8* data, atUint64 length, bool takeOwnership)
: m_data(data), m_length(length), m_bufferOwned(takeOwnership) {
if (!data) {
atError(fmt("data cannot be NULL"));
setError();
return;
}
}
MemoryWriter::~MemoryWriter() {
if (m_bufferOwned)
delete m_data;
m_data = nullptr;
m_length = 0;
}
MemoryCopyWriter::MemoryCopyWriter(atUint8* data, atUint64 length) {
m_data = data;
m_length = length;
m_position = 0;
m_bufferOwned = false;
if (length == 0) {
atError(fmt("length cannot be 0"));
setError();
return;
}
m_dataCopy.reset(new atUint8[length]);
m_data = m_dataCopy.get();
if (data)
memmove(m_data, data, length);
}
MemoryCopyWriter::MemoryCopyWriter(std::string_view filename) {
m_filepath = filename;
m_length = 0x10;
m_position = 0;
m_dataCopy.reset(new atUint8[m_length]);
m_data = m_dataCopy.get();
m_bufferOwned = false;
if (!m_data) {
atError(fmt("Could not allocate memory!"));
setError();
return;
}
}
void MemoryWriter::seek(atInt64 position, SeekOrigin origin) {
switch (origin) {
case SeekOrigin::Begin:
if (position < 0) {
atError(fmt("Position outside stream bounds"));
setError();
return;
}
if ((atUint64)position > m_length) {
atError(fmt("data exceeds available buffer space"));
setError();
return;
}
m_position = position;
break;
case SeekOrigin::Current:
if ((((atInt64)m_position + position) < 0)) {
atError(fmt("Position outside stream bounds"));
setError();
return;
}
if (m_position + position > m_length) {
atError(fmt("data exceeds available buffer space"));
setError();
return;
}
m_position += position;
break;
case SeekOrigin::End:
if (((atInt64)m_length - position) < 0) {
atError(fmt("Position outside stream bounds"));
setError();
return;
}
if ((atUint64)position > m_length) {
atError(fmt("data exceeds available buffer space"));
setError();
return;
}
m_position = m_length - position;
break;
}
}
void MemoryCopyWriter::seek(atInt64 position, SeekOrigin origin) {
switch (origin) {
case SeekOrigin::Begin:
if (position < 0) {
atError(fmt("Position outside stream bounds"));
setError();
return;
}
if ((atUint64)position > m_length)
resize(position);
m_position = position;
break;
case SeekOrigin::Current:
if ((((atInt64)m_position + position) < 0)) {
atError(fmt("Position outside stream bounds"));
setError();
return;
}
if (m_position + position > m_length)
resize(m_position + position);
m_position += position;
break;
case SeekOrigin::End:
if (((atInt64)m_length - position) < 0) {
atError(fmt("Position outside stream bounds"));
setError();
return;
}
if ((atUint64)position > m_length)
resize(position);
m_position = m_length - position;
break;
}
}
void MemoryWriter::setData(atUint8* data, atUint64 length, bool takeOwnership) {
if (m_bufferOwned)
delete m_data;
m_data = data;
m_length = length;
m_position = 0;
m_bufferOwned = takeOwnership;
}
void MemoryCopyWriter::setData(const atUint8* data, atUint64 length) {
m_dataCopy.reset(new atUint8[length]);
m_data = m_dataCopy.get();
memmove(m_data, data, length);
m_length = length;
m_position = 0;
m_bufferOwned = false;
}
atUint8* MemoryWriter::data() const {
atUint8* ret = new atUint8[m_length];
memset(ret, 0, m_length);
memmove(ret, m_data, m_length);
return ret;
}
void MemoryWriter::save(std::string_view filename) {
if (filename.empty() && m_filepath.empty()) {
atError(fmt("No file specified, cannot save."));
setError();
return;
}
if (!filename.empty()) {
m_filepath = filename;
}
std::unique_ptr<FILE, decltype(&std::fclose)> out{std::fopen(m_filepath.c_str(), "wb"), std::fclose};
if (!out) {
atError(fmt("Unable to open file '{}'"), m_filepath);
setError();
return;
}
atUint64 done = 0;
atUint64 blocksize = BLOCKSZ;
do {
if (blocksize > m_length - done) {
blocksize = m_length - done;
}
const atInt64 ret = std::fwrite(m_data + done, 1, blocksize, out.get());
if (ret < 0) {
atError(fmt("Error writing data to disk"));
setError();
return;
}
if (ret == 0) {
break;
}
done += blocksize;
} while (done < m_length);
}
void MemoryWriter::writeUBytes(const atUint8* data, atUint64 length) {
if (!data) {
atError(fmt("data cannnot be NULL"));
setError();
return;
}
if (m_position + length > m_length) {
atError(fmt("data length exceeds available buffer space"));
setError();
return;
}
memmove(reinterpret_cast<atInt8*>(m_data + m_position), data, length);
m_position += length;
}
void MemoryCopyWriter::writeUBytes(const atUint8* data, atUint64 length) {
if (!data) {
atError(fmt("data cannnot be NULL"));
setError();
return;
}
if (m_position + length > m_length)
resize(m_position + length);
memmove(reinterpret_cast<atInt8*>(m_data + m_position), data, length);
m_position += length;
}
void MemoryCopyWriter::resize(atUint64 newSize) {
if (newSize < m_length) {
atError(fmt("New size cannot be less to the old size."));
return;
}
// Allocate and copy new buffer
auto newArray = std::make_unique<atUint8[]>(newSize);
if (m_dataCopy) {
std::memmove(newArray.get(), m_dataCopy.get(), m_length);
}
m_dataCopy = std::move(newArray);
// Swap the pointer and size out for the new ones.
m_data = m_dataCopy.get();
m_length = newSize;
}
} // namespace athena::io
| 5,936 | 2,183 |
/*
* Copyright (c) 2012 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/rtp_rtcp/source/forward_error_correction_internal.h"
#include <cassert>
#include <cstring>
#include "modules/rtp_rtcp/source/fec_private_tables_random.h"
#include "modules/rtp_rtcp/source/fec_private_tables_bursty.h"
namespace {
// Allow for different modes of protection for packets in UEP case.
enum ProtectionMode
{
kModeNoOverlap,
kModeOverlap,
kModeBiasFirstPacket,
};
/**
* Fits an input mask (subMask) to an output mask.
* The mask is a matrix where the rows are the FEC packets,
* and the columns are the source packets the FEC is applied to.
* Each row of the mask is represented by a number of mask bytes.
*
* \param[in] numMaskBytes The number of mask bytes of output mask.
* \param[in] numSubMaskBytes The number of mask bytes of input mask.
* \param[in] numRows The number of rows of the input mask.
* \param[in] subMask A pointer to hold the input mask, of size
* [0, numRows * numSubMaskBytes]
* \param[out] packetMask A pointer to hold the output mask, of size
* [0, x * numMaskBytes], where x >= numRows.
*/
void FitSubMask(int numMaskBytes,
int numSubMaskBytes,
int numRows,
const uint8_t* subMask,
uint8_t* packetMask)
{
if (numMaskBytes == numSubMaskBytes)
{
memcpy(packetMask, subMask, numRows * numSubMaskBytes);
}
else
{
for (int i = 0; i < numRows; i++)
{
int pktMaskIdx = i * numMaskBytes;
int pktMaskIdx2 = i * numSubMaskBytes;
for (int j = 0; j < numSubMaskBytes; j++)
{
packetMask[pktMaskIdx] = subMask[pktMaskIdx2];
pktMaskIdx++;
pktMaskIdx2++;
}
}
}
}
/**
* Shifts a mask by number of columns (bits), and fits it to an output mask.
* The mask is a matrix where the rows are the FEC packets,
* and the columns are the source packets the FEC is applied to.
* Each row of the mask is represented by a number of mask bytes.
*
* \param[in] numMaskBytes The number of mask bytes of output mask.
* \param[in] numSubMaskBytes The number of mask bytes of input mask.
* \param[in] numColumnShift The number columns to be shifted, and
* the starting row for the output mask.
* \param[in] endRow The ending row for the output mask.
* \param[in] subMask A pointer to hold the input mask, of size
* [0, (endRowFEC - startRowFec) * numSubMaskBytes]
* \param[out] packetMask A pointer to hold the output mask, of size
* [0, x * numMaskBytes], where x >= endRowFEC.
*/
// TODO (marpan): This function is doing three things at the same time:
// shift within a byte, byte shift and resizing.
// Split up into subroutines.
void ShiftFitSubMask(int numMaskBytes,
int resMaskBytes,
int numColumnShift,
int endRow,
const uint8_t* subMask,
uint8_t* packetMask)
{
// Number of bit shifts within a byte
const int numBitShifts = (numColumnShift % 8);
const int numByteShifts = numColumnShift >> 3;
// Modify new mask with sub-mask21.
// Loop over the remaining FEC packets.
for (int i = numColumnShift; i < endRow; i++)
{
// Byte index of new mask, for row i and column resMaskBytes,
// offset by the number of bytes shifts
int pktMaskIdx = i * numMaskBytes + resMaskBytes - 1 + numByteShifts;
// Byte index of subMask, for row i and column resMaskBytes
int pktMaskIdx2 =
(i - numColumnShift) * resMaskBytes + resMaskBytes - 1;
uint8_t shiftRightCurrByte = 0;
uint8_t shiftLeftPrevByte = 0;
uint8_t combNewByte = 0;
// Handle case of numMaskBytes > resMaskBytes:
// For a given row, copy the rightmost "numBitShifts" bits
// of the last byte of subMask into output mask.
if (numMaskBytes > resMaskBytes)
{
shiftLeftPrevByte =
(subMask[pktMaskIdx2] << (8 - numBitShifts));
packetMask[pktMaskIdx + 1] = shiftLeftPrevByte;
}
// For each row i (FEC packet), shift the bit-mask of the subMask.
// Each row of the mask contains "resMaskBytes" of bytes.
// We start from the last byte of the subMask and move to first one.
for (int j = resMaskBytes - 1; j > 0; j--)
{
// Shift current byte of sub21 to the right by "numBitShifts".
shiftRightCurrByte =
subMask[pktMaskIdx2] >> numBitShifts;
// Fill in shifted bits with bits from the previous (left) byte:
// First shift the previous byte to the left by "8-numBitShifts".
shiftLeftPrevByte =
(subMask[pktMaskIdx2 - 1] << (8 - numBitShifts));
// Then combine both shifted bytes into new mask byte.
combNewByte = shiftRightCurrByte | shiftLeftPrevByte;
// Assign to new mask.
packetMask[pktMaskIdx] = combNewByte;
pktMaskIdx--;
pktMaskIdx2--;
}
// For the first byte in the row (j=0 case).
shiftRightCurrByte = subMask[pktMaskIdx2] >> numBitShifts;
packetMask[pktMaskIdx] = shiftRightCurrByte;
}
}
} // namespace
namespace webrtc {
namespace internal {
PacketMaskTable::PacketMaskTable(FecMaskType fec_mask_type,
int num_media_packets)
: fec_mask_type_(InitMaskType(fec_mask_type, num_media_packets)),
fec_packet_mask_table_(InitMaskTable(fec_mask_type_)) {
}
// Sets |fec_mask_type_| to the type of packet mask selected. The type of
// packet mask selected is based on |fec_mask_type| and |numMediaPackets|.
// If |numMediaPackets| is larger than the maximum allowed by |fec_mask_type|
// for the bursty type, then the random type is selected.
FecMaskType PacketMaskTable::InitMaskType(FecMaskType fec_mask_type,
int num_media_packets) {
// The mask should not be bigger than |packetMaskTbl|.
assert(num_media_packets <= static_cast<int>(sizeof(kPacketMaskRandomTbl) /
sizeof(*kPacketMaskRandomTbl)));
switch (fec_mask_type) {
case kFecMaskRandom: {
return kFecMaskRandom;
}
case kFecMaskBursty: {
int max_media_packets = static_cast<int>(sizeof(kPacketMaskBurstyTbl) /
sizeof(*kPacketMaskBurstyTbl));
if (num_media_packets > max_media_packets) {
return kFecMaskRandom;
} else {
return kFecMaskBursty;
}
}
}
assert(false);
return kFecMaskRandom;
}
// Returns the pointer to the packet mask tables corresponding to type
// |fec_mask_type|.
const uint8_t*** PacketMaskTable::InitMaskTable(FecMaskType fec_mask_type) {
switch (fec_mask_type) {
case kFecMaskRandom: {
return kPacketMaskRandomTbl;
}
case kFecMaskBursty: {
return kPacketMaskBurstyTbl;
}
}
assert(false);
return kPacketMaskRandomTbl;
}
// Remaining protection after important (first partition) packet protection
void RemainingPacketProtection(int numMediaPackets,
int numFecRemaining,
int numFecForImpPackets,
int numMaskBytes,
ProtectionMode mode,
uint8_t* packetMask,
const PacketMaskTable& mask_table)
{
if (mode == kModeNoOverlap)
{
// subMask21
const int lBit =
(numMediaPackets - numFecForImpPackets) > 16 ? 1 : 0;
const int resMaskBytes =
(lBit == 1) ? kMaskSizeLBitSet : kMaskSizeLBitClear;
const uint8_t* packetMaskSub21 =
mask_table.fec_packet_mask_table()
[numMediaPackets - numFecForImpPackets - 1]
[numFecRemaining - 1];
ShiftFitSubMask(numMaskBytes, resMaskBytes, numFecForImpPackets,
(numFecForImpPackets + numFecRemaining),
packetMaskSub21, packetMask);
}
else if (mode == kModeOverlap || mode == kModeBiasFirstPacket)
{
// subMask22
const uint8_t* packetMaskSub22 =
mask_table.fec_packet_mask_table()
[numMediaPackets - 1][numFecRemaining - 1];
FitSubMask(numMaskBytes, numMaskBytes, numFecRemaining, packetMaskSub22,
&packetMask[numFecForImpPackets * numMaskBytes]);
if (mode == kModeBiasFirstPacket)
{
for (int i = 0; i < numFecRemaining; i++)
{
int pktMaskIdx = i * numMaskBytes;
packetMask[pktMaskIdx] = packetMask[pktMaskIdx] | (1 << 7);
}
}
}
else
{
assert(false);
}
}
// Protection for important (first partition) packets
void ImportantPacketProtection(int numFecForImpPackets,
int numImpPackets,
int numMaskBytes,
uint8_t* packetMask,
const PacketMaskTable& mask_table)
{
const int lBit = numImpPackets > 16 ? 1 : 0;
const int numImpMaskBytes =
(lBit == 1) ? kMaskSizeLBitSet : kMaskSizeLBitClear;
// Get subMask1 from table
const uint8_t* packetMaskSub1 =
mask_table.fec_packet_mask_table()
[numImpPackets - 1][numFecForImpPackets - 1];
FitSubMask(numMaskBytes, numImpMaskBytes,
numFecForImpPackets, packetMaskSub1, packetMask);
}
// This function sets the protection allocation: i.e., how many FEC packets
// to use for numImp (1st partition) packets, given the: number of media
// packets, number of FEC packets, and number of 1st partition packets.
int SetProtectionAllocation(int numMediaPackets,
int numFecPackets,
int numImpPackets)
{
// TODO (marpan): test different cases for protection allocation:
// Use at most (allocPar * numFecPackets) for important packets.
float allocPar = 0.5;
int maxNumFecForImp = allocPar * numFecPackets;
int numFecForImpPackets = (numImpPackets < maxNumFecForImp) ?
numImpPackets : maxNumFecForImp;
// Fall back to equal protection in this case
if (numFecPackets == 1 && (numMediaPackets > 2 * numImpPackets))
{
numFecForImpPackets = 0;
}
return numFecForImpPackets;
}
// Modification for UEP: reuse the off-line tables for the packet masks.
// Note: these masks were designed for equal packet protection case,
// assuming random packet loss.
// Current version has 3 modes (options) to build UEP mask from existing ones.
// Various other combinations may be added in future versions.
// Longer-term, we may add another set of tables specifically for UEP cases.
// TODO (marpan): also consider modification of masks for bursty loss cases.
// Mask is characterized as (#packets_to_protect, #fec_for_protection).
// Protection factor defined as: (#fec_for_protection / #packets_to_protect).
// Let k=numMediaPackets, n=total#packets, (n-k)=numFecPackets, m=numImpPackets.
// For ProtectionMode 0 and 1:
// one mask (subMask1) is used for 1st partition packets,
// the other mask (subMask21/22, for 0/1) is for the remaining FEC packets.
// In both mode 0 and 1, the packets of 1st partition (numImpPackets) are
// treated equally important, and are afforded more protection than the
// residual partition packets.
// For numImpPackets:
// subMask1 = (m, t): protection = t/(m), where t=F(k,n-k,m).
// t=F(k,n-k,m) is the number of packets used to protect first partition in
// subMask1. This is determined from the function SetProtectionAllocation().
// For the left-over protection:
// Mode 0: subMask21 = (k-m,n-k-t): protection = (n-k-t)/(k-m)
// mode 0 has no protection overlap between the two partitions.
// For mode 0, we would typically set t = min(m, n-k).
// Mode 1: subMask22 = (k, n-k-t), with protection (n-k-t)/(k)
// mode 1 has protection overlap between the two partitions (preferred).
// For ProtectionMode 2:
// This gives 1st packet of list (which is 1st packet of 1st partition) more
// protection. In mode 2, the equal protection mask (which is obtained from
// mode 1 for t=0) is modified (more "1s" added in 1st column of packet mask)
// to bias higher protection for the 1st source packet.
// Protection Mode 2 may be extended for a sort of sliding protection
// (i.e., vary the number/density of "1s" across columns) across packets.
void UnequalProtectionMask(int numMediaPackets,
int numFecPackets,
int numImpPackets,
int numMaskBytes,
uint8_t* packetMask,
const PacketMaskTable& mask_table)
{
// Set Protection type and allocation
// TODO (marpan): test/update for best mode and some combinations thereof.
ProtectionMode mode = kModeOverlap;
int numFecForImpPackets = 0;
if (mode != kModeBiasFirstPacket)
{
numFecForImpPackets = SetProtectionAllocation(numMediaPackets,
numFecPackets,
numImpPackets);
}
int numFecRemaining = numFecPackets - numFecForImpPackets;
// Done with setting protection type and allocation
//
// Generate subMask1
//
if (numFecForImpPackets > 0)
{
ImportantPacketProtection(numFecForImpPackets, numImpPackets,
numMaskBytes, packetMask,
mask_table);
}
//
// Generate subMask2
//
if (numFecRemaining > 0)
{
RemainingPacketProtection(numMediaPackets, numFecRemaining,
numFecForImpPackets, numMaskBytes,
mode, packetMask, mask_table);
}
}
void GeneratePacketMasks(int numMediaPackets,
int numFecPackets,
int numImpPackets,
bool useUnequalProtection,
const PacketMaskTable& mask_table,
uint8_t* packetMask)
{
assert(numMediaPackets > 0);
assert(numFecPackets <= numMediaPackets && numFecPackets > 0);
assert(numImpPackets <= numMediaPackets && numImpPackets >= 0);
int lBit = numMediaPackets > 16 ? 1 : 0;
const int numMaskBytes =
(lBit == 1) ? kMaskSizeLBitSet : kMaskSizeLBitClear;
// Equal-protection for these cases
if (!useUnequalProtection || numImpPackets == 0)
{
// Retrieve corresponding mask table directly:for equal-protection case.
// Mask = (k,n-k), with protection factor = (n-k)/k,
// where k = numMediaPackets, n=total#packets, (n-k)=numFecPackets.
memcpy(packetMask,
mask_table.fec_packet_mask_table()[numMediaPackets - 1]
[numFecPackets - 1],
numFecPackets * numMaskBytes);
}
else //UEP case
{
UnequalProtectionMask(numMediaPackets, numFecPackets, numImpPackets,
numMaskBytes, packetMask, mask_table);
} // End of UEP modification
} //End of GetPacketMasks
} // namespace internal
} // namespace webrtc
| 16,550 | 5,095 |
// 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.
#include "base/values.h"
#include "chrome/browser/external_protocol/auto_launch_protocols_policy_handler.h"
#include "chrome/browser/external_protocol/external_protocol_handler.h"
#include "chrome/browser/policy/policy_test_utils.h"
#include "chrome/browser/ui/browser.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/policy_constants.h"
#include "content/public/test/browser_test.h"
#include "url/gurl.h"
#include "url/origin.h"
namespace policy {
class ExternalProtocolPolicyBrowserTest : public PolicyTest {};
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsMalformedPolicy) {
const char kWildcardOrigin[] = "*";
const char kExampleScheme[] = "custom";
url::Origin test_origin = url::Origin::Create(GURL("https://example.test"));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
// Single dictionary for this test case, but erroneously not embedded
// in a list.
base::DictionaryValue protocol_origins_map;
// Set a protocol list with a matching protocol.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set origins list with a wildcard origin matching pattern.
base::ListValue origins;
origins.Append(kWildcardOrigin);
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map.Clone(), nullptr);
UpdateProviderPolicy(policies);
block_state = ExternalProtocolHandler::GetBlockState(
kExampleScheme, &test_origin, browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsNullInitiatingOrigin) {
const char kWildcardOrigin[] = "*";
const char kExampleScheme[] = "custom";
base::ListValue protocol_origins_map_list;
// Single dictionary in the list for this test case.
base::DictionaryValue protocol_origins_map;
// Set a protocol.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set an origins list with the wildcard origin matching pattern.
base::ListValue origins;
origins.Append(kWildcardOrigin);
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
protocol_origins_map_list.Append(std::move(protocol_origins_map));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
// Calling GetBlockState with a null initiating_origin should
// return UNKNOWN.
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, nullptr,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsEmptyOriginList) {
const char kExampleScheme[] = "custom";
url::Origin test_origin = url::Origin::Create(GURL("https://example.test"));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
base::ListValue protocol_origins_map_list;
// Single dictionary in the list for this test case.
base::DictionaryValue protocol_origins_map;
// Set a protocol list with a matching protocol.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set an empty origins list.
base::ListValue origins;
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
protocol_origins_map_list.Append(std::move(protocol_origins_map));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
block_state = ExternalProtocolHandler::GetBlockState(
kExampleScheme, &test_origin, browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsWildcardOriginList) {
const char kWildcardOrigin[] = "*";
const char kExampleScheme[] = "custom";
base::ListValue protocol_origins_map_list;
// Single dictionary in the list for this test case.
base::DictionaryValue protocol_origins_map;
// Set a protocol to match the test.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set an origins list with the wildcard origin matching pattern.
base::ListValue origins;
origins.Append(kWildcardOrigin);
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
protocol_origins_map_list.Append(std::move(protocol_origins_map));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
url::Origin test_origin = url::Origin::Create(GURL("https://example.test"));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsInvalidProtocols) {
const char kInvalidProtocol1[] = "custom:";
const char kInvalidProtocol2[] = "custom://";
const char kInvalidProtocol3[] = "custom//";
const char kWildcardOrigin[] = "*";
const char kExampleScheme[] = "custom";
base::ListValue protocol_origins_map_list;
// Three dictionaries in the list for this test case.
base::DictionaryValue protocol_origins_map1;
base::DictionaryValue protocol_origins_map2;
base::DictionaryValue protocol_origins_map3;
// Set invalid protocols, each with the wildcard origin matching pattern.
protocol_origins_map1.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kInvalidProtocol1);
base::ListValue origins1;
origins1.Append(kWildcardOrigin);
protocol_origins_map1.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins1));
protocol_origins_map_list.Append(std::move(protocol_origins_map1));
protocol_origins_map2.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kInvalidProtocol2);
base::ListValue origins2;
origins2.Append(kWildcardOrigin);
protocol_origins_map2.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins2));
protocol_origins_map_list.Append(std::move(protocol_origins_map2));
protocol_origins_map3.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kInvalidProtocol3);
base::ListValue origins3;
origins3.Append(kWildcardOrigin);
protocol_origins_map3.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins3));
protocol_origins_map_list.Append(std::move(protocol_origins_map3));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
url::Origin test_origin = url::Origin::Create(GURL("https://example.test"));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsOriginPatternWithMissingScheme) {
const char kExampleScheme[] = "custom";
const char kHost[] = "www.example.test";
base::ListValue protocol_origins_map_list;
// Single dictionary in the list for this test case.
base::DictionaryValue protocol_origins_map;
// Set a protocol to match the test.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set an origins list with an origin matching pattern that matches but is
// only the host name.
base::ListValue origins;
origins.Append(kHost);
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
protocol_origins_map_list.Append(std::move(protocol_origins_map));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
// Test that secure origin matches.
url::Origin test_origin =
url::Origin::Create(GURL("https://www.example.test"));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state);
// Test that insecure origin matches.
test_origin = url::Origin::Create(GURL("http://www.example.test"));
block_state = ExternalProtocolHandler::GetBlockState(
kExampleScheme, &test_origin, browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state);
// Test that different origin does not match.
test_origin = url::Origin::Create(GURL("http://www.other.test"));
block_state = ExternalProtocolHandler::GetBlockState(
kExampleScheme, &test_origin, browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsOriginPatternWithExactHostname) {
const char kExampleScheme[] = "custom";
const char kExactHostName[] = ".www.example.test";
base::ListValue protocol_origins_map_list;
// Single dictionary in the list for this test case.
base::DictionaryValue protocol_origins_map;
// Set a protocol to match the test.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set an origins list with an origin matching pattern that matches exactly
// but has no scheme.
base::ListValue origins;
origins.Append(kExactHostName);
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
protocol_origins_map_list.Append(std::move(protocol_origins_map));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
// Test that secure origin matches.
url::Origin test_origin =
url::Origin::Create(GURL("https://www.example.test"));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state);
// Test that insecure origin matches.
test_origin = url::Origin::Create(GURL("http://www.example.test"));
block_state = ExternalProtocolHandler::GetBlockState(
kExampleScheme, &test_origin, browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state);
// Test that different origin does not match.
test_origin = url::Origin::Create(GURL("http://www.other.test"));
block_state = ExternalProtocolHandler::GetBlockState(
kExampleScheme, &test_origin, browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsOriginPatternWithParentDomain) {
const char kExampleScheme[] = "custom";
const char kParentDomain[] = "example.test";
base::ListValue protocol_origins_map_list;
// Single dictionary in the list for this test case.
base::DictionaryValue protocol_origins_map;
// Set a protocol to match the test.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set an origins list with an origin matching pattern that is the parent
// domain but should match subdomains.
base::ListValue origins;
origins.Append(kParentDomain);
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
protocol_origins_map_list.Append(std::move(protocol_origins_map));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
// Test that a subdomain matches.
url::Origin test_origin =
url::Origin::Create(GURL("https://www.example.test"));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsOriginPatternWithWildcardOrigin) {
const char kExampleScheme[] = "custom";
const char kProtocolWithWildcardHostname[] = "https://*";
base::ListValue protocol_origins_map_list;
// Single dictionary in the list for this test case.
base::DictionaryValue protocol_origins_map;
// Set a protocol to match the test.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set an origins list with an origin matching pattern that matches the scheme
// and all hosts.
base::ListValue origins;
origins.Append(kProtocolWithWildcardHostname);
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
protocol_origins_map_list.Append(std::move(protocol_origins_map));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
// Test that secure origin matches.
url::Origin test_origin =
url::Origin::Create(GURL("https://www.example.test"));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state);
// Test that insecure origin does not match.
test_origin = url::Origin::Create(GURL("http://www.example.test"));
block_state = ExternalProtocolHandler::GetBlockState(
kExampleScheme, &test_origin, browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsOriginPatternWithFullOrigin) {
const char kExampleScheme[] = "custom";
const char kFullOrigin[] = "https://www.example.test:443";
base::ListValue protocol_origins_map_list;
// Single dictionary in the list for this test case.
base::DictionaryValue protocol_origins_map;
// Set a protocol to match the test.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set an origins list with an origin matching pattern that matches the full
// origin exactly.
base::ListValue origins;
origins.Append(kFullOrigin);
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
protocol_origins_map_list.Append(std::move(protocol_origins_map));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
// Test that default HTTPS port 443 matches.
url::Origin test_origin =
url::Origin::Create(GURL("https://www.example.test"));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state);
// Test that explicit port 443 matches.
test_origin = url::Origin::Create(GURL("https://www.example.test:443"));
block_state = ExternalProtocolHandler::GetBlockState(
kExampleScheme, &test_origin, browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::DONT_BLOCK, block_state);
// Test that explicit other port does not match.
test_origin = url::Origin::Create(GURL("https://www.example.test:8080"));
block_state = ExternalProtocolHandler::GetBlockState(
kExampleScheme, &test_origin, browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsOriginPatternWithExactParentDomain) {
const char kExampleScheme[] = "custom";
const char kExactParentDomain[] = ".example.com";
base::ListValue protocol_origins_map_list;
// Single dictionary in the list for this test case.
base::DictionaryValue protocol_origins_map;
// Set a protocol to match the test.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set an origins list with an origin matching pattern that doesn't match
// because it is a parent domain that does not match subdomains.
base::ListValue origins;
origins.Append(kExactParentDomain);
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
protocol_origins_map_list.Append(std::move(protocol_origins_map));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
url::Origin test_origin =
url::Origin::Create(GURL("https://www.example.test"));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
IN_PROC_BROWSER_TEST_F(ExternalProtocolPolicyBrowserTest,
AutoLaunchProtocolsOriginPatternWithPath) {
const char kExampleScheme[] = "custom";
const char kFullUrlWithPath[] = "https://example.test/home.html";
base::ListValue protocol_origins_map_list;
// Single dictionary in the list for this test case.
base::DictionaryValue protocol_origins_map;
// Set a protocol to match the test.
protocol_origins_map.SetStringKey(
AutoLaunchProtocolsPolicyHandler::kProtocolNameKey, kExampleScheme);
// Set an origins list with an origin matching pattern that doesn't match
// because it contains a [/path] element.
base::ListValue origins;
origins.Append(kFullUrlWithPath);
protocol_origins_map.SetKey(AutoLaunchProtocolsPolicyHandler::kOriginListKey,
std::move(origins));
protocol_origins_map_list.Append(std::move(protocol_origins_map));
PolicyMap policies;
policies.Set(key::kAutoLaunchProtocolsFromOrigins, POLICY_LEVEL_MANDATORY,
POLICY_SCOPE_USER, POLICY_SOURCE_CLOUD,
protocol_origins_map_list.Clone(), nullptr);
UpdateProviderPolicy(policies);
url::Origin test_origin = url::Origin::Create(GURL(kFullUrlWithPath));
ExternalProtocolHandler::BlockState block_state =
ExternalProtocolHandler::GetBlockState(kExampleScheme, &test_origin,
browser()->profile());
EXPECT_EQ(ExternalProtocolHandler::UNKNOWN, block_state);
}
} // namespace policy
| 21,702 | 6,434 |
/*
*
* File obtained from pgenlibr R library:
* https://github.com/chrchang/plink-ng/tree/master/2.0/pgenlibr
*
* License info obtained from DESCRIPTION file:
* https://github.com/chrchang/plink-ng/blob/master/2.0/pgenlibr/DESCRIPTION
* -----------------------------------------------------
Package: pgenlibr
Type: Package
Title: PLINK 2 Binary (.pgen) Reader
Version: 0.2
Date: 2019-07-10
Author: Christopher Chang
Maintainer: Christopher Chang <chrchang@alumni.caltech.edu>
Description: A thin wrapper over PLINK 2's core libraries which provides an R
interface for reading .pgen files. A minimal .pvar loader is also included.
License: LGPL (>= 3)
Imports: Rcpp (>= 1.0.1)
LinkingTo: Rcpp
* -----------------------------------------------------
* Modified by Joelle Mbatchou - June 29 2020
* - removed functions that were for R
* - split file to header (added link to several standard C++ libraries)
* - modified remaining functions to be fully C/C++ compatible
*
* This file remains under LGPL v3 license (license is in same directory as this file)
*/
#include "pgenlibr.h"
PgenReader::PgenReader() : _info_ptr(nullptr),
//_allele_idx_offsetsp(nullptr),
//_nonref_flagsp(nullptr),
_state_ptr(nullptr) {
}
PgenReader::~PgenReader() {
Close();
}
void PgenReader::Load(std::string filename, uint32_t cur_sample_ct, std::vector<int> sample_subset_1based) {
if (_info_ptr) {
Close();
}
_info_ptr = static_cast<plink2::PgenFileInfo*>(malloc(sizeof(plink2::PgenFileInfo)));
if (!_info_ptr) {
fprintf(stderr,"Out of memory");
exit(-1);
}
plink2::PreinitPgfi(_info_ptr);
uint32_t cur_variant_ct = UINT32_MAX;
const char* fname = filename.c_str();
plink2::PgenHeaderCtrl header_ctrl;
uintptr_t pgfi_alloc_cacheline_ct;
char errstr_buf[plink2::kPglErrstrBufBlen];
if (PgfiInitPhase1(fname, cur_variant_ct, cur_sample_ct, 0, &header_ctrl, _info_ptr, &pgfi_alloc_cacheline_ct, errstr_buf) != plink2::kPglRetSuccess) {
fprintf(stderr, "%s\n", &(errstr_buf[7]));
exit(-1);
}
const uint32_t raw_variant_ct = _info_ptr->raw_variant_ct;
if (header_ctrl & 0x30) {
fprintf(stderr,"Storing of allele count information is not supported (only bi-allelic variants should be present).");
exit(-1);
// no need to zero-initialize this
//_allele_idx_offsetsp = plink2::CreateRefcountedWptr(raw_variant_ct + 1);
//_info_ptr->allele_idx_offsets = _allele_idx_offsetsp->p;
// _info_ptr->max_allele_ct updated by PgfiInitPhase2() in this case
}
_info_ptr->max_allele_ct = 2;
if ((header_ctrl & 0xc0) == 0xc0) {
fprintf(stderr,"Tracking og reference alleles in header is not supported.");
exit(-1);
// todo: load this in pvar, to enable consistency check. we use a
// (manually implemented) shared_ptr in preparation for this.
//const uintptr_t raw_variant_ctl = plink2::DivUp(raw_variant_ct, plink2::kBitsPerWord);
// no need to zero-initialize this
//_nonref_flagsp = plink2::CreateRefcountedWptr(raw_variant_ctl + 1);
//_info_ptr->nonref_flags = _nonref_flagsp->p;
}
const uint32_t file_sample_ct = _info_ptr->raw_sample_ct;
unsigned char* pgfi_alloc = nullptr;
if (plink2::cachealigned_malloc(pgfi_alloc_cacheline_ct * plink2::kCacheline, &pgfi_alloc)) {
fprintf(stderr,"Out of memory");
exit(-1);
}
uint32_t max_vrec_width;
uintptr_t pgr_alloc_cacheline_ct;
if (PgfiInitPhase2(header_ctrl, 1, 0, 0, 0, raw_variant_ct, &max_vrec_width, _info_ptr, pgfi_alloc, &pgr_alloc_cacheline_ct, errstr_buf)) {
if (pgfi_alloc && (!_info_ptr->vrtypes)) {
plink2::aligned_free(pgfi_alloc);
}
fprintf(stderr,"%s\n", &(errstr_buf[7]));
exit(-1);
}
if ((!_allele_idx_offsetsp) && (_info_ptr->gflags & 4)) {
// Note that it's safe to be ignorant of multiallelic variants when
// phase and dosage info aren't present; GetAlleleCt() then always returns
// 2 when that isn't actually true, and all ALTs are treated as if they
// were ALT1, but otherwise everything works properly.
fprintf(stderr,"Multiallelic variants and phase/dosage info simultaneously present; pvar required in this case");
exit(-1);
}
_state_ptr = static_cast<plink2::PgenReader*>(malloc(sizeof(plink2::PgenReader)));
if (!_state_ptr) {
fprintf(stderr,"Out of memory");
exit(-1);
}
plink2::PreinitPgr(_state_ptr);
plink2::PgrSetFreadBuf(nullptr, _state_ptr);
const uintptr_t pgr_alloc_main_byte_ct = pgr_alloc_cacheline_ct * plink2::kCacheline;
const uintptr_t sample_subset_byte_ct = plink2::DivUp(file_sample_ct, plink2::kBitsPerVec) * plink2::kBytesPerVec;
const uintptr_t cumulative_popcounts_byte_ct = plink2::DivUp(file_sample_ct, plink2::kBitsPerWord * plink2::kInt32PerVec) * plink2::kBytesPerVec;
const uintptr_t genovec_byte_ct = plink2::DivUp(file_sample_ct, plink2::kNypsPerVec) * plink2::kBytesPerVec;
const uintptr_t ac_byte_ct = plink2::RoundUpPow2(file_sample_ct * sizeof(plink2::AlleleCode), plink2::kBytesPerVec);
const uintptr_t ac2_byte_ct = plink2::RoundUpPow2(file_sample_ct * 2 * sizeof(plink2::AlleleCode), plink2::kBytesPerVec);
uintptr_t multiallelic_hc_byte_ct = 0;
if (_info_ptr->max_allele_ct != 2) {
multiallelic_hc_byte_ct = 2 * sample_subset_byte_ct + ac_byte_ct + ac2_byte_ct;
}
const uintptr_t dosage_main_byte_ct = plink2::DivUp(file_sample_ct, (2 * plink2::kInt32PerVec)) * plink2::kBytesPerVec;
unsigned char* pgr_alloc;
if (plink2::cachealigned_malloc(pgr_alloc_main_byte_ct + (2 * plink2::kPglNypTransposeBatch + 5) * sample_subset_byte_ct + cumulative_popcounts_byte_ct + (1 + plink2::kPglNypTransposeBatch) * genovec_byte_ct + multiallelic_hc_byte_ct + dosage_main_byte_ct + plink2::kPglBitTransposeBufbytes + 4 * (plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8), &pgr_alloc)) {
fprintf(stderr,"Out of memory");
exit(-1);
}
plink2::PglErr reterr = PgrInit(fname, max_vrec_width, _info_ptr, _state_ptr, pgr_alloc);
if (reterr != plink2::kPglRetSuccess) {
if (!plink2::PgrGetFreadBuf(_state_ptr)) {
plink2::aligned_free(pgr_alloc);
}
sprintf(errstr_buf, "PgrInit() error %d", static_cast<int>(reterr));
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
unsigned char* pgr_alloc_iter = &(pgr_alloc[pgr_alloc_main_byte_ct]);
_subset_include_vec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
_subset_include_interleaved_vec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
#ifdef USE_AVX2
_subset_include_interleaved_vec[-3] = 0;
_subset_include_interleaved_vec[-2] = 0;
#endif
_subset_include_interleaved_vec[-1] = 0;
_subset_cumulative_popcounts = reinterpret_cast<uint32_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[cumulative_popcounts_byte_ct]);
_pgv.genovec = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[genovec_byte_ct]);
if (multiallelic_hc_byte_ct) {
_pgv.patch_01_set = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
_pgv.patch_01_vals = reinterpret_cast<plink2::AlleleCode*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[ac_byte_ct]);
_pgv.patch_10_set = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
_pgv.patch_10_vals = reinterpret_cast<plink2::AlleleCode*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[ac2_byte_ct]);
} else {
_pgv.patch_01_set = nullptr;
_pgv.patch_01_vals = nullptr;
_pgv.patch_10_set = nullptr;
_pgv.patch_10_vals = nullptr;
}
_pgv.phasepresent = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
_pgv.phaseinfo = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
_pgv.dosage_present = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[sample_subset_byte_ct]);
_pgv.dosage_main = reinterpret_cast<uint16_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[dosage_main_byte_ct]);
if (sample_subset_1based.size() > 0) {
SetSampleSubsetInternal(sample_subset_1based);
} else {
_subset_size = file_sample_ct;
}
pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglBitTransposeBufbytes]);
_multivar_vmaj_geno_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * genovec_byte_ct]);
_multivar_vmaj_phasepresent_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * sample_subset_byte_ct]);
_multivar_vmaj_phaseinfo_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * sample_subset_byte_ct]);
_multivar_smaj_geno_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 4]);
_multivar_smaj_phaseinfo_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8]);
_multivar_smaj_phasepresent_batch_buf = reinterpret_cast<uintptr_t*>(pgr_alloc_iter);
// pgr_alloc_iter = &(pgr_alloc_iter[plink2::kPglNypTransposeBatch * plink2::kPglNypTransposeBatch / 8]);
}
uint32_t PgenReader::GetRawSampleCt() const {
if (!_info_ptr) {
fprintf(stderr,"pgen is closed");
exit(-1);
}
return _info_ptr->raw_sample_ct;
}
uint32_t PgenReader::GetSubsetSize() const {
return _subset_size;
}
uint32_t PgenReader::GetVariantCt() const {
if (!_info_ptr) {
fprintf(stderr,"pgen is closed");
exit(-1);
}
return _info_ptr->raw_variant_ct;
}
uint32_t PgenReader::GetAlleleCt(uint32_t variant_idx) const {
if (!_info_ptr) {
fprintf(stderr,"pgen is closed");
exit(-1);
}
if (variant_idx >= _info_ptr->raw_variant_ct) {
char errstr_buf[256];
sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
if (!_allele_idx_offsetsp) {
return 2;
}
fprintf(stderr,"Error: only bi-allelic variants are supported");
exit(-1);
//const uintptr_t* allele_idx_offsets = _allele_idx_offsetsp->p;
//return allele_idx_offsets[variant_idx + 1] - allele_idx_offsets[variant_idx];
}
uint32_t PgenReader::GetMaxAlleleCt() const {
if (!_info_ptr) {
fprintf(stderr,"pgen is closed");
exit(-1);
}
return _info_ptr->max_allele_ct;
}
bool PgenReader::HardcallPhasePresent() const {
if (!_info_ptr) {
fprintf(stderr,"pgen is closed");
exit(-1);
}
return ((_info_ptr->gflags & plink2::kfPgenGlobalHardcallPhasePresent) != 0);
}
// added by J.Mbatchou (09/22/20) to check if dosages are present in PGEN file
bool PgenReader::DosagePresent() const {
if (!_info_ptr) {
fprintf(stderr,"pgen is closed");
exit(-1);
}
return ((_info_ptr->gflags & plink2::kfPgenGlobalDosagePresent) != 0);
}
static const int32_t kGenoRInt32Quads[1024] ALIGNV16 = QUAD_TABLE256(0, 1, 2, -3);
void PgenReader::ReadIntHardcalls(std::vector<int>& buf, int variant_idx, int allele_idx) {
if (!_info_ptr) {
fprintf(stderr,"pgen is closed");
exit(-1);
}
if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) {
char errstr_buf[256];
sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
if (buf.size() != _subset_size) {
char errstr_buf[256];
sprintf(errstr_buf, "buf has wrong length (%" PRIdPTR "; %u expected)", buf.size(), _subset_size);
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
plink2::PglErr reterr = PgrGet1(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec);
if (reterr != plink2::kPglRetSuccess) {
char errstr_buf[256];
sprintf(errstr_buf, "PgrGet1() error %d", static_cast<int>(reterr));
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
plink2::GenoarrLookup256x4bx4(_pgv.genovec, kGenoRInt32Quads, _subset_size, &buf[0]);
}
static const double kGenoRDoublePairs[32] ALIGNV16 = PAIR_TABLE16(0.0, 1.0, 2.0, -3.0);
void PgenReader::ReadHardcalls(std::vector<double>& buf, int variant_idx, int allele_idx) {
if (!_info_ptr) {
fprintf(stderr,"pgen is closed");
exit(-1);
}
if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) {
char errstr_buf[256];
sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
if (buf.size() != _subset_size) {
char errstr_buf[256];
sprintf(errstr_buf, "buf has wrong length (%" PRIdPTR "; %u expected)", buf.size(), _subset_size);
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
plink2::PglErr reterr = PgrGet1(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec);
if (reterr != plink2::kPglRetSuccess) {
char errstr_buf[256];
sprintf(errstr_buf, "PgrGet1() error %d", static_cast<int>(reterr));
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
plink2::GenoarrLookup16x8bx2(_pgv.genovec, kGenoRDoublePairs, _subset_size, &buf[0]);
}
void PgenReader::Read(std::vector<double>& buf, int variant_idx, int allele_idx) {
if (!_info_ptr) {
fprintf(stderr,"pgen is closed");
exit(-1);
}
if (static_cast<uint32_t>(variant_idx) >= _info_ptr->raw_variant_ct) {
char errstr_buf[256];
sprintf(errstr_buf, "variant_num out of range (%d; must be 1..%u)", variant_idx + 1, _info_ptr->raw_variant_ct);
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
if (buf.size() != _subset_size) {
char errstr_buf[256];
sprintf(errstr_buf, "buf has wrong length (%" PRIdPTR "; %u expected)", buf.size(), _subset_size);
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
uint32_t dosage_ct;
plink2::PglErr reterr = PgrGet1D(_subset_include_vec, _subset_index, _subset_size, variant_idx, allele_idx, _state_ptr, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, &dosage_ct);
if (reterr != plink2::kPglRetSuccess) {
char errstr_buf[256];
sprintf(errstr_buf, "PgrGet1D() error %d", static_cast<int>(reterr));
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
plink2::Dosage16ToDoubles(kGenoRDoublePairs, _pgv.genovec, _pgv.dosage_present, _pgv.dosage_main, _subset_size, dosage_ct, &buf[0]);
}
void PgenReader::Close() {
// don't bother propagating file close errors for now
if (_info_ptr) {
//CondReleaseRefcountedWptr(&_allele_idx_offsetsp);
//CondReleaseRefcountedWptr(&_nonref_flagsp);
if (_info_ptr->vrtypes) {
plink2::aligned_free(_info_ptr->vrtypes);
}
plink2::PglErr reterr = plink2::kPglRetSuccess;
plink2::CleanupPgfi(_info_ptr, &reterr);
free(_info_ptr);
_info_ptr = nullptr;
}
if (_state_ptr) {
plink2::PglErr reterr = plink2::kPglRetSuccess;
plink2::CleanupPgr(_state_ptr, &reterr);
if (PgrGetFreadBuf(_state_ptr)) {
plink2::aligned_free(PgrGetFreadBuf(_state_ptr));
}
free(_state_ptr);
_state_ptr = nullptr;
}
_subset_size = 0;
}
void PgenReader::SetSampleSubsetInternal(std::vector<int>& sample_subset_1based) {
const uint32_t raw_sample_ct = _info_ptr->raw_sample_ct;
const uint32_t raw_sample_ctv = plink2::DivUp(raw_sample_ct, plink2::kBitsPerVec);
const uint32_t raw_sample_ctaw = raw_sample_ctv * plink2::kWordsPerVec;
uintptr_t* sample_include = _subset_include_vec;
plink2::ZeroWArr(raw_sample_ctaw, sample_include);
const uint32_t subset_size = sample_subset_1based.size();
if (subset_size == 0) {
fprintf(stderr,"Empty sample_subset is not currently permitted");
exit(-1);
}
uint32_t sample_uidx = sample_subset_1based[0] - 1;
uint32_t idx = 0;
uint32_t next_uidx;
while (1) {
if (sample_uidx >= raw_sample_ct) {
char errstr_buf[256];
sprintf(errstr_buf, "sample number out of range (%d; must be 1..%u)", static_cast<int>(sample_uidx + 1), raw_sample_ct);
fprintf(stderr,"%s\n", errstr_buf);
exit(-1);
}
plink2::SetBit(sample_uidx, sample_include);
if (++idx == subset_size) {
break;
}
next_uidx = sample_subset_1based[idx] - 1;
// prohibit this since it implies that the caller expects genotypes to be
// returned in a different order
if (next_uidx <= sample_uidx) {
fprintf(stderr,"sample_subset is not in strictly increasing order");
exit(-1);
}
sample_uidx = next_uidx;
}
plink2::FillInterleavedMaskVec(sample_include, raw_sample_ctv, _subset_include_interleaved_vec);
const uint32_t raw_sample_ctl = plink2::DivUp(raw_sample_ct, plink2::kBitsPerWord);
plink2::FillCumulativePopcounts(sample_include, raw_sample_ctl, _subset_cumulative_popcounts);
plink2::PgrSetSampleSubsetIndex(_subset_cumulative_popcounts, _state_ptr, &_subset_index);
_subset_size = subset_size;
}
| 17,436 | 7,131 |
#ifndef __GECODE_STRING_FIND_HH__
#define __GECODE_STRING_FIND_HH__
namespace Gecode { namespace String {
/**
* \brief %Propagator for string find.
*
*/
class Find :
public MixTernaryPropagator<StringView, PC_STRING_DOM,
StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND> {
protected:
using MixTernaryPropagator<StringView, PC_STRING_DOM,
StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND>
::x0;
using MixTernaryPropagator<StringView, PC_STRING_DOM,
StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND>
::x1;
using MixTernaryPropagator<StringView, PC_STRING_DOM,
StringView, PC_STRING_DOM, Gecode::Int::IntView, Gecode::Int::PC_INT_BND>
::x2;
/// Constructor for cloning \a p
Find(Space& home, Find& p);
/// Constructor for posting
Find(Home home, StringView, StringView, Gecode::Int::IntView);
public:
/// Copy propagator during cloning
virtual Actor* copy(Space& home);
/// Perform propagation
virtual ExecStatus propagate(Space& home, const ModEventDelta& med);
/// Post propagator for \f n = find(x, y) \f$
static ExecStatus post(Home, StringView, StringView, Gecode::Int::IntView);
};
}}
#include <gecode/string/int/find.hpp>
#endif
| 1,335 | 470 |
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <grpc/support/port_platform.h>
#include <grpc/grpc.h>
#include <string.h>
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
#include "src/core/ext/filters/client_channel/client_channel.h"
#include "src/core/ext/filters/client_channel/resolver_registry.h"
#include "src/core/ext/transport/chttp2/client/chttp2_connector.h"
#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/surface/channel.h"
static void client_channel_factory_ref(
grpc_client_channel_factory* cc_factory) {}
static void client_channel_factory_unref(
grpc_client_channel_factory* cc_factory) {}
static grpc_subchannel* client_channel_factory_create_subchannel(
grpc_client_channel_factory* cc_factory, const grpc_subchannel_args* args) {
grpc_connector* connector = grpc_chttp2_connector_create();
grpc_subchannel* s = grpc_subchannel_create(connector, args);
grpc_connector_unref(connector);
return s;
}
static grpc_channel* client_channel_factory_create_channel(
grpc_client_channel_factory* cc_factory, const char* target,
grpc_client_channel_type type, const grpc_channel_args* args) {
if (target == nullptr) {
gpr_log(GPR_ERROR, "cannot create channel with NULL target name");
return nullptr;
}
// Add channel arg containing the server URI.
grpc_core::UniquePtr<char> canonical_target =
grpc_core::ResolverRegistry::AddDefaultPrefixIfNeeded(target);
grpc_arg arg = grpc_channel_arg_string_create((char*)GRPC_ARG_SERVER_URI,
canonical_target.get());
const char* to_remove[] = {GRPC_ARG_SERVER_URI};
grpc_channel_args* new_args =
grpc_channel_args_copy_and_add_and_remove(args, to_remove, 1, &arg, 1);
grpc_channel* channel =
grpc_channel_create(target, new_args, GRPC_CLIENT_CHANNEL, nullptr);
grpc_channel_args_destroy(new_args);
return channel;
}
static const grpc_client_channel_factory_vtable client_channel_factory_vtable =
{client_channel_factory_ref, client_channel_factory_unref,
client_channel_factory_create_subchannel,
client_channel_factory_create_channel};
static grpc_client_channel_factory client_channel_factory = {
&client_channel_factory_vtable};
/* Create a client channel:
Asynchronously: - resolve target
- connect to it (trying alternatives as presented)
- perform handshakes */
grpc_channel* grpc_insecure_channel_create(const char* target,
const grpc_channel_args* args,
void* reserved) {
grpc_core::ExecCtx exec_ctx;
GRPC_API_TRACE(
"grpc_insecure_channel_create(target=%s, args=%p, reserved=%p)", 3,
(target, args, reserved));
GPR_ASSERT(reserved == nullptr);
// Add channel arg containing the client channel factory.
grpc_arg arg =
grpc_client_channel_factory_create_channel_arg(&client_channel_factory);
grpc_channel_args* new_args = grpc_channel_args_copy_and_add(args, &arg, 1);
// Create channel.
grpc_channel* channel = client_channel_factory_create_channel(
&client_channel_factory, target, GRPC_CLIENT_CHANNEL_TYPE_REGULAR,
new_args);
// Clean up.
grpc_channel_args_destroy(new_args);
return channel != nullptr ? channel
: grpc_lame_client_channel_create(
target, GRPC_STATUS_INTERNAL,
"Failed to create client channel");
}
| 4,152 | 1,332 |
/*
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <fnmatch.h>
#include <boost/filesystem.hpp>
#include <osquery/filesystem.h>
#include <osquery/logger.h>
#include <osquery/tables.h>
#include "osquery/events/darwin/fsevents.h"
/**
* @brief FSEvents needs a real/absolute path for watches.
*
* When adding a subscription, FSEvents will resolve a depth of recursive
* symlinks. Increasing the max will make tolerance to odd setups more robust
* but introduce additional latency during startup.
*/
#define FSEVENTS_MAX_SYMLINK_DEPTH 5
namespace fs = boost::filesystem;
namespace osquery {
std::map<FSEventStreamEventFlags, std::string> kMaskActions = {
{kFSEventStreamEventFlagItemChangeOwner, "ATTRIBUTES_MODIFIED"},
{kFSEventStreamEventFlagItemXattrMod, "ATTRIBUTES_MODIFIED"},
{kFSEventStreamEventFlagItemInodeMetaMod, "ATTRIBUTES_MODIFIED"},
{kFSEventStreamEventFlagItemCreated, "CREATED"},
{kFSEventStreamEventFlagItemRemoved, "DELETED"},
{kFSEventStreamEventFlagItemModified, "UPDATED"},
{kFSEventStreamEventFlagItemRenamed, "MOVED_TO"},
{kFSEventStreamEventFlagMustScanSubDirs, "COLLISION_WITHIN"},
{kFSEventStreamEventFlagUnmount, "UNMOUNTED"},
{kFSEventStreamEventFlagRootChanged, "ROOT_CHANGED"},
};
REGISTER(FSEventsEventPublisher, "event_publisher", "fsevents");
void FSEventsSubscriptionContext::requireAction(const std::string& action) {
for (const auto& bit : kMaskActions) {
if (action == bit.second) {
mask = mask & bit.first;
}
}
}
void FSEventsEventPublisher::restart() {
if (run_loop_ == nullptr) {
return;
}
// Remove any existing stream.
stop();
// Build paths as CFStrings
{
WriteLock lock(mutex_);
if (paths_.empty()) {
// There are no paths to watch.
paths_.insert("/dev/null");
}
std::vector<CFStringRef> cf_paths;
for (const auto& path : paths_) {
auto cf_path = CFStringCreateWithCString(
nullptr, path.c_str(), kCFStringEncodingUTF8);
cf_paths.push_back(cf_path);
}
// The FSEvents watch takes a CFArrayRef
auto watch_list =
CFArrayCreate(nullptr,
reinterpret_cast<const void**>(&cf_paths[0]),
cf_paths.size(),
&kCFTypeArrayCallBacks);
// Set stream flags.
auto flags =
kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagWatchRoot;
if (no_defer_) {
flags |= kFSEventStreamCreateFlagNoDefer;
}
if (no_self_) {
flags |= kFSEventStreamCreateFlagIgnoreSelf;
}
// Create the FSEvent stream.
stream_ = FSEventStreamCreate(nullptr,
&FSEventsEventPublisher::Callback,
nullptr,
watch_list,
kFSEventStreamEventIdSinceNow,
1,
flags);
if (stream_ != nullptr) {
// Schedule the stream on the run loop.
FSEventStreamScheduleWithRunLoop(
stream_, run_loop_, kCFRunLoopDefaultMode);
if (FSEventStreamStart(stream_)) {
stream_started_ = true;
} else {
LOG(ERROR) << "Cannot start FSEvent stream: FSEventStreamStart failed";
}
} else {
LOG(ERROR) << "Cannot create FSEvent stream: FSEventStreamCreate failed";
}
// Clean up strings, watch list, and context.
CFRelease(watch_list);
for (auto& cf_path : cf_paths) {
CFRelease(cf_path);
}
}
}
void FSEventsEventPublisher::stop() {
// Stop the stream.
WriteLock lock(mutex_);
if (run_loop_ == nullptr) {
// No need to stop if there is not run loop.
return;
}
if (stream_ != nullptr) {
FSEventStreamStop(stream_);
stream_started_ = false;
FSEventStreamUnscheduleFromRunLoop(
stream_, run_loop_, kCFRunLoopDefaultMode);
FSEventStreamInvalidate(stream_);
FSEventStreamRelease(stream_);
stream_ = nullptr;
}
// Stop the run loop.
CFRunLoopStop(run_loop_);
}
void FSEventsEventPublisher::tearDown() {
stop();
// Do not keep a reference to the run loop.
run_loop_ = nullptr;
}
std::set<std::string> FSEventsEventPublisher::transformSubscription(
FSEventsSubscriptionContextRef& sc) const {
std::set<std::string> paths;
sc->discovered_ = sc->path;
if (sc->path.find("**") != std::string::npos) {
// Double star will indicate recursive matches, restricted to endings.
sc->recursive = true;
sc->discovered_ = sc->path.substr(0, sc->path.find("**"));
// Remove '**' from the subscription path (used to match later).
sc->path = sc->discovered_;
}
// If the path 'still' OR 'either' contains a single wildcard.
if (sc->path.find('*') != std::string::npos) {
// First check if the wildcard is applied to the end.
auto fullpath = fs::path(sc->path);
if (fullpath.filename().string().find('*') != std::string::npos) {
sc->discovered_ = fullpath.parent_path().string();
}
// FSEvents needs a real path, if the wildcard is within the path then
// a configure-time resolve is required.
if (sc->discovered_.find('*') != std::string::npos) {
std::vector<std::string> exploded_paths;
resolveFilePattern(sc->discovered_, exploded_paths);
for (const auto& path : exploded_paths) {
paths.insert(path);
}
sc->recursive_match = sc->recursive;
return paths;
}
}
paths.insert(sc->discovered_);
return paths;
}
void FSEventsEventPublisher::configure() {
// Rebuild the watch paths.
stop();
{
WriteLock lock(mutex_);
paths_.clear();
for (auto& sub : subscriptions_) {
auto sc = getSubscriptionContext(sub->context);
if (sc->discovered_.size() > 0) {
continue;
}
auto paths = transformSubscription(sc);
paths_.insert(paths.begin(), paths.end());
}
}
restart();
}
Status FSEventsEventPublisher::run() {
// The run entrypoint executes in a dedicated thread.
if (run_loop_ == nullptr) {
run_loop_ = CFRunLoopGetCurrent();
// Restart the stream creation.
restart();
}
// Start the run loop, it may be removed with a tearDown.
CFRunLoopRun();
return Status(0, "OK");
}
void FSEventsEventPublisher::Callback(
ConstFSEventStreamRef stream,
void* callback_info,
size_t num_events,
void* event_paths,
const FSEventStreamEventFlags fsevent_flags[],
const FSEventStreamEventId fsevent_ids[]) {
for (size_t i = 0; i < num_events; ++i) {
auto ec = createEventContext();
ec->fsevent_stream = stream;
ec->fsevent_flags = fsevent_flags[i];
ec->transaction_id = fsevent_ids[i];
ec->path = std::string(((char**)event_paths)[i]);
if (ec->fsevent_flags & kFSEventStreamEventFlagMustScanSubDirs) {
// The FSEvents thread coalesced events within and will report a root.
TLOG << "FSEvents collision, root: " << ec->path;
}
if (ec->fsevent_flags & kFSEventStreamEventFlagRootChanged) {
// Must rescan for the changed root.
}
if (ec->fsevent_flags & kFSEventStreamEventFlagUnmount) {
// Should remove the watch on this path.
}
// Record the string-version of the first matched mask bit.
bool has_action = false;
for (const auto& action : kMaskActions) {
if (ec->fsevent_flags & action.first) {
// Actions may be multiplexed. Fire and event for each.
ec->action = action.second;
EventFactory::fire<FSEventsEventPublisher>(ec);
has_action = true;
}
}
if (!has_action) {
// If no action was matched for this path event, fire and unknown.
ec->action = "UNKNOWN";
EventFactory::fire<FSEventsEventPublisher>(ec);
}
}
}
bool FSEventsEventPublisher::shouldFire(
const FSEventsSubscriptionContextRef& sc,
const FSEventsEventContextRef& ec) const {
if (sc->recursive && !sc->recursive_match) {
ssize_t found = ec->path.find(sc->path);
if (found != 0) {
return false;
}
} else if (fnmatch((sc->path + "*").c_str(),
ec->path.c_str(),
FNM_PATHNAME | FNM_CASEFOLD |
((sc->recursive_match) ? FNM_LEADING_DIR : 0)) != 0) {
// Only apply a leading-dir match if this is a recursive watch with a
// match requirement (an inline wildcard with ending recursive wildcard).
return false;
}
if (sc->mask != 0 && !(ec->fsevent_flags & sc->mask)) {
// Compare the event context mask to the subscription context.
return false;
}
return true;
}
void FSEventsEventPublisher::flush(bool async) {
if (stream_ != nullptr && stream_started_) {
if (async) {
FSEventStreamFlushAsync(stream_);
} else {
FSEventStreamFlushSync(stream_);
}
}
}
size_t FSEventsEventPublisher::numSubscriptionedPaths() const {
return paths_.size();
}
bool FSEventsEventPublisher::isStreamRunning() const {
if (stream_ == nullptr || !stream_started_ || run_loop_ == nullptr) {
return false;
}
return CFRunLoopIsWaiting(run_loop_);
}
}
| 9,397 | 3,129 |