text
string
size
int64
token_count
int64
// Copyright (c) 2017 Graphcore Ltd. All rights reserved. #ifndef poplibs_test_NonLinearity_hpp #define poplibs_test_NonLinearity_hpp #include "poplibs_support/Compiler.hpp" #include "poplibs_test/exceptions.hpp" #include "popnn/NonLinearity.hpp" #include <boost/multi_array.hpp> namespace poplibs_test { // input/output can be pointers to same memory void nonLinearity(popnn::NonLinearityType nonLinearityType, const double *inputData, double *outputData, std::size_t n); void nonLinearity(popnn::NonLinearityType nonLinearityType, boost::multi_array_ref<double, 2> array); void nonLinearity(popnn::NonLinearityType nonLinearityType, boost::multi_array<double, 4> &array); // For computing the gradient of non-linearity types SWISH and GELU // `activations` refers to the the input to the activation function rather than // the output. void bwdNonLinearity(popnn::NonLinearityType nonLinearityType, const double *activations, double *deltas, std::size_t n); void bwdNonLinearity(popnn::NonLinearityType nonLinearityType, const boost::multi_array<double, 4> &activations, boost::multi_array<double, 4> &deltas); void bwdNonLinearity(popnn::NonLinearityType nonLinearityType, const boost::multi_array<double, 2> &activations, boost::multi_array<double, 2> &deltas); } // End namespace poplibs_test. #endif // poplibs_test_NonLinearity_hpp
1,506
461
/* * Copyright (c) 2018 Julian Soeren Lorenz, Carnegie Mellon University, All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * END OF LICENSE * * Author: Julian Soeren Lorenz * Email: JulianLorenz@live.de * */ #include "MathUtil.h" namespace Util{ Matrix3d calcRotationMatrix(double qw, double qx, double qy, double qz){ // Sources: https://en.wikipedia.org/wiki/Conversion_between_quaternions_and_Euler_angles // https://arxiv.org/pdf/1708.08680.pdf // Note that the below matrix is transposed so it can be pre-multiplied Matrix3d R_g2f; R_g2f << qw*qw+qx*qx-qy*qy-qz*qz, 2*(qx*qy+qw*qz), 2*(qx*qz-qw*qy), 2*(qx*qy-qw*qz), qw*qw-qx*qx+qy*qy-qz*qz, 2*(qw*qx+qy*qz), 2*(qw*qy+qx*qz), 2*(qy*qz-qw*qx), qw*qw-qx*qx-qy*qy+qz*qz; return R_g2f; } Matrix3d calcRotationMatrix(Quaternion<double> q){ return calcRotationMatrix(q.w(),q.x(),q.y(),q.z()); } Matrix3d calcRotationMatrix(Vector4d q){ return calcRotationMatrix(q(0),q(1),q(2),q(3)); } Matrix3d calcRotationMatrix(double phi, double theta, double psi){ // Source: https://de.wikipedia.org/wiki/Eulersche_Winkel#Gier-Nick-Roll:_z.2C_y.E2.80.B2.2C_x.E2.80.B3-Konvention // Convention: Z Y' X'' Matrix3d R_g2f; const double c1 = std::cos(psi); //yaw const double c2 = std::cos(theta); //pitch const double c3 = std::cos(phi); //roll const double s1 = std::sin(psi); const double s2 = std::sin(theta); const double s3 = std::sin(phi); Matrix3d R_yaw, R_pitch, R_roll; R_yaw << c1, s1, 0, -s1, c1, 0, 0, 0, 1; R_pitch << c2, 0, -s2, 0, 1, 0, s2, 0, c2; R_roll << 1, 0, 0, 0, c3, s3, 0, -s3, c3; R_g2f = R_roll * R_pitch * R_yaw; /* Resulting matrix: R_g2f << c2*c1, c2*s1, -s2, s3*s2*c1-c3*s1, s3*s2*s1+c3*c1, s3*c2, c3*s2*c1+s3*s1, c3*s2*s1-s3*c1, c3*c2; */ return R_g2f; } }//end namespace
3,491
1,504
#include "pch.h" #include <angsys.h> using namespace ang; #define MY_TYPE ang::variable<bool> #include "ang/inline/object_wrapper_specialization.inl" #undef MY_TYPE static collections::pair<castr_t, bool> s_boolean_parsing_map[] = { { "FALSE"_sv, false }, { "False"_sv, false }, { "HIGH"_sv, true }, { "High"_sv, true }, { "LOW"_sv, false }, { "Low"_sv, false }, { "NO"_sv, false }, { "No"_sv, false }, { "TRUE"_sv, true }, { "True"_sv, true }, { "YES"_sv, true }, { "Yes"_sv, true }, { "false"_sv, false }, { "high"_sv, true }, { "low"_sv, false }, { "no"_sv, false }, { "true"_sv, true }, { "yes"_sv, true }, }; value<bool> variable<bool>::parse(cstr_t cstr) { auto idx = algorithms::binary_search(cstr, collections::to_array(s_boolean_parsing_map)); if (idx >= algorithms::array_size(s_boolean_parsing_map)) return false; else return s_boolean_parsing_map[idx].value; } string variable<bool>::to_string(value<bool> val, text::text_format_t f_) { text::text_format_flags_t f; f.value = f_.format_flags(); switch (f.target) { case text::text_format::bool_: switch (f.case_) { case 2: switch (f.type) { case 1: return val.get() ? "YES"_r : "NO"_r; case 2: return val.get() ? "HIGH"_r : "LOW"_r; default: return val.get() ? "TRUE"_r : "FALSE"_r; } case 3: switch (f.type) { case 1: return val.get() ? "Yes"_r : "No"_r; case 2: return val.get() ? "High"_r : "Low"_r; default: return val.get() ? "True"_r : "False"_r; } default: switch (f.type) { case 1: return val.get() ? "yes"_r : "no"_r; case 2: return val.get() ? "high"_r : "low"_r; default: return val.get() ? "true"_r : "false"_r; } } case text::text_format::signed_: return variable<int>::to_string(val.get() ? 1 : 0, f_); case text::text_format::unsigned_: return variable<uint>::to_string(val.get() ? 1 : 0, f_); case text::text_format::float_: return variable<float>::to_string(val.get() ? 1.0f : 0.0f, f_); default: return val.get() ? "true"_r : "false"_r; } } variable<bool>::variable() { set(false); } variable<bool>::variable(bool const& val) { set(val); } variable<bool>::variable(value<bool> const& val) { set(val); } variable<bool>::variable(variable const* val) { set(val ? val->get() : false); } variable<bool>::~variable() { } string variable<bool>::to_string()const { return get() ? "true"_r : "false"_r; } string variable<bool>::to_string(text::text_format_t f)const { return ang::move(to_string(*this, f)); } rtti_t const& variable<bool>::value_type()const { return type_of<bool>(); } bool variable<bool>::set_value(rtti_t const& id, unknown_t val) { return false; } bool variable<bool>::get_value(rtti_t const& id, unknown_t val)const { return false; } variant variable<bool>::clone()const { return (ivariable*)new variable<bool>(get()); }
2,850
1,257
/* Copyright (c) 2009, Robin RUAUX All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of California, Berkeley nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <SFML/Graphics/RenderTarget.hpp> #include <SFUI/CheckBox.hpp> namespace sf { namespace ui { CheckBox::CheckBox(const Unicode::Text& caption) : Widget(), mChecked(false), mDecorator(), mCaption(caption), mCheckIcon() { SetDefaultStyle("BI_CheckBox"); LoadStyle(GetDefaultStyle()); Add(&mDecorator); Add(&mCaption); Add(&mCheckIcon); //mCheckIcon.AddMouseListener(this); AddMouseListener(this); } void CheckBox::SetChecked(bool checked) { mChecked = checked; LoadStyle((checked) ? GetDefaultStyle() + "_Checked" : GetDefaultStyle()); } bool CheckBox::IsChecked() const { return mChecked; } void CheckBox::OnMouseReleased(const Event::MouseButtonEvent& mouse) { if (mouse.Button == Mouse::Left) { if (mChecked) { mChecked = false; LoadStyle(GetDefaultStyle()); } else { mChecked = true; LoadStyle(GetDefaultStyle() + "_Checked"); } } } void CheckBox::LoadStyle(const std::string& nameStyle) { Widget::LoadStyle(nameStyle); mDecorator.LoadStyle(nameStyle + "->Background"); mCheckIcon.LoadStyle(nameStyle + "->Icon"); mCaption.LoadStyle(nameStyle + "->Label"); } void CheckBox::SetText(const Unicode::Text& text) { mCaption.SetText(text); } const Unicode::Text& CheckBox::GetText() const { return mCaption.GetText(); } void CheckBox::SetFont(const Font& font) { mCaption.SetFont(font); } const Font& CheckBox::GetFont() const { return mCaption.GetFont(); } void CheckBox::SetTextColor(const Color& color) { mCaption.SetColor(color); } const Color& CheckBox::GetTextColor() const { return mCaption.GetColor(); } } }
3,986
1,145
/* * Copyright (c) 2018-2019, NVIDIA CORPORATION. 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 <Python.h> #include <vector> #include <string> #include <stdio.h> #include "NVStrings.h" #include "util.h" #include "NVText.h" // utility to deference NVStrings instance from nvstrings instance // caller should never dextroy the return object NVStrings* strings_from_object(PyObject* pystrs) { if( pystrs == Py_None ) { PyErr_Format(PyExc_ValueError,"nvtext: parameter required"); return 0; } std::string cname = pystrs->ob_type->tp_name; if( cname.compare("nvstrings")!=0 ) { PyErr_Format(PyExc_ValueError,"nvtext: argument must be nvstrings object"); return 0; } NVStrings* strs = (NVStrings*)PyLong_AsVoidPtr(PyObject_GetAttrString(pystrs,"m_cptr")); if( strs==0 ) PyErr_Format(PyExc_ValueError,"nvtext: invalid nvstrings object"); return strs; } // utility to create NVStrings instance from a list of strings // caller must destroy the returned object NVStrings* strings_from_list(PyObject* listObj) { unsigned int count = (unsigned int)PyList_Size(listObj); if( count==0 ) return 0; // const char** list = new const char*[count]; for( unsigned int idx=0; idx < count; ++idx ) { PyObject* pystr = PyList_GetItem(listObj,idx); if( (pystr == Py_None) || !PyObject_TypeCheck(pystr,&PyUnicode_Type) ) list[idx] = 0; else list[idx] = PyUnicode_AsUTF8(pystr); } NVStrings* strs = NVStrings::create_from_array(list,count); delete list; return strs; } // // static PyObject* n_unique_tokens( PyObject* self, PyObject* args ) { PyObject* pystrs = PyTuple_GetItem(args,0); // only one parm expected NVStrings* strs = strings_from_object(pystrs); if( strs==0 ) Py_RETURN_NONE; const char* delimiter = " "; PyObject* argDelim = PyTuple_GetItem(args,1); if( argDelim != Py_None ) delimiter = PyUnicode_AsUTF8(argDelim); strs = NVText::unique_tokens(*strs,delimiter); if( strs==0 ) Py_RETURN_NONE; return PyLong_FromVoidPtr((void*)strs); } // static PyObject* n_token_count( PyObject* self, PyObject* args ) { PyObject* pystrs = PyTuple_GetItem(args,0); NVStrings* strs = strings_from_object(pystrs); if( strs==0 ) Py_RETURN_NONE; const char* delimiter = " "; PyObject* argDelim = PyTuple_GetItem(args,1); if( argDelim != Py_None ) delimiter = PyUnicode_AsUTF8(argDelim); unsigned int* devptr = (unsigned int*)PyLong_AsVoidPtr(PyTuple_GetItem(args,2)); if( devptr ) { unsigned int rtn = NVText::token_count(*strs,delimiter,devptr); return PyLong_FromLong((long)rtn); } // unsigned int count = strs->size(); PyObject* ret = PyList_New(count); if( count==0 ) return ret; unsigned int* rtn = new unsigned int[count]; NVText::token_count(*strs,delimiter,rtn,false); for(unsigned int idx=0; idx < count; idx++) PyList_SetItem(ret, idx, PyLong_FromLong((long)rtn[idx])); delete rtn; return ret; } // static PyObject* n_contains_strings( PyObject* self, PyObject* args ) { PyObject* pystrs = PyTuple_GetItem(args,0); NVStrings* strs = strings_from_object(pystrs); if( strs==0 ) Py_RETURN_NONE; PyObject* argStrs = PyTuple_GetItem(args,1); if( argStrs == Py_None ) { PyErr_Format(PyExc_ValueError,"tgts argument must be specified"); Py_RETURN_NONE; } NVStrings* tgts = 0; std::string cname = argStrs->ob_type->tp_name; if( cname.compare("nvstrings")==0 ) tgts = (NVStrings*)PyLong_AsVoidPtr(PyObject_GetAttrString(argStrs,"m_cptr")); else if( cname.compare("list")==0 ) tgts = strings_from_list(argStrs); // if( !tgts ) { PyErr_Format(PyExc_ValueError,"invalid tgts parameter"); Py_RETURN_NONE; } if( tgts->size()==0 ) { if( cname.compare("list")==0 ) NVStrings::destroy(tgts); PyErr_Format(PyExc_ValueError,"tgts argument is empty"); Py_RETURN_NONE; } bool* devptr = (bool*)PyLong_AsVoidPtr(PyTuple_GetItem(args,2)); if( devptr ) { unsigned int rtn = NVText::contains_strings(*strs,*tgts,devptr); if( cname.compare("list")==0 ) NVStrings::destroy(tgts); return PyLong_FromLong((long)rtn); } // unsigned int rows = strs->size(); unsigned int columns = tgts->size(); PyObject* ret = PyList_New(rows); if( rows==0 ) { if( cname.compare("list")==0 ) NVStrings::destroy(tgts); return ret; } bool* rtn = new bool[rows*columns]; NVText::contains_strings(*strs,*tgts,rtn,false); for(unsigned int idx=0; idx < rows; idx++) { PyObject* row = PyList_New(columns); for( unsigned int jdx=0; jdx < columns; ++jdx ) PyList_SetItem(row, jdx, PyBool_FromLong((long)rtn[(idx*columns)+jdx])); PyList_SetItem(ret, idx, row); } delete rtn; if( cname.compare("list")==0 ) NVStrings::destroy(tgts); return ret; } static PyObject* n_strings_counts( PyObject* self, PyObject* args ) { PyObject* pystrs = PyTuple_GetItem(args,0); NVStrings* strs = strings_from_object(pystrs); if( strs==0 ) Py_RETURN_NONE; // PyObject* argStrs = PyTuple_GetItem(args,1); if( argStrs == Py_None ) { PyErr_Format(PyExc_ValueError,"tgts argument must be specified"); Py_RETURN_NONE; } NVStrings* tgts = 0; std::string cname = argStrs->ob_type->tp_name; if( cname.compare("nvstrings")==0 ) tgts = (NVStrings*)PyLong_AsVoidPtr(PyObject_GetAttrString(argStrs,"m_cptr")); else if( cname.compare("list")==0 ) tgts = strings_from_list(argStrs); // if( !tgts ) { PyErr_Format(PyExc_ValueError,"invalid tgts parameter"); Py_RETURN_NONE; } if( tgts->size()==0 ) { if( cname.compare("list")==0 ) NVStrings::destroy(tgts); PyErr_Format(PyExc_ValueError,"tgts argument is empty"); Py_RETURN_NONE; } // fill in devptr with result if provided unsigned int* devptr = (unsigned int*)PyLong_AsVoidPtr(PyTuple_GetItem(args,2)); if( devptr ) { unsigned int rtn = NVText::strings_counts(*strs,*tgts,devptr); if( cname.compare("list")==0 ) NVStrings::destroy(tgts); return PyLong_FromLong((long)rtn); } // or fill in python list with host memory unsigned int rows = strs->size(); unsigned int columns = tgts->size(); PyObject* ret = PyList_New(rows); if( rows==0 ) { if( cname.compare("list")==0 ) NVStrings::destroy(tgts); return ret; } unsigned int* rtn = new unsigned int[rows*columns]; NVText::strings_counts(*strs,*tgts,rtn,false); for(unsigned int idx=0; idx < rows; idx++) { PyObject* row = PyList_New(columns); for( unsigned int jdx=0; jdx < columns; ++jdx ) PyList_SetItem(row, jdx, PyLong_FromLong((long)rtn[(idx*columns)+jdx])); PyList_SetItem(ret, idx, row); } delete rtn; if( cname.compare("list")==0 ) NVStrings::destroy(tgts); return ret; } static PyObject* n_edit_distance( PyObject* self, PyObject* args ) { PyObject* pystrs = PyTuple_GetItem(args,0); NVStrings* strs = strings_from_object(pystrs); if( strs==0 ) Py_RETURN_NONE; // PyObject* pytgts = PyTuple_GetItem(args,1); if( pytgts == Py_None ) { PyErr_Format(PyExc_ValueError,"tgt argument must be specified"); Py_RETURN_NONE; } unsigned int count = strs->size(); unsigned int* devptr = (unsigned int*)PyLong_AsVoidPtr(PyTuple_GetItem(args,2)); std::string cname = pytgts->ob_type->tp_name; if( cname.compare("str")==0 ) { const char* tgt = PyUnicode_AsUTF8(pytgts); if( devptr ) { NVText::edit_distance(NVText::levenshtein,*strs,tgt,devptr); Py_RETURN_NONE; } // or fill in python list with host memory PyObject* ret = PyList_New(count); if( count==0 ) return ret; std::vector<unsigned int> rtn(count); NVText::edit_distance(NVText::levenshtein,*strs,tgt,rtn.data(),false); for(unsigned int idx=0; idx < count; idx++) PyList_SetItem(ret, idx, PyLong_FromLong((long)rtn[idx])); return ret; } NVStrings* tgts = 0; if( cname.compare("nvstrings")==0 ) tgts = (NVStrings*)PyLong_AsVoidPtr(PyObject_GetAttrString(pytgts,"m_cptr")); else if( cname.compare("list")==0 ) tgts = strings_from_list(pytgts); if( !tgts ) { PyErr_Format(PyExc_ValueError,"invalid tgt parameter"); Py_RETURN_NONE; } if( tgts->size() != strs->size() ) { PyErr_Format(PyExc_ValueError,"strs and tgt must have the same number of strings"); Py_RETURN_NONE; } if( devptr ) { NVText::edit_distance(NVText::levenshtein,*strs,*tgts,devptr); if( cname.compare("list")==0 ) NVStrings::destroy(tgts); Py_RETURN_NONE; } PyObject* ret = PyList_New(count); if( count==0 ) return ret; std::vector<unsigned int> rtn(count); NVText::edit_distance(NVText::levenshtein,*strs,*tgts,rtn.data(),false); for(unsigned int idx=0; idx < count; idx++) PyList_SetItem(ret, idx, PyLong_FromLong((long)rtn[idx])); if( cname.compare("list")==0 ) NVStrings::destroy(tgts); return ret; } // static PyMethodDef s_Methods[] = { { "n_unique_tokens", n_unique_tokens, METH_VARARGS, "" }, { "n_token_count", n_token_count, METH_VARARGS, "" }, { "n_contains_strings", n_contains_strings, METH_VARARGS, "" }, { "n_strings_counts", n_strings_counts, METH_VARARGS, "" }, { "n_edit_distance", n_edit_distance, METH_VARARGS, "" }, { NULL, NULL, 0, NULL } }; static struct PyModuleDef cModPyDem = { PyModuleDef_HEAD_INIT, "NVText_module", "", -1, s_Methods }; PyMODINIT_FUNC PyInit_pyniNVText(void) { return PyModule_Create(&cModPyDem); }
10,795
3,987
#define WITHOUT_CMS_FRAMEWORK 1 #include "DQMServices/Core/src/DQMStore.cc" int main() { return 0; }
102
50
/* * QuadraticIntegralErrorTerm.cpp * * Created on: Dec 4, 2013 * Author: hannes */ #include <sstream> #include <boost/python.hpp> #include <numpy_eigen/boost_python_headers.hpp> #include <Eigen/Core> #include <aslam/backend/QuadraticIntegralError.hpp> using namespace boost::python; template <int dim, typename Expression = aslam::backend::VectorExpression<dim>> inline void addQuadraticIntegralExpressionErrorTerms(aslam::backend::OptimizationProblem & problem, double a, double b, int numberOfPoints, const object & expressionFactory, const Eigen::Matrix<double, dim, dim> & sqrtInvR){ using namespace aslam::backend::integration; struct ExpressionFactoryAdapter { ExpressionFactoryAdapter(const object & o) : o(o){} Expression operator()(double time) const { return extract<Expression>(o(time)); } private: const object & o; }; addQuadraticIntegralExpressionErrorTerms(problem, a, b, numberOfPoints, ExpressionFactoryAdapter(expressionFactory), sqrtInvR); } const char * BaseName = "addQuadraticIntegralExpressionErrorTermsToProblem"; template <int dimMax> void defAddQuadraticIntegralExpressionErrorTerms(){ std::stringstream s; s << BaseName << dimMax; boost::python::def( s.str().c_str(), &addQuadraticIntegralExpressionErrorTerms<dimMax>, boost::python::args("problem, timeA, timeB, nIntegrationPoints, expressionFactory, sqrtInvR") ); defAddQuadraticIntegralExpressionErrorTerms<dimMax -1>(); } template <> void defAddQuadraticIntegralExpressionErrorTerms<0>(){ } void exportAddQuadraticIntegralExpressionErrorTerms(){ defAddQuadraticIntegralExpressionErrorTerms<3>(); boost::python::def( "addQuadraticIntegralEuclideanExpressionErrorTermsToProblem", &addQuadraticIntegralExpressionErrorTerms<3, aslam::backend::EuclideanExpression>, boost::python::args("problem, timeA, timeB, nIntegrationPoints, expressionFactory, sqrtInvR") ); }
1,953
599
// Copyright 2012 the V8 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. #include "src/codegen.h" #if defined(V8_OS_AIX) #include <fenv.h> // NOLINT(build/c++11) #endif #include <memory> #include "src/ast/prettyprinter.h" #include "src/bootstrapper.h" #include "src/compilation-info.h" #include "src/counters.h" #include "src/debug/debug.h" #include "src/eh-frame.h" #include "src/objects-inl.h" #include "src/runtime/runtime.h" namespace v8 { namespace internal { #if defined(V8_OS_WIN) double modulo(double x, double y) { // Workaround MS fmod bugs. ECMA-262 says: // dividend is finite and divisor is an infinity => result equals dividend // dividend is a zero and divisor is nonzero finite => result equals dividend if (!(std::isfinite(x) && (!std::isfinite(y) && !std::isnan(y))) && !(x == 0 && (y != 0 && std::isfinite(y)))) { x = fmod(x, y); } return x; } #else // POSIX double modulo(double x, double y) { #if defined(V8_OS_AIX) // AIX raises an underflow exception for (Number.MIN_VALUE % Number.MAX_VALUE) feclearexcept(FE_ALL_EXCEPT); double result = std::fmod(x, y); int exception = fetestexcept(FE_UNDERFLOW); return (exception ? x : result); #else return std::fmod(x, y); #endif } #endif // defined(V8_OS_WIN) #define UNARY_MATH_FUNCTION(name, generator) \ static UnaryMathFunctionWithIsolate fast_##name##_function = nullptr; \ double std_##name(double x, Isolate* isolate) { return std::name(x); } \ void init_fast_##name##_function(Isolate* isolate) { \ if (FLAG_fast_math) fast_##name##_function = generator(isolate); \ if (!fast_##name##_function) fast_##name##_function = std_##name; \ } \ void lazily_initialize_fast_##name(Isolate* isolate) { \ if (!fast_##name##_function) init_fast_##name##_function(isolate); \ } \ double fast_##name(double x, Isolate* isolate) { \ return (*fast_##name##_function)(x, isolate); \ } UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction) #undef UNARY_MATH_FUNCTION #define __ ACCESS_MASM(masm_) #ifdef DEBUG Comment::Comment(MacroAssembler* masm, const char* msg) : masm_(masm), msg_(msg) { __ RecordComment(msg); } Comment::~Comment() { if (msg_[0] == '[') __ RecordComment("]"); } #endif // DEBUG #undef __ void CodeGenerator::MakeCodePrologue(CompilationInfo* info, const char* kind) { bool print_ast = false; const char* ftype; if (info->isolate()->bootstrapper()->IsActive()) { print_ast = FLAG_print_builtin_ast; ftype = "builtin"; } else { print_ast = FLAG_print_ast; ftype = "user-defined"; } if (FLAG_trace_codegen || print_ast) { std::unique_ptr<char[]> name = info->GetDebugName(); PrintF("[generating %s code for %s function: %s]\n", kind, ftype, name.get()); } #ifdef DEBUG if (info->parse_info() && print_ast) { PrintF("--- AST ---\n%s\n", AstPrinter(info->isolate()).PrintProgram(info->literal())); } #endif // DEBUG } Handle<Code> CodeGenerator::MakeCodeEpilogue(MacroAssembler* masm, EhFrameWriter* eh_frame_writer, CompilationInfo* info, Handle<Object> self_reference) { Isolate* isolate = info->isolate(); // Allocate and install the code. CodeDesc desc; Code::Flags flags = info->code_flags(); bool is_crankshafted = Code::ExtractKindFromFlags(flags) == Code::OPTIMIZED_FUNCTION || info->IsStub(); masm->GetCode(&desc); if (eh_frame_writer) eh_frame_writer->GetEhFrame(&desc); Handle<Code> code = isolate->factory()->NewCode( desc, flags, self_reference, false, is_crankshafted, info->prologue_offset(), info->is_debug() && !is_crankshafted); isolate->counters()->total_compiled_code_size()->Increment( code->instruction_size()); return code; } // Print function's source if it was not printed before. // Return a sequential id under which this function was printed. static int PrintFunctionSource(CompilationInfo* info, std::vector<Handle<SharedFunctionInfo>>* printed, int inlining_id, Handle<SharedFunctionInfo> shared) { // Outermost function has source id -1 and inlined functions take // source ids starting from 0. int source_id = -1; if (inlining_id != SourcePosition::kNotInlined) { for (unsigned i = 0; i < printed->size(); i++) { if (printed->at(i).is_identical_to(shared)) { return i; } } source_id = static_cast<int>(printed->size()); printed->push_back(shared); } Isolate* isolate = info->isolate(); if (!shared->script()->IsUndefined(isolate)) { Handle<Script> script(Script::cast(shared->script()), isolate); if (!script->source()->IsUndefined(isolate)) { CodeTracer::Scope tracing_scope(isolate->GetCodeTracer()); Object* source_name = script->name(); OFStream os(tracing_scope.file()); os << "--- FUNCTION SOURCE ("; if (source_name->IsString()) { os << String::cast(source_name)->ToCString().get() << ":"; } os << shared->DebugName()->ToCString().get() << ") id{"; os << info->optimization_id() << "," << source_id << "} start{"; os << shared->start_position() << "} ---\n"; { DisallowHeapAllocation no_allocation; int start = shared->start_position(); int len = shared->end_position() - start; String::SubStringRange source(String::cast(script->source()), start, len); for (const auto& c : source) { os << AsReversiblyEscapedUC16(c); } } os << "\n--- END ---\n"; } } return source_id; } // Print information for the given inlining: which function was inlined and // where the inlining occured. static void PrintInlinedFunctionInfo( CompilationInfo* info, int source_id, int inlining_id, const CompilationInfo::InlinedFunctionHolder& h) { CodeTracer::Scope tracing_scope(info->isolate()->GetCodeTracer()); OFStream os(tracing_scope.file()); os << "INLINE (" << h.shared_info->DebugName()->ToCString().get() << ") id{" << info->optimization_id() << "," << source_id << "} AS " << inlining_id << " AT "; const SourcePosition position = h.position.position; if (position.IsKnown()) { os << "<" << position.InliningId() << ":" << position.ScriptOffset() << ">"; } else { os << "<?>"; } os << std::endl; } // Print the source of all functions that participated in this optimizing // compilation. For inlined functions print source position of their inlining. static void DumpParticipatingSource(CompilationInfo* info) { AllowDeferredHandleDereference allow_deference_for_print_code; std::vector<Handle<SharedFunctionInfo>> printed; printed.reserve(info->inlined_functions().size()); PrintFunctionSource(info, &printed, SourcePosition::kNotInlined, info->shared_info()); const auto& inlined = info->inlined_functions(); for (unsigned id = 0; id < inlined.size(); id++) { const int source_id = PrintFunctionSource(info, &printed, id, inlined[id].shared_info); PrintInlinedFunctionInfo(info, source_id, id, inlined[id]); } } void CodeGenerator::PrintCode(Handle<Code> code, CompilationInfo* info) { if (FLAG_print_opt_source && info->IsOptimizing()) { DumpParticipatingSource(info); } #ifdef ENABLE_DISASSEMBLER AllowDeferredHandleDereference allow_deference_for_print_code; Isolate* isolate = info->isolate(); bool print_code = isolate->bootstrapper()->IsActive() ? FLAG_print_builtin_code : (FLAG_print_code || (info->IsStub() && FLAG_print_code_stubs) || (info->IsOptimizing() && FLAG_print_opt_code && info->shared_info()->PassesFilter(FLAG_print_opt_code_filter)) || (info->IsWasm() && FLAG_print_wasm_code)); if (print_code) { std::unique_ptr<char[]> debug_name = info->GetDebugName(); CodeTracer::Scope tracing_scope(info->isolate()->GetCodeTracer()); OFStream os(tracing_scope.file()); // Print the source code if available. bool print_source = info->parse_info() && (code->kind() == Code::OPTIMIZED_FUNCTION || code->kind() == Code::FUNCTION); if (print_source) { Handle<SharedFunctionInfo> shared = info->shared_info(); Handle<Script> script = info->script(); if (!script->IsUndefined(isolate) && !script->source()->IsUndefined(isolate)) { os << "--- Raw source ---\n"; StringCharacterStream stream(String::cast(script->source()), shared->start_position()); // fun->end_position() points to the last character in the stream. We // need to compensate by adding one to calculate the length. int source_len = shared->end_position() - shared->start_position() + 1; for (int i = 0; i < source_len; i++) { if (stream.HasMore()) { os << AsReversiblyEscapedUC16(stream.GetNext()); } } os << "\n\n"; } } if (info->IsOptimizing()) { if (FLAG_print_unopt_code && info->parse_info()) { os << "--- Unoptimized code ---\n"; info->closure()->shared()->code()->Disassemble(debug_name.get(), os); } os << "--- Optimized code ---\n" << "optimization_id = " << info->optimization_id() << "\n"; } else { os << "--- Code ---\n"; } if (print_source) { Handle<SharedFunctionInfo> shared = info->shared_info(); os << "source_position = " << shared->start_position() << "\n"; } code->Disassemble(debug_name.get(), os); os << "--- End code ---\n"; } #endif // ENABLE_DISASSEMBLER } } // namespace internal } // namespace v8
10,249
3,332
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2020, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED * STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************************************************************/ #include "../ForwardTranslator.hpp" #include "../../model/Model.hpp" #include "../../model/Schedule.hpp" #include "../../model/Schedule_Impl.hpp" #include "../../model/Node.hpp" #include "../../model/Node_Impl.hpp" #include "../../model/PlantLoop.hpp" #include "../../model/PlantLoop_Impl.hpp" #include "../../model/ThermalZone.hpp" #include "../../model/ThermalZone_Impl.hpp" #include "../../model/AirConditionerVariableRefrigerantFlow.hpp" #include "../../model/AirConditionerVariableRefrigerantFlow_Impl.hpp" #include "../../model/ZoneHVACTerminalUnitVariableRefrigerantFlow.hpp" #include "../../model/ZoneHVACTerminalUnitVariableRefrigerantFlow_Impl.hpp" #include "../../model/Curve.hpp" #include "../../model/Curve_Impl.hpp" #include "../../utilities/core/Logger.hpp" #include "../../utilities/core/Assert.hpp" #include <utilities/idd/AirConditioner_VariableRefrigerantFlow_FieldEnums.hxx> #include <utilities/idd/ZoneTerminalUnitList_FieldEnums.hxx> #include "../../utilities/idd/IddEnums.hpp" #include <utilities/idd/IddEnums.hxx> #include "../../utilities/idf/IdfExtensibleGroup.hpp" using namespace openstudio::model; using namespace std; namespace openstudio { namespace energyplus { boost::optional<IdfObject> ForwardTranslator::translateAirConditionerVariableRefrigerantFlow( AirConditionerVariableRefrigerantFlow & modelObject ) { boost::optional<std::string> s; boost::optional<double> value; IdfObject idfObject(IddObjectType::AirConditioner_VariableRefrigerantFlow); m_idfObjects.push_back(idfObject); // Name s = modelObject.name(); if( s ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatPumpName,*s); } // AvailabilityScheduleName if( boost::optional<model::Schedule> schedule = modelObject.availabilitySchedule() ) { if( boost::optional<IdfObject> _schedule = translateAndMapModelObject(schedule.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::AvailabilityScheduleName,_schedule->name().get()); } } // RatedTotalCoolingCapacity if( modelObject.isGrossRatedTotalCoolingCapacityAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::GrossRatedTotalCoolingCapacity,"Autosize"); } else if( (value = modelObject.grossRatedTotalCoolingCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::GrossRatedTotalCoolingCapacity,value.get()); } // RatedCoolingCOP if( (value = modelObject.grossRatedCoolingCOP()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::GrossRatedCoolingCOP,value.get()); } // MinimumOutdoorTemperatureinCoolingMode if( (value = modelObject.minimumOutdoorTemperatureinCoolingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MinimumOutdoorTemperatureinCoolingMode,value.get()); } // MaximumOutdoorTemperatureinCoolingMode if( (value = modelObject.maximumOutdoorTemperatureinCoolingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorTemperatureinCoolingMode,value.get()); } // CoolingCapacityRatioModifierFunctionofLowTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.coolingCapacityRatioModifierFunctionofLowTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingCapacityRatioModifierFunctionofLowTemperatureCurveName,_curve->name().get()); } } // CoolingCapacityRatioBoundaryCurveName if( boost::optional<model::Curve> curve = modelObject.coolingCapacityRatioBoundaryCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingCapacityRatioBoundaryCurveName,_curve->name().get()); } } // CoolingCapacityRatioModifierFunctionofHighTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.coolingCapacityRatioModifierFunctionofHighTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingCapacityRatioModifierFunctionofHighTemperatureCurveName,_curve->name().get()); } } // CoolingEnergyInputRatioModifierFunctionofLowTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.coolingEnergyInputRatioModifierFunctionofLowTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingEnergyInputRatioModifierFunctionofLowTemperatureCurveName,_curve->name().get()); } } // CoolingEnergyInputRatioBoundaryCurveName if( boost::optional<model::Curve> curve = modelObject.coolingEnergyInputRatioBoundaryCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingEnergyInputRatioBoundaryCurveName,_curve->name().get()); } } // CoolingEnergyInputRatioModifierFunctionofHighTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.coolingEnergyInputRatioModifierFunctionofHighTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingEnergyInputRatioModifierFunctionofHighTemperatureCurveName,_curve->name().get()); } } // CoolingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurveName if( boost::optional<model::Curve> curve = modelObject.coolingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurveName,_curve->name().get()); } } // CoolingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurveName if( boost::optional<model::Curve> curve = modelObject.coolingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurveName,_curve->name().get()); } } // CoolingCombinationRatioCorrectionFactorCurveName if( boost::optional<model::Curve> curve = modelObject.coolingCombinationRatioCorrectionFactorCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingCombinationRatioCorrectionFactorCurveName,_curve->name().get()); } } // CoolingPartLoadFractionCorrelationCurveName if( boost::optional<model::Curve> curve = modelObject.coolingPartLoadFractionCorrelationCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CoolingPartLoadFractionCorrelationCurveName,_curve->name().get()); } } // RatedTotalHeatingCapacity if( modelObject.isGrossRatedHeatingCapacityAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::GrossRatedHeatingCapacity,"Autosize"); } else if( (value = modelObject.grossRatedHeatingCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::GrossRatedHeatingCapacity,value.get()); } // RatedTotalHeatingCapacitySizingRatio if( (value = modelObject.ratedHeatingCapacitySizingRatio()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::RatedHeatingCapacitySizingRatio,value.get()); } // RatedHeatingCOP if( (value = modelObject.ratedHeatingCOP()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::GrossRatedHeatingCOP,value.get()); } // MinimumOutdoorTemperatureinHeatingMode if( (value = modelObject.minimumOutdoorTemperatureinHeatingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MinimumOutdoorTemperatureinHeatingMode,value.get()); } // MaximumOutdoorTemperatureinHeatingMode if( (value = modelObject.maximumOutdoorTemperatureinHeatingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorTemperatureinHeatingMode,value.get()); } // HeatingCapacityRatioModifierFunctionofLowTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.heatingCapacityRatioModifierFunctionofLowTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingCapacityRatioModifierFunctionofLowTemperatureCurveName,_curve->name().get()); } } // HeatingCapacityRatioBoundaryCurveName if( boost::optional<model::Curve> curve = modelObject.heatingCapacityRatioBoundaryCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingCapacityRatioBoundaryCurveName,_curve->name().get()); } } // HeatingCapacityRatioModifierFunctionofHighTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.heatingCapacityRatioModifierFunctionofHighTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingCapacityRatioModifierFunctionofHighTemperatureCurveName,_curve->name().get()); } } // HeatingEnergyInputRatioModifierFunctionofLowTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.heatingEnergyInputRatioModifierFunctionofLowTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingEnergyInputRatioModifierFunctionofLowTemperatureCurveName,_curve->name().get()); } } // HeatingEnergyInputRatioBoundaryCurveName if( boost::optional<model::Curve> curve = modelObject.heatingEnergyInputRatioBoundaryCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingEnergyInputRatioBoundaryCurveName,_curve->name().get()); } } // HeatingEnergyInputRatioModifierFunctionofHighTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.heatingEnergyInputRatioModifierFunctionofHighTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingEnergyInputRatioModifierFunctionofHighTemperatureCurveName,_curve->name().get()); } } // HeatingPerformanceCurveOutdoorTemperatureType if( (s = modelObject.heatingPerformanceCurveOutdoorTemperatureType()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingPerformanceCurveOutdoorTemperatureType,s.get()); } // HeatingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurveName if( boost::optional<model::Curve> curve = modelObject.heatingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingEnergyInputRatioModifierFunctionofLowPartLoadRatioCurveName,_curve->name().get()); } } // HeatingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurveName if( boost::optional<model::Curve> curve = modelObject.heatingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingEnergyInputRatioModifierFunctionofHighPartLoadRatioCurveName,_curve->name().get()); } } // HeatingCombinationRatioCorrectionFactorCurveName if( boost::optional<model::Curve> curve = modelObject.heatingCombinationRatioCorrectionFactorCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingCombinationRatioCorrectionFactorCurveName,_curve->name().get()); } } // HeatingPartLoadFractionCorrelationCurveName if( boost::optional<model::Curve> curve = modelObject.heatingPartLoadFractionCorrelationCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatingPartLoadFractionCorrelationCurveName,_curve->name().get()); } } // MinimumHeatPumpPartLoadRatio if( (value = modelObject.minimumHeatPumpPartLoadRatio()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MinimumHeatPumpPartLoadRatio,value.get()); } // ZoneNameforMasterThermostatLocation if( boost::optional<model::ThermalZone> zone = modelObject.zoneforMasterThermostatLocation() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::ZoneNameforMasterThermostatLocation,zone->name().get()); } // MasterThermostatPriorityControlType if( (s = modelObject.masterThermostatPriorityControlType()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::MasterThermostatPriorityControlType,s.get()); } // ThermostatPriorityScheduleName if( boost::optional<model::Schedule> schedule = modelObject.thermostatPrioritySchedule() ) { if( boost::optional<IdfObject> _schedule = translateAndMapModelObject(schedule.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::ThermostatPriorityScheduleName,_schedule->name().get()); } } // HeatPumpWasteHeatRecovery if( modelObject.heatPumpWasteHeatRecovery() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatPumpWasteHeatRecovery,"Yes"); } else { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatPumpWasteHeatRecovery,"No"); } // EquivalentPipingLengthusedforPipingCorrectionFactorinCoolingMode if( (value = modelObject.equivalentPipingLengthusedforPipingCorrectionFactorinCoolingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EquivalentPipingLengthusedforPipingCorrectionFactorinCoolingMode,value.get()); } // VerticalHeightusedforPipingCorrectionFactor if( (value = modelObject.verticalHeightusedforPipingCorrectionFactor()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::VerticalHeightusedforPipingCorrectionFactor,value.get()); } // PipingCorrectionFactorforLengthinCoolingModeCurveName if( boost::optional<model::Curve> curve = modelObject.pipingCorrectionFactorforLengthinCoolingModeCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::PipingCorrectionFactorforLengthinCoolingModeCurveName,_curve->name().get()); } } // PipingCorrectionFactorforHeightinCoolingModeCoefficient if( (value = modelObject.pipingCorrectionFactorforHeightinCoolingModeCoefficient()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::PipingCorrectionFactorforHeightinCoolingModeCoefficient,value.get()); } // EquivalentPipingLengthusedforPipingCorrectionFactorinHeatingMode if( (value = modelObject.equivalentPipingLengthusedforPipingCorrectionFactorinHeatingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EquivalentPipingLengthusedforPipingCorrectionFactorinHeatingMode,value.get()); } // PipingCorrectionFactorforLengthinHeatingModeCurveName if( boost::optional<model::Curve> curve = modelObject.pipingCorrectionFactorforLengthinHeatingModeCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::PipingCorrectionFactorforLengthinHeatingModeCurveName,_curve->name().get()); } } // PipingCorrectionFactorforHeightinHeatingModeCoefficient if( (value = modelObject.pipingCorrectionFactorforHeightinHeatingModeCoefficient()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::PipingCorrectionFactorforHeightinHeatingModeCoefficient,value.get()); } // CrankcaseHeaterPowerperCompressor if( (value = modelObject.crankcaseHeaterPowerperCompressor()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::CrankcaseHeaterPowerperCompressor,value.get()); } // NumberofCompressors { int number = modelObject.numberofCompressors(); idfObject.setUnsigned(AirConditioner_VariableRefrigerantFlowFields::NumberofCompressors,(unsigned)number); } // RatioofCompressorSizetoTotalCompressorCapacity if( (value = modelObject.ratioofCompressorSizetoTotalCompressorCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::RatioofCompressorSizetoTotalCompressorCapacity,value.get()); } // MaximumOutdoorDrybulbTemperatureforCrankcaseHeater if( (value = modelObject.maximumOutdoorDrybulbTemperatureforCrankcaseHeater()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorDryBulbTemperatureforCrankcaseHeater,value.get()); } // DefrostStrategy if( (s = modelObject.defrostStrategy()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::DefrostStrategy,s.get()); } // DefrostControl if( (s = modelObject.defrostControl()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::DefrostControl,s.get()); } // DefrostEnergyInputRatioModifierFunctionofTemperatureCurveName if( boost::optional<model::Curve> curve = modelObject.defrostEnergyInputRatioModifierFunctionofTemperatureCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::DefrostEnergyInputRatioModifierFunctionofTemperatureCurveName,_curve->name().get()); } } // DefrostTimePeriodFraction if( (value = modelObject.defrostTimePeriodFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::DefrostTimePeriodFraction,value.get()); } // ResistiveDefrostHeaterCapacity if( modelObject.isResistiveDefrostHeaterCapacityAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::ResistiveDefrostHeaterCapacity,"Autosize"); } else if( (value = modelObject.resistiveDefrostHeaterCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::ResistiveDefrostHeaterCapacity,value.get()); } // MaximumOutdoorDrybulbTemperatureforDefrostOperation if( (value = modelObject.maximumOutdoorDrybulbTemperatureforDefrostOperation()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorDrybulbTemperatureforDefrostOperation,value.get()); } // Condenser Type // It was decided that the "smart" logic shouldn't be in the model itself. // So now, we do two things: // * If condenserType is set, respect that, but issue Errors if it's wrong // * If condenserType is not set, we default it (default is done in the model actually) // * If VRF connected to a PlantLoop => WaterCooled, else "AirCooled" ("EvaporativelyCooled" is less common and will be reserved for people who // know what they are doing and are hardsetting it) std::string condenserType = modelObject.condenserType(); if (modelObject.isCondenserTypeDefaulted()) { // We log an Info anyways, might be useful if (openstudio::istringEqual(condenserType, "EvaporativelyCooled")) { LOG(Info, modelObject.briefDescription() << " is connected to a PlantLoop, defaulting condenserType to 'WaterCooled'."); } else { LOG(Info, modelObject.briefDescription() << " is not connected to a PlantLoop, defaulting condenserType to 'AirCooled'."); } } else { boost::optional<PlantLoop> _plant = modelObject.plantLoop(); if ( (openstudio::istringEqual(condenserType, "AirCooled") || openstudio::istringEqual(condenserType, "EvaporativelyCooled")) && _plant.is_initialized()) { LOG(Error, modelObject.briefDescription() << " has an hardcoded condenserType '" << condenserType << "' while it is connected to a PlantLoop."); } else if( openstudio::istringEqual(condenserType, "WaterCooled") && !_plant.is_initialized()) { LOG(Error, modelObject.briefDescription() << " has an hardcoded condenserType '" << condenserType << "' while it is NOT connected to a PlantLoop."); } } idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CondenserType, condenserType); // CondenserInletNodeName if( boost::optional<ModelObject> mo = modelObject.inletModelObject() ) { if( boost::optional<Node> node = mo->optionalCast<Node>() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CondenserInletNodeName,node->name().get()); } } // CondenserOutletNodeName if( boost::optional<ModelObject> mo = modelObject.outletModelObject() ) { if( boost::optional<Node> node = mo->optionalCast<Node>() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::CondenserOutletNodeName,node->name().get()); } } // WaterCondenserVolumeFlowRate if( modelObject.isWaterCondenserVolumeFlowRateAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::WaterCondenserVolumeFlowRate,"Autosize"); } else if( (value = modelObject.waterCondenserVolumeFlowRate()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::WaterCondenserVolumeFlowRate,value.get()); } // EvaporativeCondenserEffectiveness if( (value = modelObject.evaporativeCondenserEffectiveness()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserEffectiveness,value.get()); } // EvaporativeCondenserAirFlowRate if( modelObject.isEvaporativeCondenserAirFlowRateAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserAirFlowRate,"Autosize"); } else if( (value = modelObject.evaporativeCondenserAirFlowRate()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserAirFlowRate,value.get()); } // EvaporativeCondenserPumpRatedPowerConsumption if( modelObject.isEvaporativeCondenserPumpRatedPowerConsumptionAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserPumpRatedPowerConsumption,"Autosize"); } else if( ( value = modelObject.evaporativeCondenserPumpRatedPowerConsumption()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserPumpRatedPowerConsumption,value.get()); } // BasinHeaterCapacity if( (value = modelObject.basinHeaterCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterCapacity,value.get()); } // BasinHeaterSetpointTemperature if( (value = modelObject.basinHeaterSetpointTemperature()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterSetpointTemperature,value.get()); } // BasinHeaterOperatingScheduleName if( boost::optional<model::Schedule> schedule = modelObject.basinHeaterOperatingSchedule() ) { if( boost::optional<IdfObject> _schedule = translateAndMapModelObject(schedule.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterOperatingScheduleName,_schedule->name().get()); } } // FuelType if( (s = modelObject.fuelType()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::FuelType,s.get()); } // MinimumOutdoorTemperatureinHeatRecoveryMode if( (value = modelObject.minimumOutdoorTemperatureinHeatRecoveryMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MinimumOutdoorTemperatureinHeatRecoveryMode,value.get()); } // MaximumOutdoorTemperatureinHeatRecoveryMode if( (value = modelObject.maximumOutdoorTemperatureinHeatingMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorTemperatureinHeatRecoveryMode,value.get()); } // HeatRecoveryCoolingCapacityModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryCoolingCapacityModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingCapacityModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryCoolingCapacityFraction if( (value = modelObject.initialHeatRecoveryCoolingEnergyFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryCoolingCapacityFraction,value.get()); } // HeatRecoveryCoolingCapacityTimeConstant if( (value = modelObject.heatRecoveryCoolingCapacityTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingCapacityTimeConstant,value.get()); } // HeatRecoveryCoolingEnergyModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryCoolingEnergyModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingEnergyModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryCoolingEnergyFraction if( (value = modelObject.initialHeatRecoveryCoolingEnergyFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryCoolingEnergyFraction,value.get()); } // HeatRecoveryCoolingEnergyTimeConstant if( (value = modelObject.heatRecoveryCoolingEnergyTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingEnergyTimeConstant,value.get()); } // HeatRecoveryHeatingCapacityModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryHeatingCapacityModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingCapacityModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryHeatingCapacityFraction if( (value = modelObject.initialHeatRecoveryHeatingCapacityFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryHeatingCapacityFraction,value.get()); } // HeatRecoveryHeatingCapacityTimeConstant if( (value = modelObject.heatRecoveryHeatingCapacityTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingCapacityTimeConstant,value.get()); } // HeatRecoveryHeatingEnergyModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryHeatingEnergyModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingEnergyModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryHeatingEnergyFraction if( (value = modelObject.initialHeatRecoveryHeatingEnergyFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryHeatingEnergyFraction,value.get()); } // HeatRecoveryHeatingEnergyTimeConstant if( (value = modelObject.heatRecoveryHeatingEnergyTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingEnergyTimeConstant,value.get()); } // Terminal Unit List IdfObject _zoneTerminalUnitList(IddObjectType::ZoneTerminalUnitList); std::string terminalUnitListName = modelObject.name().get() + " Terminal List"; _zoneTerminalUnitList.setString(ZoneTerminalUnitListFields::ZoneTerminalUnitListName,terminalUnitListName); idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::ZoneTerminalUnitListName,terminalUnitListName); m_idfObjects.push_back(_zoneTerminalUnitList); std::vector<ZoneHVACTerminalUnitVariableRefrigerantFlow> terminals = modelObject.terminals(); for( auto & terminal : terminals ) { boost::optional<IdfObject> _terminal = translateAndMapModelObject(terminal); OS_ASSERT(_terminal); IdfExtensibleGroup eg = _zoneTerminalUnitList.pushExtensibleGroup(); eg.setString(ZoneTerminalUnitListExtensibleFields::ZoneTerminalUnitName,_terminal->name().get()); } // WaterCondenserVolumeFlowRate if( modelObject.isWaterCondenserVolumeFlowRateAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::WaterCondenserVolumeFlowRate,"Autosize"); } else if( (value = modelObject.waterCondenserVolumeFlowRate()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::WaterCondenserVolumeFlowRate,value.get()); } // EvaporativeCondenserEffectiveness if( (value = modelObject.evaporativeCondenserEffectiveness()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserEffectiveness,value.get()); } // EvaporativeCondenserAirFlowRate if( modelObject.isEvaporativeCondenserAirFlowRateAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserAirFlowRate,"Autosize"); } else if( (value = modelObject.evaporativeCondenserAirFlowRate()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserAirFlowRate,value.get()); } // EvaporativeCondenserPumpRatedPowerConsumption if( modelObject.isEvaporativeCondenserPumpRatedPowerConsumptionAutosized() ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserPumpRatedPowerConsumption,"Autosize"); } else if( (value = modelObject.evaporativeCondenserPumpRatedPowerConsumption()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::EvaporativeCondenserPumpRatedPowerConsumption,value.get()); } // BasinHeaterCapacity if( (value = modelObject.basinHeaterCapacity()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterCapacity,value.get()); } // BasinHeaterSetpointTemperature if( (value = modelObject.basinHeaterSetpointTemperature()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterSetpointTemperature,value.get()); } // BasinHeaterOperatingScheduleName if( boost::optional<model::Schedule> schedule = modelObject.basinHeaterOperatingSchedule() ) { if( boost::optional<IdfObject> _schedule = translateAndMapModelObject(schedule.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::BasinHeaterOperatingScheduleName,_schedule->name().get()); } } // FuelType if( (s = modelObject.fuelType()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::FuelType,s.get()); } // MinimumOutdoorTemperatureinHeatRecoveryMode if( (value = modelObject.minimumOutdoorTemperatureinHeatRecoveryMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MinimumOutdoorTemperatureinHeatRecoveryMode,value.get()); } // MaximumOutdoorTemperatureinHeatRecoveryMode if( (value = modelObject.maximumOutdoorTemperatureinHeatRecoveryMode()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::MaximumOutdoorTemperatureinHeatRecoveryMode,value.get()); } // HeatRecoveryCoolingCapacityModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryCoolingCapacityModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingCapacityModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryCoolingCapacityFraction if( (value = modelObject.initialHeatRecoveryCoolingCapacityFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryCoolingCapacityFraction,value.get()); } // HeatRecoveryCoolingCapacityTimeConstant if( (value = modelObject.heatRecoveryCoolingCapacityTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingCapacityTimeConstant,value.get()); } // HeatRecoveryCoolingEnergyModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryCoolingEnergyModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingEnergyModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryCoolingEnergyFraction if( (value = modelObject.initialHeatRecoveryCoolingEnergyFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryCoolingEnergyFraction,value.get()); } // HeatRecoveryCoolingEnergyTimeConstant if( (value = modelObject.heatRecoveryCoolingEnergyTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryCoolingEnergyTimeConstant,value.get()); } // HeatRecoveryHeatingCapacityModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryHeatingCapacityModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingCapacityModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryHeatingCapacityFraction if( (value = modelObject.initialHeatRecoveryHeatingCapacityFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryHeatingCapacityFraction,value.get()); } // HeatRecoveryHeatingCapacityTimeConstant if( (value = modelObject.heatRecoveryHeatingCapacityTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingCapacityTimeConstant,value.get()); } // HeatRecoveryHeatingEnergyModifierCurveName if( boost::optional<model::Curve> curve = modelObject.heatRecoveryHeatingEnergyModifierCurve() ) { if( boost::optional<IdfObject> _curve = translateAndMapModelObject(curve.get()) ) { idfObject.setString(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingEnergyModifierCurveName,_curve->name().get()); } } // InitialHeatRecoveryHeatingEnergyFraction if( (value = modelObject.initialHeatRecoveryHeatingEnergyFraction()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::InitialHeatRecoveryHeatingEnergyFraction,value.get()); } // HeatRecoveryHeatingEnergyTimeConstant if( (value = modelObject.heatRecoveryHeatingEnergyTimeConstant()) ) { idfObject.setDouble(AirConditioner_VariableRefrigerantFlowFields::HeatRecoveryHeatingEnergyTimeConstant,value.get()); } return idfObject; } } // energyplus } // openstudio
38,681
12,986
/* * Author: Christian Rauch * * Copyright (c) 2018, University Of Edinburgh * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of nor the names of its contributors may be used to * endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "task_map/Point2Line.hpp" REGISTER_TASKMAP_TYPE("Point2Line", exotica::Point2Line); namespace exotica { Eigen::Vector3d Point2Line::distance(const Eigen::Vector3d &point, const Eigen::Vector3d &line, const bool infinite, const bool dbg) { // http://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html // let: // s: start of line // e: end of line // p: point // then the point on vector v = e-s that is closest to p is vp = s + t*(e-s) with // t = ((s-p)*(e-s)) / (|e-s|^2) (* denotes the dot product) // the line starts at the origin of BaseOffset, hence s=0, v='line', vp=t*'line' double t = (-point).dot(line) / line.norm(); if (dbg) HIGHLIGHT_NAMED("P2L", "t " << t); if (!infinite) { // clip to to range [0,1] t = std::min(std::max(0.0, t), 1.0); if (dbg) HIGHLIGHT_NAMED("P2L", "|t| " << t); } // vector from point 'p' to point 'vp' on line const Eigen::Vector3d dv = (t * line) - point; if (dbg) HIGHLIGHT_NAMED("P2L", "dv " << dv.transpose()); return dv; } Point2Line::Point2Line() {} void Point2Line::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi) { if (phi.rows() != Kinematics[0].Phi.rows()) throw_named("Wrong size of phi!"); for (int i = 0; i < Kinematics[0].Phi.rows(); i++) { phi(i) = distance(Eigen::Map<const Eigen::Vector3d>(Kinematics[0].Phi(i).p.data), line, infinite, debug_).norm(); } } void Point2Line::update(Eigen::VectorXdRefConst x, Eigen::VectorXdRef phi, Eigen::MatrixXdRef J) { if (phi.rows() != Kinematics[0].Phi.rows()) throw_named("Wrong size of phi!"); if (J.rows() != Kinematics[0].J.rows() || J.cols() != Kinematics[0].J(0).data.cols()) throw_named("Wrong size of J! " << Kinematics[0].J(0).data.cols()); for (int i = 0; i < Kinematics[0].Phi.rows(); i++) { // direction from point to line const Eigen::Vector3d dv = distance(Eigen::Map<const Eigen::Vector3d>(Kinematics[0].Phi(i).p.data), line, infinite, debug_); phi(i) = dv.norm(); for (int j = 0; j < J.cols(); j++) { J(i, j) = -dv.dot(Eigen::Map<const Eigen::Vector3d>(Kinematics[0].J[i].getColumn(j).vel.data)) / dv.norm(); } } } void Point2Line::Instantiate(Point2LineInitializer &init) { line = init.EndPoint.head<3>() - boost::any_cast<Eigen::VectorXd>(init.EndEffector[0].getProperty("BaseOffset")).head<3>(); infinite = init.infinite; } int Point2Line::taskSpaceDim() { return Kinematics[0].Phi.rows(); } } // namespace exotica
4,196
1,556
/**************************************************************************** ** Meta object code from reading C++ file 'bip38tooldialog.h' ** ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "qt/bip38tooldialog.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'bip38tooldialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_Bip38ToolDialog_t { QByteArrayData data[11]; char stringdata0[286]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Bip38ToolDialog_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Bip38ToolDialog_t qt_meta_stringdata_Bip38ToolDialog = { { QT_MOC_LITERAL(0, 0, 15), // "Bip38ToolDialog" QT_MOC_LITERAL(1, 16, 32), // "on_addressBookButton_ENC_clicked" QT_MOC_LITERAL(2, 49, 0), // "" QT_MOC_LITERAL(3, 50, 26), // "on_pasteButton_ENC_clicked" QT_MOC_LITERAL(4, 77, 31), // "on_encryptKeyButton_ENC_clicked" QT_MOC_LITERAL(5, 109, 28), // "on_copyKeyButton_ENC_clicked" QT_MOC_LITERAL(6, 138, 26), // "on_clearButton_ENC_clicked" QT_MOC_LITERAL(7, 165, 26), // "on_pasteButton_DEC_clicked" QT_MOC_LITERAL(8, 192, 31), // "on_decryptKeyButton_DEC_clicked" QT_MOC_LITERAL(9, 224, 34), // "on_importAddressButton_DEC_cl..." QT_MOC_LITERAL(10, 259, 26) // "on_clearButton_DEC_clicked" }, "Bip38ToolDialog\0on_addressBookButton_ENC_clicked\0" "\0on_pasteButton_ENC_clicked\0" "on_encryptKeyButton_ENC_clicked\0" "on_copyKeyButton_ENC_clicked\0" "on_clearButton_ENC_clicked\0" "on_pasteButton_DEC_clicked\0" "on_decryptKeyButton_DEC_clicked\0" "on_importAddressButton_DEC_clicked\0" "on_clearButton_DEC_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Bip38ToolDialog[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 9, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 0, 59, 2, 0x08 /* Private */, 3, 0, 60, 2, 0x08 /* Private */, 4, 0, 61, 2, 0x08 /* Private */, 5, 0, 62, 2, 0x08 /* Private */, 6, 0, 63, 2, 0x08 /* Private */, 7, 0, 64, 2, 0x08 /* Private */, 8, 0, 65, 2, 0x08 /* Private */, 9, 0, 66, 2, 0x08 /* Private */, 10, 0, 67, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, QMetaType::Void, 0 // eod }; void Bip38ToolDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Bip38ToolDialog *_t = static_cast<Bip38ToolDialog *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_addressBookButton_ENC_clicked(); break; case 1: _t->on_pasteButton_ENC_clicked(); break; case 2: _t->on_encryptKeyButton_ENC_clicked(); break; case 3: _t->on_copyKeyButton_ENC_clicked(); break; case 4: _t->on_clearButton_ENC_clicked(); break; case 5: _t->on_pasteButton_DEC_clicked(); break; case 6: _t->on_decryptKeyButton_DEC_clicked(); break; case 7: _t->on_importAddressButton_DEC_clicked(); break; case 8: _t->on_clearButton_DEC_clicked(); break; default: ; } } Q_UNUSED(_a); } const QMetaObject Bip38ToolDialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_Bip38ToolDialog.data, qt_meta_data_Bip38ToolDialog, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *Bip38ToolDialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Bip38ToolDialog::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_Bip38ToolDialog.stringdata0)) return static_cast<void*>(this); return QDialog::qt_metacast(_clname); } int Bip38ToolDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 9) qt_static_metacall(this, _c, _id, _a); _id -= 9; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 9) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 9; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
5,266
2,205
#include <atomic> #include <algorithm> #include <thread> #include <chrono> #include "world.hpp" #include "util.hpp" #include "player.hpp" #include "dir.hpp" #include "room.hpp" #include "object.hpp" World::World() { this->self = std::shared_ptr<World>(this); this->startActorThread(); } World::~World() { this->destructing = true; this->actorThread.join(); this->nextID = 1; // start at 1, so any default-initialized ids are never valid. } ID World::NextID() { return this->nextID.fetch_add(1, std::memory_order_relaxed); // TODO verify order } void World::AddRoom(std::shared_ptr<Room> r) { this->rooms[r->ID] = r; this->room_links[r->ID] = std::map<Direction, RoomID>(); } void World::AddPlayer(std::shared_ptr<Player> player, RoomID room_id) { this->players[player->ID] = player; this->name_players[player->Name] = player->ID; this->SetPlayerRoom(player->ID, room_id); } void World::AddObject(std::shared_ptr<Object> obj, PlayerID player_id) { this->objects[obj->ID] = obj; // TODO handle player not existing. Handle errors everywhere. Go has ruined me. std::shared_ptr<Player> player = this->GetPlayer(player_id); player->Objects[obj->ID] = obj; obj->LocationID.Player = player_id; obj->LocationType = ObjectLocationPlayer; } // LinkRooms links the two rooms in both direction, where the Direction is from room0 to room1. // TODO add a special function for one-way paths. void World::LinkRooms(RoomID room0, RoomID room1, Direction dir) { this->room_links[room0][dir] = room1; this->room_links[room1][reverse_direction(dir)] = room0; } void World::SetPlayerRoom(PlayerID playerID, RoomID newRoomID) { const auto oldPlayerRoomID = this->player_rooms.find(playerID); if(oldPlayerRoomID != this->player_rooms.end()) { auto playerSet = this->room_players.find(oldPlayerRoomID->second); playerSet->second.erase(playerID); // TODO check and error if world.room_players[room] doesn't exist (should never happen) } this->player_rooms[playerID] = newRoomID; this->room_players[newRoomID].insert(playerID); } void World::SetObjectRoom(ObjectID object_id, RoomID new_room_id) { std::shared_ptr<Object> obj = this->objects[object_id]; switch(obj->LocationType) { case ObjectLocationRoom: { RoomID old_room_id = obj->LocationID.Room; std::shared_ptr<Room> old_room(this->rooms[old_room_id]); old_room->Objects.erase(object_id); break; } case ObjectLocationPlayer: { PlayerID player_id = obj->LocationID.Player; std::shared_ptr<Player> player = this->players[player_id]; player->Objects.erase(object_id); break; } default: { // TODO handle error; should never happen return; } } std::shared_ptr<Room> room = this->rooms[new_room_id]; room->Objects[object_id] = obj; obj->LocationType = ObjectLocationRoom; obj->LocationID.Room = new_room_id; // TODO print the move to players in previous and new room } void World::startActorThread() { // TODO change to something lighter weight than an OS thread // TBB? Microthread? Poll? Something else? this->actorThread = std::thread([=]() { for(;;) { if(this->destructing) { return; } for(auto it = this->objects.begin(), end = this->objects.end(); it != end; ++it) { std::shared_ptr<Object> obj = it->second; if(obj->Actor_ == nullptr) { continue; } obj->Actor_->Do(this->GetShared(), obj->ID); } std::this_thread::sleep_for(std::chrono::milliseconds(this->ActorThreadIntervalMS)); } }); } // GetPlayer returns the player with the given ID. // If the ID doesn't exist, returns NULL. std::shared_ptr<Player> World::GetPlayer(PlayerID v) { return this->players[v]; } // GetRoom returns the room with the given ID. // If the ID doesn't exist, returns NULL. std::shared_ptr<Room> World::GetRoom(RoomID v) { return this->rooms[v]; } // GetObject returns the object with the given ID. // If the ID doesn't exist, returns NULL. std::shared_ptr<Object> World::GetObject(ObjectID v) { return this->objects[v]; } // Returns the room the given player is in. RoomID World::GetPlayerRoom(PlayerID v) { // TODO change to return a bool? If a room didn't exist, it would be a subtle bug bug // But, players should always be in a room, right? return this->player_rooms[v]; } std::map<Direction, RoomID> World::GetRoomLinks(RoomID v) { // TODO change to return a bool? If a room didn't exist, it would be a very subtle bug return this->room_links[v]; } PlayerID World::GetPlayerByName(std::string name) { // TODO change to return a bool? If a player didn't exist, it would be a very subtle bug return this->name_players[name]; } std::shared_ptr<World> World::GetShared() { return self; } LockedWorld::LockedWorld(LockableWorld w) { w.m->lock(); this->w = w.w; this->l = w; } LockedWorld::~LockedWorld() { l.m->unlock(); }
4,784
1,738
/************************************************************************* * * ADOBE CONFIDENTIAL * * Copyright 2017 Adobe * * All Rights Reserved. * * NOTICE: Adobe permits you to use, modify, and distribute this file in * accordance with the terms of the Adobe license agreement accompanying * it. If you have received this file from a source other than Adobe, * then your use, modification, or distribution of it requires the prior * written permission of Adobe. * **************************************************************************/ #pragma once #include "AITypes.h" #include "AIAssert.hpp" #include "IAILiteralString.h" /** Usage: struct Widget { ai::int32 id = -1; bool processed = false; std::string name; }; std::unique_ptr<Widget> CreateWidget(); void ProcessWidget() { auto widget1 = CreateWidget(); auto widget2 = CreateWidget(); ai::Expects(widget1 != nullptr); // Throws by default ai::Expects(widget2 != nullptr, "Widget should not be NULL"); // Throws with custom message ai::Expects(widget1->id != -1, "Wrong widget id", ai::ContractPolicy::kAssert); // Only Assert ai::Expects(!widget1->name.empty(), "Wrong widget name", ai::ContractPolicy::kAssert); // Only Assert // ... // ... ai::Ensures(widget1->processed == true, "Widget should be processed", ai::ContractPolicy::kAssertAndThrow); // Assert and Throw ai::Ensures(widget2->processed == true, ai::ContractPolicy::kAssertAndThrow); // Assert and Throw } */ namespace ai { namespace Contract { constexpr ai::LiteralString kDefaultPreconditionMsg {"Failed Precondition"}; constexpr ai::LiteralString kDefaultPostconditionMsg {"Failed Postcondition"}; /** Exception class for Contract violation */ struct Violation : public ai::LogicError { explicit Violation(const char* message) : ai::LogicError(kBadParameterErr, message) { } }; /** Contract policy types */ struct AssertPolicy {}; struct ThrowPolicy {}; struct AssertAndThrowPolicy {}; /** Contract verification */ template <typename T> /* Assert */ inline void Check(T condition, const char* msg, AssertPolicy) { AIMsgAssert(condition, msg); } template <typename T> /* Throw */ inline void Check(T condition, const char* msg, ThrowPolicy) { if (!condition) { throw Violation{msg}; } } template <typename T> /* Assert and Throw */ inline void Check(T condition, const char* msg, AssertAndThrowPolicy) { if (!condition) { AIMsgAssert(false, msg); throw Violation{msg}; } } } // namespace Contract namespace ContractPolicy { // Instances of the Contract policy types constexpr Contract::AssertPolicy kAssert {}; constexpr Contract::ThrowPolicy kThrow {}; constexpr Contract::AssertAndThrowPolicy kAssertAndThrow {}; } // namespace ContractPolicy template <typename T, typename Policy = Contract::ThrowPolicy> inline void Expects(T condition, const char* msg = Contract::kDefaultPreconditionMsg, Policy policy = ContractPolicy::kThrow) { Contract::Check(condition, msg, policy); } template <typename T, typename Policy> inline void Expects(T condition, Policy policy) { Contract::Check(condition, Contract::kDefaultPreconditionMsg, policy); } template <typename T, typename Policy = Contract::ThrowPolicy> inline void Ensures(T condition, const char* msg = Contract::kDefaultPostconditionMsg, Policy policy = ContractPolicy::kThrow) { Contract::Check(condition, msg, policy); } template <typename T, typename Policy> inline void Ensures(T condition, Policy policy) { Contract::Check(condition, Contract::kDefaultPostconditionMsg, policy); } } // namespace ai
3,695
1,208
#include <vector> #include <iostream> #include "bigmap.h" #include "bigmultimap.h" #include "indexer.h" typedef std::vector<bits24> bits24_vec; // compact at most 3 20-bit integers into one 64-bit integer // bit 62 and 61 indicate the count (1, 2 or 3) uint64_t compact_index_list(uint32_t* index_ptr, int index_count) { uint64_t res = 0; for(int i=0; i<index_count && i<3; i++) { res |= uint64_t(index_ptr[i])<<(i*20); } res |= uint64_t(index_count) << 61; return res; } struct bits24_list { bits24 arr[3]; bits24* data; int size; uint32_t get(int i) { if(data==nullptr) return arr[i].to_uint32(); return data[i].to_uint32(); } // expand one 64-bit integer into 1, 2 or 3 20-bit integers. static bits24_list from_uint64(uint64_t u) { bits24_list l; l.data = nullptr; l.size = u >> 61; assert(l.size <= 3); for(int i=0; i<l.size; i++) { l.arr[i] = bits24::from_uint64((u>>(i*20))&0xFFFFF); } return l; } }; inline i64_list vec_to_i64_list(std::vector<int64_t>* i64_vec) { if(i64_vec->size() == 0) { auto res = i64_list{.vec_ptr=size_t(0), .data=nullptr, .size=0}; delete i64_vec; return res; } else if(i64_vec->size() == 1) { auto res = i64_list{.vec_ptr=size_t(i64_vec->at(0)), .data=nullptr, .size=i64_vec->size()}; delete i64_vec; return res; } return i64_list{.vec_ptr=(size_t)i64_vec, .data=i64_vec->data(), .size=i64_vec->size()}; } //| Name | Key | Value | //| -------------------- | --------------------------- | ----------------------- | //| Block Content | Height1 + 3 + Offset5 | Pointer to TxIndex3 Vec | //| BlockHash Index | ShortHashID6 | Height4 | //| Transaction Content | Height4 + TxIndex3 | Offset5 | //| TransactionHash Index| ShortHashID6 | Offset5 | //| Address to TxKey | ShortHashID6 + BlockHeight4 | Magic Uint64 | //| Topic to TxKey | ShortHashID6 + BlockHeight4 | Magic Uint64 | // We carefully choose the data types to make sure there are no padding bytes in // the leaf nodes of btree_map (which are also called as target nodes) // positions are actually the value for block heights, but in blk_htpos2ptr, we // take them as part of keys, just to avoid padding bytes. typedef bigmap<(1<<8), uint64_t, bits24_vec*> blk_htpos2ptr; typedef bigmultimap<(1<<16), uint32_t, uint32_t> blk_hash2ht; typedef bigmap<(1<<16), bits40, bits40> tx_id2pos; typedef bigmultimap<(1<<16), bits32, bits40> tx_hash2pos; typedef bigmap<(1<<16), uint64_t, uint64_t> log_map; class indexer { blk_htpos2ptr blk_htpos2ptr_map; blk_hash2ht blk_hash2ht_map; tx_id2pos tx_id2pos_map; tx_hash2pos tx_hash2pos_map; log_map src_map; log_map dst_map; log_map addr_map; log_map topic_map; int max_offset_count; typename blk_htpos2ptr::basic_map::iterator get_iter_at_height(uint32_t height, bool* ok); public: indexer(): max_offset_count(1<<30) {}; ~indexer() { auto it = blk_htpos2ptr_map.get_iterator(0, 0); while(it.valid()) { delete it.value(); it.next(); } }; indexer(const indexer& other) = delete; indexer& operator=(const indexer& other) = delete; indexer(indexer&& other) = delete; indexer& operator=(indexer&& other) = delete; void set_max_offset_count(int c) { max_offset_count = c; } void add_block(uint32_t height, uint64_t hash48, int64_t offset40); void erase_block(uint32_t height, uint64_t hash48); int64_t offset_by_block_height(uint32_t height); bits24_vec* get_vec_at_height(uint32_t height, bool create_if_null); i64_list offsets_by_block_hash(uint64_t hash48); void add_tx(uint64_t id56, uint64_t hash48, int64_t offset40); void erase_tx(uint64_t id56, uint64_t hash48, int64_t offset40); int64_t offset_by_tx_id(uint64_t id56); i64_list offsets_by_tx_id_range(uint64_t start_id56, uint64_t end_id56); i64_list offsets_by_tx_hash(uint64_t hash48); void add_to_log_map(log_map& m, uint64_t hash48, uint32_t height, uint32_t* index_ptr, int index_count); void erase_in_log_map(log_map& m, uint64_t hash48, uint32_t height) { m.erase(hash48>>32, (hash48<<32)|uint64_t(height)); } void add_src2tx(uint64_t hash48, uint32_t height, uint32_t* index_ptr, int index_count) { add_to_log_map(src_map, hash48, height, index_ptr, index_count); } void erase_src2tx(uint64_t hash48, uint32_t height) { erase_in_log_map(src_map, hash48, height); } void add_dst2tx(uint64_t hash48, uint32_t height, uint32_t* index_ptr, int index_count) { add_to_log_map(dst_map, hash48, height, index_ptr, index_count); } void erase_dst2tx(uint64_t hash48, uint32_t height) { erase_in_log_map(dst_map, hash48, height); } void add_addr2tx(uint64_t hash48, uint32_t height, uint32_t* index_ptr, int index_count) { add_to_log_map(addr_map, hash48, height, index_ptr, index_count); } void erase_addr2tx(uint64_t hash48, uint32_t height) { erase_in_log_map(addr_map, hash48, height); } void add_topic2tx(uint64_t hash48, uint32_t height, uint32_t* index_ptr, int index_count) { add_to_log_map(topic_map, hash48, height, index_ptr, index_count); } void erase_topic2tx(uint64_t hash48, uint32_t height) { erase_in_log_map(topic_map, hash48, height); } // iterator over tx's id56 class tx_iterator { bool _valid; indexer* _parent; int _end_idx; uint64_t _end_key; bits24_list _curr_list; //current block's bits24_list int _curr_list_idx; //pointing to an element in _curr_list.data typename log_map::iterator _iter; log_map* _log_map; void load_list() {//fill data to _curr_list _curr_list_idx = 0; auto magic_u64 = _iter.value(); auto height = uint32_t(_iter.key()); auto tag = magic_u64>>61; if(tag == 7) { // more than 3 members. find them in block's bits24_vec magic_u64 = (magic_u64<<3)>>3; //clear the tag auto vec = _parent->get_vec_at_height(height, false); assert(vec != nullptr); _curr_list.size = (magic_u64 & ((1<<20)-1)); _curr_list.data = vec->data() + (magic_u64 >> 20); } else { // no more than 3 members. extract them out from magic_u64 assert(tag != 0 && tag <= 3); _curr_list = bits24_list::from_uint64(magic_u64); } assert(_curr_list.size != 0); } public: friend class indexer; bool valid() { return _valid && _iter.valid() && _curr_list_idx < _curr_list.size; } uint64_t value() {//returns id56: 4 bytes height and 3 bytes offset if(!valid()) return uint64_t(-1); auto height = uint64_t(uint32_t(_iter.key())); //discard the high 32 bits of Key return (height<<24)|_curr_list.get(_curr_list_idx); } void next() { if(!valid()) { _valid = false; return; } if(_curr_list_idx < _curr_list.size) { //within same height _curr_list_idx++; } if(_curr_list_idx == _curr_list.size) { _iter.next(); //to the next height if(is_after_end()) { _valid = false; return; } load_list(); } } void next_till_value(uint64_t value) { if(this->value() >= value) { return; } uint32_t height = value >> 24; uint64_t key = ((_end_key>>32)<<32)|uint64_t(height); // switch the target height _iter = _log_map->get_iterator(_end_idx, key); _valid = !is_after_end(); if(_valid) { load_list(); while(this->value() < value) { next(); } } } bool is_after_end() { if(!_iter.valid()) { return true; } if(_iter.curr_idx() > _end_idx || (_iter.curr_idx() == _end_idx && _iter.key() >= _end_key)) { return true; } return false; } void show_pos() { std::cout<<"Idx "<<_iter.curr_idx()<<std::hex<<" key "<<_iter.key()<<std::endl; } }; private: tx_iterator _iterator_at_log_map(log_map& m, uint64_t hash48, uint32_t start_height, uint32_t end_height) { tx_iterator it; if(start_height > end_height) { it._valid = false; return it; } it._parent = this; it._end_idx = hash48>>32; it._end_key = (hash48<<32)|uint64_t(end_height); it._iter = m.get_iterator(hash48>>32, (hash48<<32)|uint64_t(start_height)); it._log_map = &m; it._valid = !it.is_after_end(); if(it._valid) { it.load_list(); } return it; } i64_list query_tx_offsets_by(log_map& m, uint64_t hash48, uint32_t start_height, uint32_t end_height) { auto i64_vec = new std::vector<int64_t>; auto iter = _iterator_at_log_map(m, hash48, start_height, end_height); for(int count = 0; iter.valid() && count++ < max_offset_count; iter.next()) { i64_vec->push_back(offset_by_tx_id(iter.value())); } return vec_to_i64_list(i64_vec); } public: tx_iterator addr_iterator(uint64_t hash48, uint32_t start_height, uint32_t end_height) { return _iterator_at_log_map(this->addr_map, hash48, start_height, end_height); } tx_iterator topic_iterator(uint64_t hash48, uint32_t start_height, uint32_t end_height) { return _iterator_at_log_map(this->topic_map, hash48, start_height, end_height); } i64_list query_tx_offsets_by_src(uint64_t hash48, uint32_t start_height, uint32_t end_height) { return query_tx_offsets_by(this->src_map, hash48, start_height, end_height); } i64_list query_tx_offsets_by_dst(uint64_t hash48, uint32_t start_height, uint32_t end_height) { return query_tx_offsets_by(this->dst_map, hash48, start_height, end_height); } i64_list query_tx_offsets(const tx_offsets_query& q); }; // add a new block's information, return whether this 'hash48' is available to use void indexer::add_block(uint32_t height, uint64_t hash48, int64_t offset40) { auto vec = get_vec_at_height(height-1, false); //shrink the previous block's bits24_vec to save memory if(vec != nullptr) vec->shrink_to_fit(); // concat the low 3 bytes of height and 5 bytes of offset40 into ht3off5 uint64_t ht3off5 = (uint64_t(height)<<40) | ((uint64_t(offset40)<<24)>>24); bool ok; auto it = get_iter_at_height(height, &ok); if(ok && it->second!=nullptr) { it->second->clear(); } else { blk_htpos2ptr_map.set(height>>24, ht3off5, nullptr); } blk_hash2ht_map.insert(hash48>>32, uint32_t(hash48), height); } // given a block's height, return the corresponding iterator // *ok indicates whether this iterator is valid typename blk_htpos2ptr::basic_map::iterator indexer::get_iter_at_height(uint32_t height, bool* ok) { uint64_t ht3off5 = (uint64_t(height)<<40); auto it = blk_htpos2ptr_map.seek(height>>24, ht3off5, ok); *ok = (*ok) && (ht3off5>>40) == (it->first>>40); //whether the 3 bytes of height matches return it; } // erase an old block's information void indexer::erase_block(uint32_t height, uint64_t hash48) { bool ok; auto it = get_iter_at_height(height, &ok); if(ok) { delete it->second; // free the bits24_vec blk_htpos2ptr_map.erase(height>>24, it->first); //TODO } blk_hash2ht_map.erase(hash48>>32, uint32_t(hash48), height); } // given a block's height, return its offset int64_t indexer::offset_by_block_height(uint32_t height) { bool ok; auto it = get_iter_at_height(height, &ok); if(!ok) { return -1; } return (it->first<<24)>>24; //offset40 is embedded in key's low 40 bits } // get the bits24_vec for height bits24_vec* indexer::get_vec_at_height(uint32_t height, bool create_if_null) { bool ok; auto it = get_iter_at_height(height, &ok); if(!ok) { return nullptr; //no such height } if(it->second == nullptr && create_if_null) { auto v = new bits24_vec; it->second = v; return v; } return it->second; } // given a block's hash48, return its possible offsets i64_list indexer::offsets_by_block_hash(uint64_t hash48) { auto vec = blk_hash2ht_map.get(hash48>>32, uint32_t(hash48)); if(vec.size() == 0) { return i64_list{.vec_ptr=0, .data=nullptr, .size=0}; } else if(vec.size() == 1) { auto off = offset_by_block_height(vec[0]); return i64_list{.vec_ptr=size_t(off), .data=nullptr, .size=1}; } auto i64_vec = new std::vector<int64_t>; for(int i = 0; i < int(vec.size()); i++) { i64_vec->push_back(offset_by_block_height(vec[i])); } return i64_list{.vec_ptr=(size_t)i64_vec, .data=i64_vec->data(), .size=i64_vec->size()}; } // A transaction's id has 56 bits: 32 bits height + 24 bits in-block index // add a new transaction's information, return whether hash48 is available to use void indexer::add_tx(uint64_t id56, uint64_t hash48, int64_t offset40) { auto off40 = bits40::from_int64(offset40); tx_id2pos_map.set(id56>>40, bits40::from_uint64(id56), off40); tx_hash2pos_map.insert(hash48>>32, bits32::from_uint64(hash48), off40); } // erase a old transaction's information void indexer::erase_tx(uint64_t id56, uint64_t hash48, int64_t offset40) { auto off40 = bits40::from_int64(offset40); tx_id2pos_map.erase(id56>>40, bits40::from_uint64(id56)); tx_hash2pos_map.erase(hash48>>32, bits32::from_uint64(hash48), off40); } // given a transaction's 56-bit id, return its offset int64_t indexer::offset_by_tx_id(uint64_t id56) { bool ok; auto off = tx_id2pos_map.get(id56>>40, bits40::from_uint64(id56), &ok); if(!ok) return -1; return off.to_int64(); } // given a range of transactions' 56-bit start_id and end_id, return their offsets i64_list indexer::offsets_by_tx_id_range(uint64_t start_id56, uint64_t end_id56) { auto i64_vec = new std::vector<int64_t>; auto end_key = bits40::from_uint64(end_id56).to_int64(); for(auto iter = tx_id2pos_map.get_iterator(start_id56>>40, bits40::from_uint64(start_id56)); iter.valid(); iter.next()) { if(iter.curr_idx() > int(end_id56>>40) || (iter.curr_idx() == int(end_id56>>40) && iter.key().to_int64() >= end_key)) { break; } i64_vec->push_back(iter.value().to_int64()); } return vec_to_i64_list(i64_vec); } // given a transaction's hash48, return its offset i64_list indexer::offsets_by_tx_hash(uint64_t hash48) { auto vec = tx_hash2pos_map.get(hash48>>32, bits32::from_uint64(hash48)); if(vec.size() == 0) { return i64_list{.vec_ptr=0, .data=nullptr, .size=0}; } else if(vec.size() == 1) { return i64_list{.vec_ptr=size_t(vec[0].to_uint64()), .data=nullptr, .size=1}; } auto i64_vec = new std::vector<int64_t>; for(int i = 0; i < int(vec.size()); i++) { i64_vec->push_back(vec[i].to_int64()); } return i64_list{.vec_ptr=(size_t)i64_vec, .data=i64_vec->data(), .size=i64_vec->size()}; } // given a log_map m, add new information into it void indexer::add_to_log_map(log_map& m, uint64_t hash48, uint32_t height, uint32_t* index_ptr, int index_count) { uint64_t magic_u64; assert(index_count>=0); if(index_count <= 3) { // store the indexes as an in-place integer magic_u64 = compact_index_list(index_ptr, index_count); //std::cout<<" magic_u64 compact_index_list "<<std::hex<<magic_u64<<std::endl; } else { // store the indexes in a bits24_vec shared by all the logs in a block auto vec = get_vec_at_height(height, true); assert(vec != nullptr); magic_u64 = vec->size(); //pointing to the start of the new members magic_u64 = (magic_u64<<20) | index_count; //embed the count into low 20 bits magic_u64 |= uint64_t(7)<<61; // the highest three bits are all set to 1 //std::cout<<" magic_u64 vec->size() "<<vec->size()<<" index_count "<<index_count<<" magic_u64 "<<magic_u64<<std::endl; for(int i=0; i<index_count; i++) { // add members for indexes vec->push_back(bits24::from_uint32(index_ptr[i])); } } m.set(hash48>>32, (hash48<<32)|uint64_t(height), magic_u64); } // the iterators in vector are all valid bool iters_all_valid(std::vector<indexer::tx_iterator>& iters) { assert(iters.size() != 0); for(int i=0; i < int(iters.size()); i++) { if(!iters[i].valid()) return false; } return true; } // *max_value will be the maximum one of the values pointing to by the iterators // returns true if all the iterators in vector are all pointing to this maximum value // note: the iterators must be all valid bool iters_value_all_equal_max_value(std::vector<indexer::tx_iterator>& iters, uint64_t *max_value) { assert(iters.size() != 0); *max_value = iters[0].value(); bool all_equal = true; for(int i=1; i < int(iters.size()); i++) { if(iters[i].value() != *max_value) { all_equal = false; } if(iters[i].value() > *max_value) { *max_value = iters[i].value(); } } return all_equal; } // given query condition 'q', query a list of offsets for transactions i64_list indexer::query_tx_offsets(const tx_offsets_query& q) { std::vector<indexer::tx_iterator> iters; if(q.addr_hash>>48 == 0) {// only consider valid hash iters.push_back(addr_iterator(q.addr_hash, q.start_height, q.end_height)); } for(int i=0; i<q.topic_count; i++) { iters.push_back(topic_iterator(q.topic_hash[i], q.start_height, q.end_height)); } if(iters.size() == 0) { return i64_list{.vec_ptr=0, .data=nullptr, .size=0}; } auto i64_vec = new std::vector<int64_t>; for(int count = 0; iters_all_valid(iters) && count < max_offset_count; count++) { uint64_t max_value; bool all_equal = iters_value_all_equal_max_value(iters, &max_value); if(all_equal) { // found a matching tx i64_vec->push_back(offset_by_tx_id(iters[0].value())); for(int i=0; i < int(iters.size()); i++) { iters[i].next(); } } else { for(int i=0; i < int(iters.size()); i++) { iters[i].next_till_value(max_value); } } } return vec_to_i64_list(i64_vec); } // ============================================================================= size_t indexer_create() { return (size_t)(new indexer); } void indexer_destroy(size_t ptr) { delete (indexer*)ptr; } void indexer_set_max_offset_count(size_t ptr, int c) { ((indexer*)ptr)->set_max_offset_count(c); } void indexer_add_block(size_t ptr, uint32_t height, uint64_t hash48, int64_t offset40) { ((indexer*)ptr)->add_block(height, hash48, offset40); } void indexer_erase_block(size_t ptr, uint32_t height, uint64_t hash48) { ((indexer*)ptr)->erase_block(height, hash48); } int64_t indexer_offset_by_block_height(size_t ptr, uint32_t height) { return ((indexer*)ptr)->offset_by_block_height(height); } i64_list indexer_offsets_by_block_hash(size_t ptr, uint64_t hash48) { return ((indexer*)ptr)->offsets_by_block_hash(hash48); } void indexer_add_tx(size_t ptr, uint64_t id56, uint64_t hash48, int64_t offset40) { ((indexer*)ptr)->add_tx(id56, hash48, offset40); } void indexer_erase_tx(size_t ptr, uint64_t id56, uint64_t hash48, int64_t offset40) { ((indexer*)ptr)->erase_tx(id56, hash48, offset40); } int64_t indexer_offset_by_tx_id(size_t ptr, uint64_t id56) { return ((indexer*)ptr)->offset_by_tx_id(id56); } i64_list indexer_offsets_by_tx_id_range(size_t ptr, uint64_t start_id56, uint64_t end_id56) { return ((indexer*)ptr)->offsets_by_tx_id_range(start_id56, end_id56); } i64_list indexer_offsets_by_tx_hash(size_t ptr, uint64_t hash48) { return ((indexer*)ptr)->offsets_by_tx_hash(hash48); } void indexer_add_src2tx(size_t ptr, uint64_t hash48, uint32_t height, uint32_t* index_ptr, int index_count) { ((indexer*)ptr)->add_src2tx(hash48, height, index_ptr, index_count); } void indexer_erase_src2tx(size_t ptr, uint64_t hash48, uint32_t height) { ((indexer*)ptr)->erase_src2tx(hash48, height); } void indexer_add_dst2tx(size_t ptr, uint64_t hash48, uint32_t height, uint32_t* index_ptr, int index_count) { ((indexer*)ptr)->add_dst2tx(hash48, height, index_ptr, index_count); } void indexer_erase_dst2tx(size_t ptr, uint64_t hash48, uint32_t height) { ((indexer*)ptr)->erase_dst2tx(hash48, height); } void indexer_add_addr2tx(size_t ptr, uint64_t hash48, uint32_t height, uint32_t* index_ptr, int index_count) { ((indexer*)ptr)->add_addr2tx(hash48, height, index_ptr, index_count); } void indexer_erase_addr2tx(size_t ptr, uint64_t hash48, uint32_t height) { ((indexer*)ptr)->erase_addr2tx(hash48, height); } void indexer_add_topic2tx(size_t ptr, uint64_t hash48, uint32_t height, uint32_t* index_ptr, int index_count) { ((indexer*)ptr)->add_topic2tx(hash48, height, index_ptr, index_count); } void indexer_erase_topic2tx(size_t ptr, uint64_t hash48, uint32_t height) { ((indexer*)ptr)->erase_topic2tx(hash48, height); } i64_list indexer_query_tx_offsets(size_t ptr, tx_offsets_query q) { return ((indexer*)ptr)->query_tx_offsets(q); } i64_list indexer_query_tx_offsets_by_src(size_t ptr, uint64_t hash48, uint32_t start_height, uint32_t end_height) { return ((indexer*)ptr)->query_tx_offsets_by_src(hash48, start_height, end_height); } i64_list indexer_query_tx_offsets_by_dst(size_t ptr, uint64_t hash48, uint32_t start_height, uint32_t end_height) { return ((indexer*)ptr)->query_tx_offsets_by_dst(hash48, start_height, end_height); } void i64_list_destroy(i64_list l) { if(l.size>=2) { delete (std::vector<int64_t>*)l.vec_ptr; } } size_t get(const i64_list& l, int i) { if(l.size==0) { return ~size_t(0); } else if(l.size==1) { return l.vec_ptr; } auto ptr = (std::vector<int64_t>*)l.vec_ptr; return ptr->at(i); }
20,867
9,319
#pragma once #include <iosfwd> #include <limits> #include "tatum/Time.hpp" #include "tatum/TimingGraphFwd.hpp" namespace tatum { enum class TagType : unsigned char { CLOCK_LAUNCH, CLOCK_CAPTURE, DATA_ARRIVAL, DATA_REQUIRED, SLACK, UNKOWN }; class TimingTag; std::ostream& operator<<(std::ostream& os, TagType type); bool is_const_gen_tag(const TimingTag& tag); /** * The 'TimingTag' class represents an individual timing tag: the information associated * with a node's arrival/required times. * * * This primarily includes the actual arrival and required time, but also * auxillary metadata such as the clock domain, and launching node. * * The clock domain in particular is used to tag arrival/required times from different * clock domains at a single node. This enables us to perform only a single graph traversal * and still analyze mulitple clocks. * * NOTE: Timing analyzers usually operate on the collection of tags at a particular node. * This is modelled by the separate 'TimingTags' class. */ class TimingTag { public: //Static //Returns a tag suitable for use at a constant generator, during //setup analysis. // ///In particular it's domains are left invalid (i.e. wildcards), //and it's arrival time set to -inf (so it will be maxed out by //any non-constant tag) static TimingTag CONST_GEN_TAG_SETUP() { return TimingTag(Time(-std::numeric_limits<float>::infinity()), DomainId::INVALID(), DomainId::INVALID(), NodeId::INVALID(), TagType::DATA_ARRIVAL); } //Returns a tag suitable for use at a constant generator, during //hold analysis. // ///In particular it's domains are left invalid (i.e. wildcards), //and it's arrival time set to +inf (so it will be minned out by //any non-constant tag) static TimingTag CONST_GEN_TAG_HOLD() { return TimingTag(Time(+std::numeric_limits<float>::infinity()), DomainId::INVALID(), DomainId::INVALID(), NodeId::INVALID(), TagType::DATA_ARRIVAL); } public: //Constructors TimingTag(); ///\param arr_time_val The tagged arrival time ///\param req_time_val The tagged required time ///\param launch_domain The clock domain the tag was launched from ///\param capture_domain The clock domain the tag was captured on ///\param node The origin node's id (e.g. source/sink that originally launched/required this tag) TimingTag(const Time& time_val, DomainId launch_domain, DomainId capture_domain, NodeId node, TagType type); ///\param arr_time_val The tagged arrival time ///\param req_time_val The tagged required time ///\param base_tag The tag from which to copy auxilary meta-data (e.g. domain, launch node) TimingTag(const Time& time_val, NodeId origin, const TimingTag& base_tag); public: //Accessors ///\returns This tag's arrival time const Time& time() const { return time_; } ///\returns This tag's launching clock domain DomainId launch_clock_domain() const { return launch_clock_domain_; } DomainId capture_clock_domain() const { return capture_clock_domain_; } ///\returns This tag's launching node's id NodeId origin_node() const { return origin_node_; } TagType type() const { return type_; } public: //Utility friend bool operator==(const TimingTag& lhs, const TimingTag& rhs); friend bool operator!=(const TimingTag& lhs, const TimingTag& rhs); public: //Mutators ///\param new_time The new value set as the tag's time void set_time(const Time& new_time) { time_ = new_time; } ///\param new_clock_domain The new value set as the tag's source clock domain void set_launch_clock_domain(const DomainId new_clock_domain) { launch_clock_domain_ = new_clock_domain; } ///\param new_clock_domain The new value set as the tag's capture clock domain void set_capture_clock_domain(const DomainId new_clock_domain) { capture_clock_domain_ = new_clock_domain; } ///\param new_launch_node The new value set as the tag's launching node void set_origin_node(const NodeId new_origin_node) { origin_node_ = new_origin_node; } void set_type(const TagType new_type) { type_ = new_type; } /* * Modification operations * For the following the passed in time is maxed/minned with the * respective arr/req time. If the value of this tag is updated * the meta-data (domain, launch node etc) are copied from the * base tag */ ///Updates the tag's arrival time if new_arr_time is larger than the current arrival time. ///If the arrival time is updated, meta-data is also updated from base_tag ///\param new_arr_time The arrival time to compare against ///\param base_tag The tag from which meta-data is copied ///\returns true if the tag is modified, false otherwise bool max(const Time& new_time, const NodeId origin, const TimingTag& base_tag); ///Updates the tag's arrival time if new_arr_time is smaller than the current arrival time. ///If the arrival time is updated, meta-data is also updated from base_tag ///\param new_arr_time The arrival time to compare against ///\param base_tag The tag from which meta-data is copied ///\returns true if the tag is modified, false otherwise bool min(const Time& new_time, const NodeId origin, const TimingTag& base_tag); private: bool update(const Time& new_time, const NodeId origin, const TimingTag& base_tag); /* * Data */ Time time_; //Required time NodeId origin_node_; //Node which launched this arr/req time DomainId launch_clock_domain_; //Clock domain for arr/req times DomainId capture_clock_domain_; //Clock domain for arr/req times TagType type_; }; //For comparing the values of two timing tags struct TimingTagValueComp { bool operator()(const tatum::TimingTag& lhs, const tatum::TimingTag& rhs) { return lhs.time().value() < rhs.time().value(); } }; } //namepsace //Implementation #include "TimingTag.inl"
6,579
1,820
#pragma once #include <cstdint> #include <string> #include <unordered_map> namespace mppi::optimization { enum class MotionModel : uint8_t { Omni, DiffDrive, Carlike }; inline bool isHolonomic(MotionModel motion_model) { return (motion_model == MotionModel::Omni) ? true : false; } const inline std::unordered_map<std::string, MotionModel> MOTION_MODEL_NAMES_MAP = { {"diff", MotionModel::DiffDrive}, {"carlike", MotionModel::Carlike}, {"omni", MotionModel::Omni}}; } // namespace mppi::optimization
510
181
// MIT License // // Copyright (c) 2020 Jean-Louis Haywood // // 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 #include "application/scene/scene.hpp" #include "system.hpp" namespace Omnia { /* Processes Components related to time and classical mechanics physics simulations. */ class PhysicsSystem : public System { public: ~PhysicsSystem(); void setMsPerComputeUpdate(uint32_t msPerComputeUpdate); virtual void initialize() override; void process(std::shared_ptr<Scene> scene) override; virtual void deinitialize() override; void onComputeEnd(std::shared_ptr<Scene> scene); private: float secondsPerComputeUpdate = 0.008; void updateTimers(std::shared_ptr<SceneTree> scene); void displace(std::shared_ptr<SceneTree> scene); void gravitate(std::shared_ptr<SceneTree> scene); void decelerate(std::shared_ptr<SceneTree> scene); void applyForces(std::shared_ptr<SceneTree> scene); void detectCollisions(std::shared_ptr<SceneTree> scene); void handleCollisions(std::shared_ptr<SceneTree> scene); void displaceEntityTree(std::shared_ptr<SceneTree> sceneTree, EntityID entityID, glm::vec3 value); }; }
2,178
715
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/ref_counted.h" #include "base/memory/scoped_ptr.h" #include "base/test/simple_test_tick_clock.h" #include "base/time/tick_clock.h" #include "media/cast/cast_environment.h" #include "media/cast/logging/encoding_event_subscriber.h" #include "media/cast/logging/logging_defines.h" #include "media/cast/test/fake_single_thread_task_runner.h" #include "testing/gtest/include/gtest/gtest.h" using media::cast::proto::AggregatedFrameEvent; using media::cast::proto::AggregatedPacketEvent; using media::cast::proto::BasePacketEvent; namespace media { namespace cast { class EncodingEventSubscriberTest : public ::testing::Test { protected: EncodingEventSubscriberTest() : testing_clock_(new base::SimpleTestTickClock()), task_runner_(new test::FakeSingleThreadTaskRunner(testing_clock_)), cast_environment_(new CastEnvironment( scoped_ptr<base::TickClock>(testing_clock_).Pass(), task_runner_, task_runner_, task_runner_, task_runner_, task_runner_, task_runner_, GetLoggingConfigWithRawEventsAndStatsEnabled())) {} void Init(EventMediaType event_media_type) { DCHECK(!event_subscriber_); event_subscriber_.reset(new EncodingEventSubscriber(event_media_type, 10)); cast_environment_->Logging()->AddRawEventSubscriber( event_subscriber_.get()); } virtual ~EncodingEventSubscriberTest() { if (event_subscriber_) { cast_environment_->Logging()->RemoveRawEventSubscriber( event_subscriber_.get()); } } base::SimpleTestTickClock* testing_clock_; // Owned by CastEnvironment. scoped_refptr<test::FakeSingleThreadTaskRunner> task_runner_; scoped_refptr<CastEnvironment> cast_environment_; scoped_ptr<EncodingEventSubscriber> event_subscriber_; }; TEST_F(EncodingEventSubscriberTest, FrameEventTruncating) { Init(VIDEO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); // Entry with RTP timestamp 0 should get dropped. for (int i = 0; i < 11; i++) { cast_environment_->Logging()->InsertFrameEvent(now, kVideoFrameCaptured, i * 100, /*frame_id*/ 0); cast_environment_->Logging()->InsertFrameEvent(now, kVideoFrameDecoded, i * 100, /*frame_id*/ 0); } FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); ASSERT_EQ(10u, frame_events.size()); EXPECT_EQ(100u, frame_events.begin()->first); EXPECT_EQ(1000u, frame_events.rbegin()->first); } TEST_F(EncodingEventSubscriberTest, PacketEventTruncating) { Init(AUDIO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); // Entry with RTP timestamp 0 should get dropped. for (int i = 0; i < 11; i++) { cast_environment_->Logging()->InsertPacketEvent(now, kAudioPacketReceived, /*rtp_timestamp*/ i * 100, /*frame_id*/ 0, /*packet_id*/ i, /*max_packet_id*/ 10, /*size*/ 123); } PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); ASSERT_EQ(10u, packet_events.size()); EXPECT_EQ(100u, packet_events.begin()->first); EXPECT_EQ(1000u, packet_events.rbegin()->first); } TEST_F(EncodingEventSubscriberTest, EventFiltering) { Init(VIDEO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; cast_environment_->Logging()->InsertFrameEvent(now, kVideoFrameDecoded, rtp_timestamp, /*frame_id*/ 0); // This is an AUDIO_EVENT and shouldn't be processed by the subscriber. cast_environment_->Logging()->InsertFrameEvent(now, kAudioFrameDecoded, rtp_timestamp, /*frame_id*/ 0); FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); FrameEventMap::iterator frame_it = frame_events.find(rtp_timestamp); ASSERT_TRUE(frame_it != frame_events.end()); linked_ptr<AggregatedFrameEvent> frame_event = frame_it->second; ASSERT_EQ(1, frame_event->event_type_size()); EXPECT_EQ(media::cast::proto::VIDEO_FRAME_DECODED, frame_event->event_type(0)); PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); EXPECT_TRUE(packet_events.empty()); } TEST_F(EncodingEventSubscriberTest, FrameEvent) { Init(VIDEO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; cast_environment_->Logging()->InsertFrameEvent(now, kVideoFrameDecoded, rtp_timestamp, /*frame_id*/ 0); FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); ASSERT_EQ(1u, frame_events.size()); FrameEventMap::iterator it = frame_events.find(rtp_timestamp); ASSERT_TRUE(it != frame_events.end()); linked_ptr<AggregatedFrameEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(1, event->event_type_size()); EXPECT_EQ(media::cast::proto::VIDEO_FRAME_DECODED, event->event_type(0)); ASSERT_EQ(1, event->event_timestamp_micros_size()); EXPECT_EQ(now.ToInternalValue(), event->event_timestamp_micros(0)); EXPECT_EQ(0, event->encoded_frame_size()); EXPECT_EQ(0, event->delay_millis()); event_subscriber_->GetFrameEventsAndReset(&frame_events); EXPECT_TRUE(frame_events.empty()); } TEST_F(EncodingEventSubscriberTest, FrameEventDelay) { Init(AUDIO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; int delay_ms = 100; cast_environment_->Logging()->InsertFrameEventWithDelay( now, kAudioPlayoutDelay, rtp_timestamp, /*frame_id*/ 0, base::TimeDelta::FromMilliseconds(delay_ms)); FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); ASSERT_EQ(1u, frame_events.size()); FrameEventMap::iterator it = frame_events.find(rtp_timestamp); ASSERT_TRUE(it != frame_events.end()); linked_ptr<AggregatedFrameEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(1, event->event_type_size()); EXPECT_EQ(media::cast::proto::AUDIO_PLAYOUT_DELAY, event->event_type(0)); ASSERT_EQ(1, event->event_timestamp_micros_size()); EXPECT_EQ(now.ToInternalValue(), event->event_timestamp_micros(0)); EXPECT_EQ(0, event->encoded_frame_size()); EXPECT_EQ(100, event->delay_millis()); } TEST_F(EncodingEventSubscriberTest, FrameEventSize) { Init(VIDEO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; int size = 123; cast_environment_->Logging()->InsertFrameEventWithSize( now, kVideoFrameEncoded, rtp_timestamp, /*frame_id*/ 0, size); FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); ASSERT_EQ(1u, frame_events.size()); FrameEventMap::iterator it = frame_events.find(rtp_timestamp); ASSERT_TRUE(it != frame_events.end()); linked_ptr<AggregatedFrameEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(1, event->event_type_size()); EXPECT_EQ(media::cast::proto::VIDEO_FRAME_ENCODED, event->event_type(0)); ASSERT_EQ(1, event->event_timestamp_micros_size()); EXPECT_EQ(now.ToInternalValue(), event->event_timestamp_micros(0)); EXPECT_EQ(size, event->encoded_frame_size()); EXPECT_EQ(0, event->delay_millis()); } TEST_F(EncodingEventSubscriberTest, MultipleFrameEvents) { Init(AUDIO_EVENT); RtpTimestamp rtp_timestamp1 = 100; RtpTimestamp rtp_timestamp2 = 200; base::TimeTicks now1(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertFrameEventWithDelay( now1, kAudioPlayoutDelay, rtp_timestamp1, /*frame_id*/ 0, /*delay*/ base::TimeDelta::FromMilliseconds(100)); testing_clock_->Advance(base::TimeDelta::FromMilliseconds(20)); base::TimeTicks now2(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertFrameEventWithSize( now2, kAudioFrameEncoded, rtp_timestamp2, /*frame_id*/ 0, /*size*/ 123); testing_clock_->Advance(base::TimeDelta::FromMilliseconds(20)); base::TimeTicks now3(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertFrameEvent( now3, kAudioFrameDecoded, rtp_timestamp1, /*frame_id*/ 0); FrameEventMap frame_events; event_subscriber_->GetFrameEventsAndReset(&frame_events); ASSERT_EQ(2u, frame_events.size()); FrameEventMap::iterator it = frame_events.find(100); ASSERT_TRUE(it != frame_events.end()); linked_ptr<AggregatedFrameEvent> event = it->second; EXPECT_EQ(rtp_timestamp1, event->rtp_timestamp()); ASSERT_EQ(2, event->event_type_size()); EXPECT_EQ(media::cast::proto::AUDIO_PLAYOUT_DELAY, event->event_type(0)); EXPECT_EQ(media::cast::proto::AUDIO_FRAME_DECODED, event->event_type(1)); ASSERT_EQ(2, event->event_timestamp_micros_size()); EXPECT_EQ(now1.ToInternalValue(), event->event_timestamp_micros(0)); EXPECT_EQ(now3.ToInternalValue(), event->event_timestamp_micros(1)); it = frame_events.find(200); ASSERT_TRUE(it != frame_events.end()); event = it->second; EXPECT_EQ(rtp_timestamp2, event->rtp_timestamp()); ASSERT_EQ(1, event->event_type_size()); EXPECT_EQ(media::cast::proto::AUDIO_FRAME_ENCODED, event->event_type(0)); ASSERT_EQ(1, event->event_timestamp_micros_size()); EXPECT_EQ(now2.ToInternalValue(), event->event_timestamp_micros(0)); } TEST_F(EncodingEventSubscriberTest, PacketEvent) { Init(AUDIO_EVENT); base::TimeTicks now(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; int packet_id = 2; int size = 100; cast_environment_->Logging()->InsertPacketEvent( now, kAudioPacketReceived, rtp_timestamp, /*frame_id*/ 0, packet_id, /*max_packet_id*/ 10, size); PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); ASSERT_EQ(1u, packet_events.size()); PacketEventMap::iterator it = packet_events.find(rtp_timestamp); ASSERT_TRUE(it != packet_events.end()); linked_ptr<AggregatedPacketEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(1, event->base_packet_event_size()); const BasePacketEvent& base_event = event->base_packet_event(0); EXPECT_EQ(packet_id, base_event.packet_id()); ASSERT_EQ(1, base_event.event_type_size()); EXPECT_EQ(media::cast::proto::AUDIO_PACKET_RECEIVED, base_event.event_type(0)); ASSERT_EQ(1, base_event.event_timestamp_micros_size()); EXPECT_EQ(now.ToInternalValue(), base_event.event_timestamp_micros(0)); event_subscriber_->GetPacketEventsAndReset(&packet_events); EXPECT_TRUE(packet_events.empty()); } TEST_F(EncodingEventSubscriberTest, MultiplePacketEventsForPacket) { Init(OTHER_EVENT); base::TimeTicks now1(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; int packet_id = 2; int size = 100; cast_environment_->Logging()->InsertPacketEvent( now1, kPacketSentToPacer, rtp_timestamp, /*frame_id*/ 0, packet_id, /*max_packet_id*/ 10, size); testing_clock_->Advance(base::TimeDelta::FromMilliseconds(20)); base::TimeTicks now2(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertPacketEvent( now2, kPacketSentToNetwork, rtp_timestamp, /*frame_id*/ 0, packet_id, /*max_packet_id*/ 10, size); PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); ASSERT_EQ(1u, packet_events.size()); PacketEventMap::iterator it = packet_events.find(rtp_timestamp); ASSERT_TRUE(it != packet_events.end()); linked_ptr<AggregatedPacketEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(1, event->base_packet_event_size()); const BasePacketEvent& base_event = event->base_packet_event(0); EXPECT_EQ(packet_id, base_event.packet_id()); ASSERT_EQ(2, base_event.event_type_size()); EXPECT_EQ(media::cast::proto::PACKET_SENT_TO_PACER, base_event.event_type(0)); EXPECT_EQ(media::cast::proto::PACKET_SENT_TO_NETWORK, base_event.event_type(1)); ASSERT_EQ(2, base_event.event_timestamp_micros_size()); EXPECT_EQ(now1.ToInternalValue(), base_event.event_timestamp_micros(0)); EXPECT_EQ(now2.ToInternalValue(), base_event.event_timestamp_micros(1)); } TEST_F(EncodingEventSubscriberTest, MultiplePacketEventsForFrame) { Init(OTHER_EVENT); base::TimeTicks now1(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp = 100; int packet_id_1 = 2; int packet_id_2 = 3; int size = 100; cast_environment_->Logging()->InsertPacketEvent( now1, kPacketSentToPacer, rtp_timestamp, /*frame_id*/ 0, packet_id_1, /*max_packet_id*/ 10, size); testing_clock_->Advance(base::TimeDelta::FromMilliseconds(20)); base::TimeTicks now2(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertPacketEvent( now2, kPacketRetransmitted, rtp_timestamp, /*frame_id*/ 0, packet_id_2, /*max_packet_id*/ 10, size); PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); ASSERT_EQ(1u, packet_events.size()); PacketEventMap::iterator it = packet_events.find(rtp_timestamp); ASSERT_TRUE(it != packet_events.end()); linked_ptr<AggregatedPacketEvent> event = it->second; EXPECT_EQ(rtp_timestamp, event->rtp_timestamp()); ASSERT_EQ(2, event->base_packet_event_size()); const BasePacketEvent& base_event = event->base_packet_event(0); EXPECT_EQ(packet_id_1, base_event.packet_id()); ASSERT_EQ(1, base_event.event_type_size()); EXPECT_EQ(media::cast::proto::PACKET_SENT_TO_PACER, base_event.event_type(0)); ASSERT_EQ(1, base_event.event_timestamp_micros_size()); EXPECT_EQ(now1.ToInternalValue(), base_event.event_timestamp_micros(0)); const BasePacketEvent& base_event_2 = event->base_packet_event(1); EXPECT_EQ(packet_id_2, base_event_2.packet_id()); ASSERT_EQ(1, base_event_2.event_type_size()); EXPECT_EQ(media::cast::proto::PACKET_RETRANSMITTED, base_event_2.event_type(0)); ASSERT_EQ(1, base_event_2.event_timestamp_micros_size()); EXPECT_EQ(now2.ToInternalValue(), base_event_2.event_timestamp_micros(0)); } TEST_F(EncodingEventSubscriberTest, MultiplePacketEvents) { Init(OTHER_EVENT); base::TimeTicks now1(testing_clock_->NowTicks()); RtpTimestamp rtp_timestamp_1 = 100; RtpTimestamp rtp_timestamp_2 = 200; int packet_id_1 = 2; int packet_id_2 = 3; int size = 100; cast_environment_->Logging()->InsertPacketEvent( now1, kPacketSentToPacer, rtp_timestamp_1, /*frame_id*/ 0, packet_id_1, /*max_packet_id*/ 10, size); testing_clock_->Advance(base::TimeDelta::FromMilliseconds(20)); base::TimeTicks now2(testing_clock_->NowTicks()); cast_environment_->Logging()->InsertPacketEvent( now2, kPacketRetransmitted, rtp_timestamp_2, /*frame_id*/ 0, packet_id_2, /*max_packet_id*/ 10, size); PacketEventMap packet_events; event_subscriber_->GetPacketEventsAndReset(&packet_events); ASSERT_EQ(2u, packet_events.size()); PacketEventMap::iterator it = packet_events.find(rtp_timestamp_1); ASSERT_TRUE(it != packet_events.end()); linked_ptr<AggregatedPacketEvent> event = it->second; EXPECT_EQ(rtp_timestamp_1, event->rtp_timestamp()); ASSERT_EQ(1, event->base_packet_event_size()); const BasePacketEvent& base_event = event->base_packet_event(0); EXPECT_EQ(packet_id_1, base_event.packet_id()); ASSERT_EQ(1, base_event.event_type_size()); EXPECT_EQ(media::cast::proto::PACKET_SENT_TO_PACER, base_event.event_type(0)); ASSERT_EQ(1, base_event.event_timestamp_micros_size()); EXPECT_EQ(now1.ToInternalValue(), base_event.event_timestamp_micros(0)); it = packet_events.find(rtp_timestamp_2); ASSERT_TRUE(it != packet_events.end()); event = it->second; EXPECT_EQ(rtp_timestamp_2, event->rtp_timestamp()); ASSERT_EQ(1, event->base_packet_event_size()); const BasePacketEvent& base_event_2 = event->base_packet_event(0); EXPECT_EQ(packet_id_2, base_event_2.packet_id()); ASSERT_EQ(1, base_event_2.event_type_size()); EXPECT_EQ(media::cast::proto::PACKET_RETRANSMITTED, base_event_2.event_type(0)); ASSERT_EQ(1, base_event_2.event_timestamp_micros_size()); EXPECT_EQ(now2.ToInternalValue(), base_event_2.event_timestamp_micros(0)); } } // namespace cast } // namespace media
17,312
6,248
#include <gtest/gtest.h> #include <wfc/utility/math.hpp> TEST(Utilty, IsPowerOfTwo) { ASSERT_TRUE(wfc::is_power_of_two(2)); ASSERT_FALSE(wfc::is_power_of_two(3)); } TEST(Utilty, Log2OfPowerOfTwo) { ASSERT_EQ(wfc::log2_of_power_of_two(2U), 1U); ASSERT_EQ(wfc::log2_of_power_of_two(4U), 2U); ASSERT_EQ(wfc::log2_of_power_of_two(8U), 3U); } #ifndef NDEBUG # define Log2OfPowerOfTwoDeath Log2OfPowerOfTwoDeath #else # define Log2OfPowerOfTwoDeath DISABLED_Log2OfPowerOfTwoDeath #endif TEST(Utility, Log2OfPowerOfTwoDeath) { EXPECT_DEATH(wfc::log2_of_power_of_two(3U), ""); }
581
291
// Copyright 2014 The Crashpad 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 "util/mach/composite_mach_message_server.h" #include <sys/types.h> #include "base/strings/stringprintf.h" #include "gtest/gtest.h" #include "test/gtest_death_check.h" #include "util/mach/mach_message.h" namespace crashpad { namespace test { namespace { TEST(CompositeMachMessageServer, Empty) { CompositeMachMessageServer server; EXPECT_TRUE(server.MachMessageServerRequestIDs().empty()); mach_msg_empty_rcv_t request = {}; EXPECT_EQ(sizeof(request.header), server.MachMessageServerRequestSize()); mig_reply_error_t reply = {}; EXPECT_EQ(sizeof(reply), server.MachMessageServerReplySize()); bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(MIG_BAD_ID, reply.RetCode); } class TestMachMessageHandler : public MachMessageServer::Interface { public: TestMachMessageHandler() : MachMessageServer::Interface(), request_ids_(), request_size_(0), reply_size_(0), return_code_(KERN_FAILURE), return_value_(false), destroy_complex_request_(false) { } ~TestMachMessageHandler() { } void SetReturnCodes(bool return_value, kern_return_t return_code, bool destroy_complex_request) { return_value_ = return_value; return_code_ = return_code; destroy_complex_request_ = destroy_complex_request; } void AddRequestID(mach_msg_id_t request_id) { request_ids_.insert(request_id); } void SetRequestSize(mach_msg_size_t request_size) { request_size_ = request_size; } void SetReplySize(mach_msg_size_t reply_size) { reply_size_ = reply_size; } // MachMessageServer::Interface: bool MachMessageServerFunction(const mach_msg_header_t* in, mach_msg_header_t* out, bool* destroy_complex_request) override { EXPECT_NE(request_ids_.end(), request_ids_.find(in->msgh_id)); *destroy_complex_request = destroy_complex_request_; PrepareMIGReplyFromRequest(in, out); SetMIGReplyError(out, return_code_); return return_value_; } std::set<mach_msg_id_t> MachMessageServerRequestIDs() override { return request_ids_; } mach_msg_size_t MachMessageServerRequestSize() override { return request_size_; } mach_msg_size_t MachMessageServerReplySize() override { return reply_size_; } private: std::set<mach_msg_id_t> request_ids_; mach_msg_size_t request_size_; mach_msg_size_t reply_size_; kern_return_t return_code_; bool return_value_; bool destroy_complex_request_; DISALLOW_COPY_AND_ASSIGN(TestMachMessageHandler); }; TEST(CompositeMachMessageServer, HandlerDoesNotHandle) { TestMachMessageHandler handler; CompositeMachMessageServer server; server.AddHandler(&handler); EXPECT_TRUE(server.MachMessageServerRequestIDs().empty()); mach_msg_empty_rcv_t request = {}; EXPECT_EQ(sizeof(request.header), server.MachMessageServerRequestSize()); mig_reply_error_t reply = {}; EXPECT_EQ(sizeof(reply), server.MachMessageServerReplySize()); bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(MIG_BAD_ID, reply.RetCode); EXPECT_FALSE(destroy_complex_request); } TEST(CompositeMachMessageServer, OneHandler) { const mach_msg_id_t kRequestID = 100; const mach_msg_size_t kRequestSize = 256; const mach_msg_size_t kReplySize = 128; const kern_return_t kReturnCode = KERN_SUCCESS; TestMachMessageHandler handler; handler.AddRequestID(kRequestID); handler.SetRequestSize(kRequestSize); handler.SetReplySize(kReplySize); handler.SetReturnCodes(true, kReturnCode, true); CompositeMachMessageServer server; // The chosen request and reply sizes must be larger than the defaults for // that portion fo the test to be valid. EXPECT_GT(kRequestSize, server.MachMessageServerRequestSize()); EXPECT_GT(kReplySize, server.MachMessageServerReplySize()); server.AddHandler(&handler); std::set<mach_msg_id_t> expect_request_ids; expect_request_ids.insert(kRequestID); EXPECT_EQ(expect_request_ids, server.MachMessageServerRequestIDs()); EXPECT_EQ(kRequestSize, server.MachMessageServerRequestSize()); EXPECT_EQ(kReplySize, server.MachMessageServerReplySize()); mach_msg_empty_rcv_t request = {}; mig_reply_error_t reply = {}; // Send a message with an unknown request ID. request.header.msgh_id = 0; bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(MIG_BAD_ID, reply.RetCode); EXPECT_FALSE(destroy_complex_request); // Send a message with a known request ID. request.header.msgh_id = kRequestID; EXPECT_TRUE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(kReturnCode, reply.RetCode); EXPECT_TRUE(destroy_complex_request); } TEST(CompositeMachMessageServer, ThreeHandlers) { const mach_msg_id_t kRequestIDs0[] = {5}; const kern_return_t kReturnCode0 = KERN_SUCCESS; const mach_msg_id_t kRequestIDs1[] = {4, 7}; const kern_return_t kReturnCode1 = KERN_PROTECTION_FAILURE; const mach_msg_id_t kRequestIDs2[] = {10, 0, 20}; const mach_msg_size_t kRequestSize2 = 6144; const mach_msg_size_t kReplySize2 = 16384; const kern_return_t kReturnCode2 = KERN_NOT_RECEIVER; TestMachMessageHandler handlers[3]; std::set<mach_msg_id_t> expect_request_ids; for (size_t index = 0; index < arraysize(kRequestIDs0); ++index) { const mach_msg_id_t request_id = kRequestIDs0[index]; handlers[0].AddRequestID(request_id); expect_request_ids.insert(request_id); } handlers[0].SetRequestSize(sizeof(mach_msg_header_t)); handlers[0].SetReplySize(sizeof(mig_reply_error_t)); handlers[0].SetReturnCodes(true, kReturnCode0, false); for (size_t index = 0; index < arraysize(kRequestIDs1); ++index) { const mach_msg_id_t request_id = kRequestIDs1[index]; handlers[1].AddRequestID(request_id); expect_request_ids.insert(request_id); } handlers[1].SetRequestSize(100); handlers[1].SetReplySize(200); handlers[1].SetReturnCodes(false, kReturnCode1, true); for (size_t index = 0; index < arraysize(kRequestIDs2); ++index) { const mach_msg_id_t request_id = kRequestIDs2[index]; handlers[2].AddRequestID(request_id); expect_request_ids.insert(request_id); } handlers[2].SetRequestSize(kRequestSize2); handlers[2].SetReplySize(kReplySize2); handlers[2].SetReturnCodes(true, kReturnCode2, true); CompositeMachMessageServer server; // The chosen request and reply sizes must be larger than the defaults for // that portion fo the test to be valid. EXPECT_GT(kRequestSize2, server.MachMessageServerRequestSize()); EXPECT_GT(kReplySize2, server.MachMessageServerReplySize()); server.AddHandler(&handlers[0]); server.AddHandler(&handlers[1]); server.AddHandler(&handlers[2]); EXPECT_EQ(expect_request_ids, server.MachMessageServerRequestIDs()); EXPECT_EQ(kRequestSize2, server.MachMessageServerRequestSize()); EXPECT_EQ(kReplySize2, server.MachMessageServerReplySize()); mach_msg_empty_rcv_t request = {}; mig_reply_error_t reply = {}; // Send a message with an unknown request ID. request.header.msgh_id = 100; bool destroy_complex_request = false; EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(MIG_BAD_ID, reply.RetCode); EXPECT_FALSE(destroy_complex_request); // Send messages with known request IDs. for (size_t index = 0; index < arraysize(kRequestIDs0); ++index) { request.header.msgh_id = kRequestIDs0[index]; SCOPED_TRACE(base::StringPrintf( "handler 0, index %zu, id %d", index, request.header.msgh_id)); EXPECT_TRUE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(kReturnCode0, reply.RetCode); EXPECT_FALSE(destroy_complex_request); } for (size_t index = 0; index < arraysize(kRequestIDs1); ++index) { request.header.msgh_id = kRequestIDs1[index]; SCOPED_TRACE(base::StringPrintf( "handler 1, index %zu, id %d", index, request.header.msgh_id)); EXPECT_FALSE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(kReturnCode1, reply.RetCode); EXPECT_TRUE(destroy_complex_request); } for (size_t index = 0; index < arraysize(kRequestIDs2); ++index) { request.header.msgh_id = kRequestIDs2[index]; SCOPED_TRACE(base::StringPrintf( "handler 2, index %zu, id %d", index, request.header.msgh_id)); EXPECT_TRUE(server.MachMessageServerFunction( &request.header, &reply.Head, &destroy_complex_request)); EXPECT_EQ(kReturnCode2, reply.RetCode); EXPECT_TRUE(destroy_complex_request); } } // CompositeMachMessageServer can’t deal with two handlers that want to handle // the same request ID. TEST(CompositeMachMessageServerDeathTest, DuplicateRequestID) { const mach_msg_id_t kRequestID = 400; TestMachMessageHandler handlers[2]; handlers[0].AddRequestID(kRequestID); handlers[1].AddRequestID(kRequestID); CompositeMachMessageServer server; server.AddHandler(&handlers[0]); EXPECT_DEATH_CHECK(server.AddHandler(&handlers[1]), "duplicate request ID"); } } // namespace } // namespace test } // namespace crashpad
10,216
3,581
// Copyright 2020 The Autoware Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // //    http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// \copyright Copyright 2020 The Autoware Foundation /// \file /// \brief This file defines the lanelet2_map_provider_node class. #ifndef LANELET2_MAP_PROVIDER__LANELET2_MAP_PROVIDER_NODE_HPP_ #define LANELET2_MAP_PROVIDER__LANELET2_MAP_PROVIDER_NODE_HPP_ #include <rclcpp/rclcpp.hpp> #include <lanelet2_map_provider/lanelet2_map_provider.hpp> #include <common/types.hpp> #include <string> #include <memory> #include "autoware_auto_msgs/srv/had_map_service.hpp" #include "autoware_auto_msgs/msg/had_map_bin.hpp" using autoware::common::types::float64_t; using autoware::common::types::bool8_t; namespace autoware { namespace lanelet2_map_provider { /// \class Lanelet2MapProviderNode /// \brief ROS 2 Node for semantic map provider using lanelet2 map format. /// Node loads a lanelet2 OSM format map using the class Lanelet2MapProvider /// and then runs a service for supplying other /// nodes map information according to their requests. Requests are defined by /// a sequences of requested primitives as well as geometric bounds on requested map /// data class LANELET2_MAP_PROVIDER_PUBLIC Lanelet2MapProviderNode : public rclcpp::Node { public: /// \brief default constructor, starts driver /// *breaks docs test - no node_nmae generated by automatic package generator /// -- param[in] node_name name of the node for rclcpp internals /// \throw runtime error if failed to start threads or configure driver explicit Lanelet2MapProviderNode(const rclcpp::NodeOptions & options); /// \brief load_map loads the osm map data while projecting into the coordinate /// system defined by the map origin void load_map(); /// \brief Initialisation of the node Create the map provider object from the given map filename, /// and set up the service call handler for the node void init(); /// \brief Handles the node service requests /// \param request Service request message for map data specifying map content and geom. bounds /// \param response Service repsone to request, containing a sub-set of map data /// but nethertheless containing a complete and valid lanelet2 map void handle_request( std::shared_ptr<autoware_auto_msgs::srv::HADMapService_Request> request, std::shared_ptr<autoware_auto_msgs::srv::HADMapService_Response> response); private: /// If the origin not defined by parameters, get the transform describing /// the map origin (earth->map transform, set by the pcd /// map provider). Geocentric lanelet2 coordinates can then be projected intro the map frame. /// Must be recieved before the node can call the map provider constructor, and start the /// service handler void get_map_origin(); float64_t m_origin_lat; /// map orgin in latitude, longitude and elevatopm float64_t m_origin_lon; float64_t m_origin_ele; bool8_t m_origin_set; bool8_t m_verbose; ///< whether to use verbose output or not. std::string m_map_filename; std::unique_ptr<Lanelet2MapProvider> m_map_provider; rclcpp::Service<autoware_auto_msgs::srv::HADMapService>::SharedPtr m_map_service; geometry_msgs::msg::TransformStamped m_earth_to_map; /// map origin in ECEF ENU transform }; } // namespace lanelet2_map_provider } // namespace autoware #endif // LANELET2_MAP_PROVIDER__LANELET2_MAP_PROVIDER_NODE_HPP_
3,888
1,230
#include <psychlops.h> using namespace Psychlops; double estimated_gamma = 0; double gamma_step = 8.0; var estimate_gamma = function(colorlevel) { estimated_gamma = 0; gamma_step = 8.0; while (0.0001<gamma_step) { while (0<pow(colorlevel, estimated_gamma) - 0.5) { estimated_gamma += gamma_step; } estimated_gamma -= gamma_step; gamma_step /= 2.0; } estimated_gamma += gamma_step; return estimated_gamma; }; void psychlops_main() { //// 1 Declaration // declare default window and variables for its parameters double CANVAS_FRAMENUM; int CANVAS_REFRESHRATE; Canvas cnvs(Canvas::fullscreen); Widgets::Theme::setLightTheme(); Interval rng; double Gr, Gb, Gg; double measured_r = 0.5, measured_g = 0.5, measured_b = 0.5; Widgets::Dial dial_r, dial_g, dial_b; dial_r.set(200, 60).centering().shift(-300, 200); dial_g.set(200, 60).centering().shift(0, 200); dial_b.set(200, 60).centering().shift(300, 200); dial_r.link(measured_r, "Red", 0 <= rng < 0.99, 1.0 / 8, 0.5); dial_g.link(measured_g, "Green", 0 <= rng < 0.99, 1.0 / 8, 0.5); dial_b.link(measured_b, "Blue", 0 <= rng < 0.99, 1.0 / 8, 0.5); Widgets::Button endbutton, switchbutton; endbutton.set(L"キャンセル", 48); endbutton.centering().shift(cnvs.getWidth()*0.4, cnvs.getHeight()*0.4); switchbutton.set(L" 次へ ", 48); switchbutton.centering(cnvs.getHcenter(), dial_g.getBottom() + 200); //// 2 Initialization // Set initial values for local variables CANVAS_REFRESHRATE = cnvs.getRefreshRate(); CANVAS_FRAMENUM = 0; //// 3 Drawing Psychlops::Rectangle center_rect(100, 100); Image grads[3]; Color grads_color[3]; grads_color[0] = Color(1, 0, 0); grads_color[1] = Color(0, 1, 0); grads_color[2] = Color(0, 0, 1); for (int i = 0; i < 3; i++) { grads[i].set(200, 200); for (int y = 0; y < 200; y++) { for (int x = 0; x < 200; x++) { grads[i].pix(x, y, y % 2 == 0 ? grads_color[i] : Color::black); } } grads[i].cache(); grads[i].centering().shift(-300 + i * 300, 0); } int endflag = 0; Mouse::show(); Psychlops::Letters instruction1(L"それぞれの図形の下のスライダーを調整し、"); Psychlops::Letters instruction2(L"中心の四角とその周りの明るさをできるだけ近づけてください。"); instruction1.centering().shift(0, -300); instruction2.centering().shift(0, -300 + Psychlops.Font.default_font.size * 1.1); Figures::ShaderGabor gbr; gbr.setSigma(200); gbr.centering(); bool calibrating = true; int frames = 0; Psychlops::Color::setGammaValue(1.0, 1.0, 1.0); // [begin loop] while (endflag < 1) { frames++; if (calibrating) { cnvs.clear(); dial_r.draw(); dial_g.draw(); dial_b.draw(); if (dial_r.changed()) { Gr = estimate_gamma(measured_r); } if (dial_g.changed()) { Gg = estimate_gamma(measured_g); } if (dial_b.changed()) { Gb = estimate_gamma(measured_b); } if (endflag == 0) { for (int i = 0; i < 3; i++) { grads[i].shift(0, (frames % 2) * 2 - 1).draw(); } } else if (endflag == 1) { for (int i = 0; i < 3; i++) { grads[i].draw(); } } center_rect.centering().shift(-300 + 0 * 300, 0); center_rect.draw(Color(measured_r, 0.0, 0.0)); center_rect.centering().shift(-300 + 1 * 300, 0); center_rect.draw(Color(0.0, measured_g, 0.0)); center_rect.centering().shift(-300 + 2 * 300, 0); center_rect.draw(Color(0.0, 0.0, measured_b)); instruction1.draw(Color::white); instruction2.draw(Color::white); endbutton.draw(); if (endbutton.pushed()) { endflag = 4; } switchbutton.draw(); if (switchbutton.pushed()) { endflag += 1; calibrating = false; frames = 0; measured_r = 0.5; measured_g = 0.5; measured_b = 0.5; } } else { cnvs.clear(); if (frames > 30) { calibrating = true; frames = 0; } } cnvs.flip(); CANVAS_FRAMENUM++; } // [end loop] AppInfo::localSettings["GammaR"] = Gr; AppInfo::localSettings["GammaG"] = Gg; AppInfo::localSettings["GammaB"] = Gb; AppInfo::saveLocalSettings(); //alert("Estimated Gamma:\r\nR: "+Gr+"\r\nG: "+Gg+"\r\nB:"+Gb); }
4,118
2,036
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// #pragma warning (disable:4127) #include <winsock2.h> #include <ws2tcpip.h> #pragma warning (default:4127) #include "iphelpers.h" #include "basetypes.h" #include <assert.h> #include "utllinkedlist.h" #include "utlvector.h" #include "tier1/strtools.h" // This automatically calls WSAStartup for the app at startup. class CIPStarter { public: CIPStarter() { WSADATA wsaData; WSAStartup( WINSOCK_VERSION, &wsaData ); } }; static CIPStarter g_Starter; unsigned long SampleMilliseconds() { CCycleCount cnt; cnt.Sample(); return cnt.GetMilliseconds(); } // ------------------------------------------------------------------------------------------ // // CChunkWalker. // ------------------------------------------------------------------------------------------ // CChunkWalker::CChunkWalker( void const * const *pChunks, const int *pChunkLengths, int nChunks ) { m_TotalLength = 0; for ( int i=0; i < nChunks; i++ ) m_TotalLength += pChunkLengths[i]; m_iCurChunk = 0; m_iCurChunkPos = 0; m_pChunks = pChunks; m_pChunkLengths = pChunkLengths; m_nChunks = nChunks; } int CChunkWalker::GetTotalLength() const { return m_TotalLength; } void CChunkWalker::CopyTo( void *pOut, int nBytes ) { unsigned char *pOutPos = (unsigned char*)pOut; int nBytesLeft = nBytes; while ( nBytesLeft > 0 ) { int toCopy = nBytesLeft; int curChunkLen = m_pChunkLengths[m_iCurChunk]; int amtLeft = curChunkLen - m_iCurChunkPos; if ( nBytesLeft > amtLeft ) { toCopy = amtLeft; } unsigned char *pCurChunkData = (unsigned char*)m_pChunks[m_iCurChunk]; memcpy( pOutPos, &pCurChunkData[m_iCurChunkPos], toCopy ); nBytesLeft -= toCopy; pOutPos += toCopy; // Slide up to the next chunk if we're done with the one we're on. m_iCurChunkPos += toCopy; assert( m_iCurChunkPos <= curChunkLen ); if ( m_iCurChunkPos == curChunkLen ) { ++m_iCurChunk; m_iCurChunkPos = 0; if ( m_iCurChunk == m_nChunks ) { assert( nBytesLeft == 0 ); } } } } // ------------------------------------------------------------------------------------------ // // CWaitTimer // ------------------------------------------------------------------------------------------ // bool g_bForceWaitTimers = false; CWaitTimer::CWaitTimer( double flSeconds ) { m_StartTime = SampleMilliseconds(); m_WaitMS = (unsigned long)( flSeconds * 1000.0 ); } bool CWaitTimer::ShouldKeepWaiting() { if ( m_WaitMS == 0 ) { return false; } else { return ( SampleMilliseconds() - m_StartTime ) <= m_WaitMS || g_bForceWaitTimers; } } // ------------------------------------------------------------------------------------------ // // CIPAddr. // ------------------------------------------------------------------------------------------ // CIPAddr::CIPAddr() { Init( 0, 0, 0, 0, 0 ); } CIPAddr::CIPAddr( const int inputIP[4], const int inputPort ) { Init( inputIP[0], inputIP[1], inputIP[2], inputIP[3], inputPort ); } CIPAddr::CIPAddr( int ip0, int ip1, int ip2, int ip3, int ipPort ) { Init( ip0, ip1, ip2, ip3, ipPort ); } void CIPAddr::Init( int ip0, int ip1, int ip2, int ip3, int ipPort ) { ip[0] = (unsigned char)ip0; ip[1] = (unsigned char)ip1; ip[2] = (unsigned char)ip2; ip[3] = (unsigned char)ip3; port = (unsigned short)ipPort; } bool CIPAddr::operator==( const CIPAddr &o ) const { return ip[0] == o.ip[0] && ip[1] == o.ip[1] && ip[2] == o.ip[2] && ip[3] == o.ip[3] && port == o.port; } bool CIPAddr::operator!=( const CIPAddr &o ) const { return !( *this == o ); } void CIPAddr::SetupLocal( int inPort ) { ip[0] = 0x7f; ip[1] = 0; ip[2] = 0; ip[3] = 1; port = inPort; } // ------------------------------------------------------------------------------------------ // // Static helpers. // ------------------------------------------------------------------------------------------ // static double IP_FloatTime() { CCycleCount cnt; cnt.Sample(); return cnt.GetSeconds(); } TIMEVAL SetupTimeVal( double flTimeout ) { TIMEVAL timeVal; timeVal.tv_sec = (long)flTimeout; timeVal.tv_usec = (long)( (flTimeout - (long)flTimeout) * 1000.0 ); return timeVal; } // Convert a CIPAddr to a sockaddr_in. void IPAddrToInAddr( const CIPAddr *pIn, in_addr *pOut ) { u_char *p = (u_char*)pOut; p[0] = pIn->ip[0]; p[1] = pIn->ip[1]; p[2] = pIn->ip[2]; p[3] = pIn->ip[3]; } // Convert a CIPAddr to a sockaddr_in. void IPAddrToSockAddr( const CIPAddr *pIn, struct sockaddr_in *pOut ) { memset( pOut, 0, sizeof(*pOut) ); pOut->sin_family = AF_INET; pOut->sin_port = htons( pIn->port ); IPAddrToInAddr( pIn, &pOut->sin_addr ); } // Convert a CIPAddr to a sockaddr_in. void SockAddrToIPAddr( const struct sockaddr_in *pIn, CIPAddr *pOut ) { const u_char *p = (const u_char*)&pIn->sin_addr; pOut->ip[0] = p[0]; pOut->ip[1] = p[1]; pOut->ip[2] = p[2]; pOut->ip[3] = p[3]; pOut->port = ntohs( pIn->sin_port ); } class CIPSocket : public ISocket { public: CIPSocket() { m_Socket = INVALID_SOCKET; m_bSetupToBroadcast = false; } virtual ~CIPSocket() { Term(); } // ISocket implementation. public: virtual void Release() { delete this; } virtual bool CreateSocket() { // Clear any old socket we had around. Term(); // Create a socket to send and receive through. SOCKET sock = socket( AF_INET, SOCK_DGRAM, IPPROTO_IP ); if ( sock == INVALID_SOCKET ) { Assert( false ); return false; } // Nonblocking please.. int status; DWORD val = 1; status = ioctlsocket( sock, FIONBIO, &val ); if ( status != 0 ) { assert( false ); closesocket( sock ); return false; } m_Socket = sock; return true; } // Called after we have a socket. virtual bool BindPart2( const CIPAddr *pAddr ) { Assert( m_Socket != INVALID_SOCKET ); // bind to it! sockaddr_in addr; IPAddrToSockAddr( pAddr, &addr ); int status = bind( m_Socket, (sockaddr*)&addr, sizeof(addr) ); if ( status == 0 ) { return true; } else { Term(); return false; } } virtual bool Bind( const CIPAddr *pAddr ) { if ( !CreateSocket() ) return false; return BindPart2( pAddr ); } virtual bool BindToAny( const unsigned short port ) { // (INADDR_ANY) CIPAddr addr; addr.ip[0] = addr.ip[1] = addr.ip[2] = addr.ip[3] = 0; addr.port = port; return Bind( &addr ); } virtual bool ListenToMulticastStream( const CIPAddr &addr, const CIPAddr &localInterface ) { ip_mreq mr; IPAddrToInAddr( &addr, &mr.imr_multiaddr ); IPAddrToInAddr( &localInterface, &mr.imr_interface ); // This helps a lot if the stream is sending really fast. int rcvBuf = 1024*1024*2; setsockopt( m_Socket, SOL_SOCKET, SO_RCVBUF, (char*)&rcvBuf, sizeof( rcvBuf ) ); if ( setsockopt( m_Socket, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*)&mr, sizeof( mr ) ) == 0 ) { // Remember this so we do IP_DEL_MEMBERSHIP on shutdown. m_bMulticastGroupMembership = true; m_MulticastGroupMREQ = mr; return true; } else { return false; } } virtual bool Broadcast( const void *pData, const int len, const unsigned short port ) { assert( m_Socket != INVALID_SOCKET ); // Make sure we're setup to broadcast. if ( !m_bSetupToBroadcast ) { BOOL bBroadcast = true; if ( setsockopt( m_Socket, SOL_SOCKET, SO_BROADCAST, (char*)&bBroadcast, sizeof( bBroadcast ) ) != 0 ) { assert( false ); return false; } m_bSetupToBroadcast = true; } CIPAddr addr; addr.ip[0] = addr.ip[1] = addr.ip[2] = addr.ip[3] = 0xFF; addr.port = port; return SendTo( &addr, pData, len ); } virtual bool SendTo( const CIPAddr *pAddr, const void *pData, const int len ) { return SendChunksTo( pAddr, &pData, &len, 1 ); } virtual bool SendChunksTo( const CIPAddr *pAddr, void const * const *pChunks, const int *pChunkLengths, int nChunks ) { WSABUF bufs[32]; if ( nChunks > 32 ) { Error( "CIPSocket::SendChunksTo: too many chunks (%d).", nChunks ); } int nTotalBytes = 0; for ( int i=0; i < nChunks; i++ ) { bufs[i].len = pChunkLengths[i]; bufs[i].buf = (char*)pChunks[i]; nTotalBytes += pChunkLengths[i]; } assert( m_Socket != INVALID_SOCKET ); // Translate the address. sockaddr_in addr; IPAddrToSockAddr( pAddr, &addr ); DWORD dwNumBytesSent = 0; DWORD ret = WSASendTo( m_Socket, bufs, nChunks, &dwNumBytesSent, 0, (sockaddr*)&addr, sizeof( addr ), NULL, NULL ); return ret == 0 && (int)dwNumBytesSent == nTotalBytes; } virtual int RecvFrom( void *pData, int maxDataLen, CIPAddr *pFrom ) { assert( m_Socket != INVALID_SOCKET ); fd_set readSet; readSet.fd_count = 1; readSet.fd_array[0] = m_Socket; TIMEVAL timeVal = SetupTimeVal( 0 ); // See if it has a packet waiting. int status = select( 0, &readSet, NULL, NULL, &timeVal ); if ( status == 0 || status == SOCKET_ERROR ) return -1; // Get the data. sockaddr_in sender; int fromSize = sizeof( sockaddr_in ); status = recvfrom( m_Socket, (char*)pData, maxDataLen, 0, (struct sockaddr*)&sender, &fromSize ); if ( status == 0 || status == SOCKET_ERROR ) { return -1; } else { if ( pFrom ) { SockAddrToIPAddr( &sender, pFrom ); } m_flLastRecvTime = IP_FloatTime(); return status; } } virtual double GetRecvTimeout() { return IP_FloatTime() - m_flLastRecvTime; } private: void Term() { if ( m_Socket != INVALID_SOCKET ) { if ( m_bMulticastGroupMembership ) { // Undo our multicast group membership. setsockopt( m_Socket, IPPROTO_IP, IP_DROP_MEMBERSHIP, (char*)&m_MulticastGroupMREQ, sizeof( m_MulticastGroupMREQ ) ); } closesocket( m_Socket ); m_Socket = INVALID_SOCKET; } m_bSetupToBroadcast = false; m_bMulticastGroupMembership = false; } private: SOCKET m_Socket; bool m_bMulticastGroupMembership; // Did we join a multicast group? ip_mreq m_MulticastGroupMREQ; bool m_bSetupToBroadcast; double m_flLastRecvTime; bool m_bListenSocket; }; ISocket* CreateIPSocket() { return new CIPSocket; } ISocket* CreateMulticastListenSocket( const CIPAddr &addr, const CIPAddr &localInterface ) { CIPSocket *pSocket = new CIPSocket; CIPAddr bindAddr = localInterface; bindAddr.port = addr.port; if ( pSocket->Bind( &bindAddr ) && pSocket->ListenToMulticastStream( addr, localInterface ) ) { return pSocket; } else { pSocket->Release(); return NULL; } } bool ConvertStringToIPAddr( const char *pStr, CIPAddr *pOut ) { char ipStr[512]; const char *pColon = strchr( pStr, ':' ); if ( pColon ) { int toCopy = pColon - pStr; if ( toCopy < 2 || toCopy > sizeof(ipStr)-1 ) { assert( false ); return false; } memcpy( ipStr, pStr, toCopy ); ipStr[toCopy] = 0; pOut->port = (unsigned short)atoi( pColon+1 ); } else { strncpy( ipStr, pStr, sizeof( ipStr ) ); ipStr[ sizeof(ipStr)-1 ] = 0; } if ( ipStr[0] >= '0' && ipStr[0] <= '9' ) { // It's numbers. int ip[4]; sscanf( ipStr, "%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3] ); pOut->ip[0] = (unsigned char)ip[0]; pOut->ip[1] = (unsigned char)ip[1]; pOut->ip[2] = (unsigned char)ip[2]; pOut->ip[3] = (unsigned char)ip[3]; } else { // It's a text string. struct hostent *pHost = gethostbyname( ipStr ); if( !pHost ) return false; pOut->ip[0] = pHost->h_addr_list[0][0]; pOut->ip[1] = pHost->h_addr_list[0][1]; pOut->ip[2] = pHost->h_addr_list[0][2]; pOut->ip[3] = pHost->h_addr_list[0][3]; } return true; } bool ConvertIPAddrToString( const CIPAddr *pIn, char *pOut, int outLen ) { in_addr addr; addr.S_un.S_un_b.s_b1 = pIn->ip[0]; addr.S_un.S_un_b.s_b2 = pIn->ip[1]; addr.S_un.S_un_b.s_b3 = pIn->ip[2]; addr.S_un.S_un_b.s_b4 = pIn->ip[3]; HOSTENT *pEnt = gethostbyaddr( (char*)&addr, sizeof( addr ), AF_INET ); if ( pEnt ) { Q_strncpy( pOut, pEnt->h_name, outLen ); return true; } else { return false; } } void IP_GetLastErrorString( char *pStr, int maxLen ) { char *lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL ); Q_strncpy( pStr, lpMsgBuf, maxLen ); LocalFree( lpMsgBuf ); }
12,513
5,607
/* * EFiberMutex.hh * * Created on: 2016-5-9 * Author: cxxjava@163.com */ #ifndef EFIBERMUTEX_HH_ #define EFIBERMUTEX_HH_ #include "./EFiberBlocker.hh" namespace efc { namespace eco { /** * Mutex for fiber. */ class EFiberMutex: public ELock { public: virtual ~EFiberMutex(); EFiberMutex(); virtual void lock(); virtual void lockInterruptibly() THROWS(EUnsupportedOperationException); virtual boolean tryLock(); virtual boolean tryLock(llong time, ETimeUnit* unit=ETimeUnit::MILLISECONDS); virtual void unlock(); virtual ECondition* newCondition() THROWS(EUnsupportedOperationException); virtual boolean isLocked(); private: EFiberBlocker blocker; }; } /* namespace eco */ } /* namespace efc */ #endif /* EFIBERMUTEX_HH_ */
756
288
/// @file lascl.hpp Multiplies a matrix by a scalar. /// @author Weslley S Pereira, University of Colorado Denver, USA // // Copyright (c) 2012-2021, University of Colorado Denver. All rights reserved. // // This file is part of <T>LAPACK. // <T>LAPACK is free software: you can redistribute it and/or modify it under // the terms of the BSD 3-Clause license. See the accompanying LICENSE file. #ifndef __SLATE_LASCL_HH__ #define __SLATE_LASCL_HH__ #include "lapack/types.hpp" #include "lapack/lascl.hpp" namespace lapack { /** @brief Multiplies a matrix A by the real scalar a/b. * * Multiplication of a matrix A by scalar a/b is done without over/underflow as long as the final * result $a A/b$ does not over/underflow. The parameter type specifies that * A may be full, upper triangular, lower triangular, upper Hessenberg, or banded. * * @return 0 if success. * @return -i if the ith argument is invalid. * * @param[in] type Specifies the type of matrix A. * * MatrixType::General: * A is a full matrix. * MatrixType::Lower: * A is a lower triangular matrix. * MatrixType::Upper: * A is an upper triangular matrix. * MatrixType::Hessenberg: * A is an upper Hessenberg matrix. * MatrixType::LowerBand: * A is a symmetric band matrix with lower bandwidth kl and upper bandwidth ku * and with the only the lower half stored. * MatrixType::UpperBand: * A is a symmetric band matrix with lower bandwidth kl and upper bandwidth ku * and with the only the upper half stored. * MatrixType::Band: * A is a band matrix with lower bandwidth kl and upper bandwidth ku. * * @param[in] kl The lower bandwidth of A, used only for banded matrix types B, Q and Z. * @param[in] ku The upper bandwidth of A, used only for banded matrix types B, Q and Z. * @param[in] b The denominator of the scalar a/b. * @param[in] a The numerator of the scalar a/b. * @param[in] m The number of rows of the matrix A. m>=0 * @param[in] n The number of columns of the matrix A. n>=0 * @param[in,out] A Pointer to the matrix A [in/out]. * @param[in] lda The column length of the matrix A. * * @ingroup auxiliary */ template< typename T > int lascl( lapack::MatrixType matrixtype, idx_t kl, idx_t ku, const real_type<T>& b, const real_type<T>& a, idx_t m, idx_t n, T* A, idx_t lda ) { using blas::internal::colmajor_matrix; using std::max; // check arguments lapack_error_if( (matrixtype != MatrixType::General) && (matrixtype != MatrixType::Lower) && (matrixtype != MatrixType::Upper) && (matrixtype != MatrixType::Hessenberg), -1 ); lapack_error_if( ( (matrixtype == MatrixType::LowerBand) || (matrixtype == MatrixType::UpperBand) || (matrixtype == MatrixType::Band) ) && ( (kl < 0) || (kl > max(m-1, idx_t(0))) ), -2 ); lapack_error_if( ( (matrixtype == MatrixType::LowerBand) || (matrixtype == MatrixType::UpperBand) || (matrixtype == MatrixType::Band) ) && ( (ku < 0) || (ku > max(n-1, idx_t(0))) ), -3 ); lapack_error_if( ( (matrixtype == MatrixType::LowerBand) || (matrixtype == MatrixType::UpperBand) ) && ( kl != ku ), -3 ); lapack_error_if( m < 0, -6 ); lapack_error_if( (lda < m) && ( (matrixtype == MatrixType::General) || (matrixtype == MatrixType::Lower) || (matrixtype == MatrixType::Upper) || (matrixtype == MatrixType::Hessenberg) ), -9 ); lapack_error_if( (matrixtype == MatrixType::LowerBand) && (lda < kl + 1), -9); lapack_error_if( (matrixtype == MatrixType::UpperBand) && (lda < ku + 1), -9); lapack_error_if( (matrixtype == MatrixType::Band) && (lda < 2 * kl + ku + 1), -9); // Matrix views auto _A = colmajor_matrix<T>( A, m, n, lda ); if (matrixtype == MatrixType::General) return lascl( general_matrix, b, a, _A ); else if (matrixtype == MatrixType::Lower) return lascl( lower_triangle, b, a, _A ); else if (matrixtype == MatrixType::Upper) return lascl( upper_triangle, b, a, _A ); else if (matrixtype == MatrixType::Hessenberg) return lascl( hessenberg_matrix, b, a, _A ); else if (matrixtype == MatrixType::LowerBand) return lascl( symmetric_lowerband_t{kl}, b, a, _A ); else if (matrixtype == MatrixType::UpperBand) return lascl( symmetric_upperband_t{ku}, b, a, _A ); else if (matrixtype == MatrixType::Band) return lascl( band_matrix_t{kl,ku}, b, a, _A ); return 0; } } #endif // __LASCL_HH__
4,799
1,642
#include "adminlogssystem.h" AdminLogsSystem::AdminLogsSystem(QObject *parent): QObject(parent) { logsSystem = new LogsSystem; logsSystem->moveToThread(&logsSystemThread); connect(&logsSystemThread, &QThread::finished, logsSystem, &QObject::deleteLater); connect(this, &AdminLogsSystem::operate, logsSystem, &LogsSystem::doWork); connect(logsSystem, &LogsSystem::resultReady, this, &AdminLogsSystem::handleResults); connect(logsSystem, &LogsSystem::SignalTemperatura, this, &AdminLogsSystem::SlotTemperatura); connect(logsSystem, &LogsSystem::SignalRAM, this, &AdminLogsSystem::SlotRAM); connect(logsSystem, &LogsSystem::SignalProcesos, this, &AdminLogsSystem::SignalProcesos); connect(logsSystem, &LogsSystem::SignalSOCKET, this, &AdminLogsSystem::SignalSOCKET); connect(logsSystem, &LogsSystem::SignalStatusWIFI, this, &AdminLogsSystem::SignalStatusWIFI); connect(logsSystem, &LogsSystem::SignalEspacioDisco, this, &AdminLogsSystem::SlotEspacioDisco); logsSystemThread.start(); //initHilo(accion); } AdminLogsSystem::~AdminLogsSystem() { } void AdminLogsSystem::SlotTemperatura(float temperatura) { emit SignalTemperatura(temperatura); } void AdminLogsSystem::SlotRAM(QString RAM) { emit SignalRAM(RAM); } void AdminLogsSystem::SlotSOCKET(int SOCKET) { emit SignalSOCKET(SOCKET); } void AdminLogsSystem::SlotProcesos(int Procesos) { emit SignalProcesos(Procesos); } void AdminLogsSystem::SlotStatusWIFI(bool StatusWIFI) { emit SignalStatusWIFI(StatusWIFI); } void AdminLogsSystem::SlotEspacioDisco(QString EspacioDisco) { emit SignalEspacioDisco(EspacioDisco); } void AdminLogsSystem::initHilo(int accion) { emit operate(accion); } void AdminLogsSystem::handleResults(const QString &result) { }
1,795
637
// gitupdate.cpp : Tento soubor obsahuje funkci main. Provádění programu se tam zahajuje a ukončuje. // #define _CTR_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <string.h> #include <conio.h> #include <windows.h> #include <stdlib.h> #include <string> #include<algorithm> #include <cstring> #include <functional> #include <sstream> //#define START #pragma comment(linker,"\"/manifestdependency:type='win32' \ name='Microsoft.Windows.Common-Controls' version='6.0.0.0' \ processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") using namespace std; //vraci jestli nasel novy update /*bool LoadUpdates() { }*/ string version = "v1.2"; string str = ""; int create_copy(const char* NameSource, const char* targetName) { const unsigned buflen = 4096; ifstream source; ofstream target; unsigned _count = 0; char buffer[buflen]; unsigned loaded; source.open(NameSource, ios::in | ios::binary); if (!source) { return -1; } target.open(targetName, ios::out | ios::binary); if (!target) { return -3; } while (source.read(buffer, buflen), loaded = source.gcount(), loaded > 0) { target.write(buffer, loaded); _count += loaded; } source.close(); target.close(); return _count; } bool FolderExists(const string& path) { DWORD dwAttrib = GetFileAttributesA(path.c_str()); return dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY) != 0; } void eraseSubStr(std::string& mainStr, const std::string& toErase) { // Search for the substring in string size_t pos = mainStr.find(toErase); if (pos != std::string::npos) { // If found then erase it from string mainStr.erase(pos, toErase.length()); } } inline bool FileExist(const std::string& name) { #pragma warning(suppress : 4996) if (FILE* file = fopen(name.c_str(), "r")) { fclose(file); return true; } else { return false; } } string ToString(int x) { stringstream ss; ss << x; return ss.str(); } int main() { HWND con = GetConsoleWindow(); #pragma warning(disable: 4996) string path = getenv("PRG path"); string pP = path + "/ver.txt"; ifstream verL(pP.c_str()); #ifdef START getline(verL, version); #endif cout << path << endl; if (FileExist("info.txt")) { remove("info.txt"); } if (FileExist("p.zip")) { remove("p.zip"); } system("curl -L -O -C - https://raw.githubusercontent.com/MitasVit/Patern-Remember-Game/main/info.txt"); //curl https://codeload.github.com/MitasVit/Patern-Remember-Game/zip/refs/tags/v1.3 >> 13 ifstream File("info.txt"); string line[2]; string must; if (File.is_open()) { for(int i = 0; i < 2; i++){ getline(File, line[i]); cout << line[i] << endl; } File.close(); } else { cout << "Error! File not found!"; exit(1); } if (line[0] != version) { string t = "New update found version(" + line[0] + "), do you want to install?"; int tmp = MessageBoxA(NULL, t.c_str(), "New update found", MB_YESNO | MB_ICONQUESTION); if (tmp == IDYES) { HWND win = FindWindow(NULL, L"Patern Remember Game"); DestroyWindow(win); version = line[0]; #ifdef START verL.close(); ifstream _new(Pp.c_str()); _new << version; #endif system("CLS"); str = line[1]; //Download(con); string t2 = "curl -L -C - " + line[1] + " >> p.zip"; system(t2.c_str()); system("mkdir p"); cout << "powershell -command \"Expand-Archive -Force 'p.zip' 'p'\"" << endl; system("powershell -command Expand - Archive - Force 'p.zip' 'p'"); line[0].erase(remove(line[0].begin(), line[0].end(), 'v'), line[0].end()); cout << endl <<"line0 " << line[0] << endl; string t3 = "Patern-Remember-Game-" + line[0]; cout << endl << "t3 " << t3 << endl; string p1 = "p/" + t3 + "/Patern Remember Game/Debug/Patern Remember Game.exe"; cout << "p1 " << p1 << endl; string full = path + "/Patern Remember Game.exe"; cout << full << endl; create_copy(p1.c_str(), full.c_str()); ShellExecuteA(NULL, "open", full.c_str(), NULL, NULL, SW_SHOWNORMAL); remove("p.zip"); remove("info.txt"); system("rmdir p"); /* * --------------------SETUP * [Registry] Root: HKCU; Subkey: "Environment"; ValueType:string; ValueName: "PRG path"; \ ValueData: {autopf}\{#MyAppName}; Flags: preservestringtype [Setup] ; Tell Windows Explorer to reload the environment ChangesEnvironment=yes */ } } /*cout << endl << endl << endl; must = line[1]; cout << must << endl; eraseSubStr(must, "<html><body>You are being <a href=\""); eraseSubStr(must, "\" > redirected< / a>.< / body> < / html>"); cout << must << endl;*/ }
4,825
1,979
#pragma once namespace appbase { extern const char* appbase_version_string; }
85
27
//$Id: Brent.cpp 10052 2011-12-06 22:56:03Z djcinsb $ //------------------------------------------------------------------------------ // Brent //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under NASA Prime // Contract NNG10CP02C, Task Order 28 // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: Sep 20, 2011 // /** * Implementation of Brent's Method used in event location and, eventually, * stopping conditions */ //------------------------------------------------------------------------------ #include "Brent.hpp" #include "EventException.hpp" #include "RealUtilities.hpp" #include "MessageInterface.hpp" //#define DEBUG_BRENT //#define DEBUG_BRENT_BUFFER //#define DEBUG_BRACKETACCESS //------------------------------------------------------------------------------ // Brent() //------------------------------------------------------------------------------ /** * Default constructor */ //------------------------------------------------------------------------------ Brent::Brent() : RootFinder ("BrentsMethod"), bisectionUsed (true), epochOfStep (-1.0), step (0.0), oldCValue (-1.0) { bufferSize = 3; } //------------------------------------------------------------------------------ // ~Brent() //------------------------------------------------------------------------------ /** * Destructor */ //------------------------------------------------------------------------------ Brent::~Brent() { } //------------------------------------------------------------------------------ // Brent(const Brent & b) //------------------------------------------------------------------------------ /** * Copy constructor * * @param b The original being copied here */ //------------------------------------------------------------------------------ Brent::Brent(const Brent & b) : RootFinder (b), bisectionUsed (true), epochOfStep (-1.0), step (0.0), oldCValue (-1.0) { } //------------------------------------------------------------------------------ // Brent &operator =(const Brent & b) //------------------------------------------------------------------------------ /** * Assignment operator * * @param b The original being copied here * * @return this instance, set to match b. */ //------------------------------------------------------------------------------ Brent & Brent::operator =(const Brent & b) { if (this != &b) { RootFinder::operator =(b); bisectionUsed = true; epochOfStep = -1.0; step = 0.0; oldCValue = -1.0; } return *this; } //------------------------------------------------------------------------------ // bool Brent::Initialize(GmatEpoch t0, Real f0, GmatEpoch t1, Real f1) //------------------------------------------------------------------------------ /** * Prepares Brent's Method for use * * This method calls the RootFinder initialization to prepare the buffers for * use, then rearranges the buffers as needed and sets the third data point to * the first as needed by the algorithm. * * @param t0 The earlier epoch for the data. * @param f0 The function value at t0 * @param t1 The later epoch for the data. * @param f1 The function value at t1 * * @return true if initialization succeeds, false if it fails. */ //------------------------------------------------------------------------------ bool Brent::Initialize(GmatEpoch t0, Real f0, GmatEpoch t1, Real f1) { #ifdef DEBUG_BRENT MessageInterface::ShowMessage("Brent::Initialize(%15.9lf, %12lf, %15.9lf, " "%12lf) called\n", t0, f0, t1, f1); #endif if (f0 * f1 >= 0.0) throw EventException("Error initializing Brent's method; the solution is " "not bracketed"); bool retval = RootFinder::Initialize(t0, f0, t1, f1); if (retval) { if (buffer[0] < buffer[1]) { Swap(0, 1); } epochBuffer[2] = epochBuffer[0]; buffer[2] = buffer[0]; bisectionUsed = true; // Act as if bisection was used previously } #ifdef DEBUG_BRENT_BUFFER MessageInterface::ShowMessage("Brent::Buffer Data:\n %15.9lf " "%.12lf\n %15.9lf %.12lf\n %15.9lf %.12lf\n", epochBuffer[0], buffer[0], epochBuffer[1], buffer[1], epochBuffer[2], buffer[2]); #endif return retval; } //------------------------------------------------------------------------------ // void SetValue(GmatEpoch forEpoch, Real withValue) //------------------------------------------------------------------------------ /** * Adds a new data point to the algorithm, discarding the stale data * * @param forEpoch The epoch of the new data * @param withValue The new data value * * @return true on success. (This Brent's method override always returns true) */ //------------------------------------------------------------------------------ bool Brent::SetValue(GmatEpoch forEpoch, Real withValue) { #ifdef DEBUG_BRENT_BUFFER MessageInterface::ShowMessage("Received data: %15.9lf %.12lf\n", forEpoch, withValue); MessageInterface::ShowMessage("Brent::SetValue Initial Buffer Data:\n " "%15.9lf %.12lf\n %15.9lf %.12lf\n %15.9lf %.12lf\n", epochBuffer[0], buffer[0], epochBuffer[1], buffer[1], epochBuffer[2], buffer[2]); #endif bool retval = true; oldCValue = epochBuffer[2]; epochBuffer[2] = epochBuffer[1]; buffer[2] = buffer[1]; if (buffer[0] * withValue < 0.0) { epochBuffer[1] = forEpoch; buffer[1] = withValue; } else { epochBuffer[0] = forEpoch; buffer[0] = withValue; } if (GmatMathUtil::Abs(buffer[0]) < GmatMathUtil::Abs(buffer[1])) Swap(0,1); #ifdef DEBUG_BRENT_BUFFER MessageInterface::ShowMessage("Brent::SetValue Updated Buffer Data:\n " "%15.9lf %.12lf\n %15.9lf %.12lf\n %15.9lf %.12lf\n", epochBuffer[0], buffer[0], epochBuffer[1], buffer[1], epochBuffer[2], buffer[2]); #endif return retval; } //------------------------------------------------------------------------------ // Real FindStep() //------------------------------------------------------------------------------ /** * Finds the next step to take, given the data in the buffers. * * @param currentEpoch The epoch of the latest data in the buffers. If not set, * the return value is treated as absolute and the step is not converted * from days to seconds from the current epoch. * * @return The next step * * @todo Complete the implementation of Brent's algorithm. THe current code is * performing bisection. */ //------------------------------------------------------------------------------ Real Brent::FindStep(const GmatEpoch currentEpoch) { bool bisectOnly = false; if (bisectOnly) { epochOfStep = 0.5 * (epochBuffer[0] + epochBuffer[1]); } else { Real diffAB, diffAC, diffBC; diffAB = buffer[0] - buffer[1]; if ((buffer[0] != buffer[2]) && (buffer[1] != buffer[2])) { diffAC = buffer[0] - buffer[2]; diffBC = buffer[1] - buffer[2]; // Inverse quadratic interpolation epochOfStep = epochBuffer[0] * buffer[1] * buffer[2] / ((diffAB*diffAC)) + epochBuffer[1] * buffer[0] * buffer[2] / ((-diffAB*diffBC)) + epochBuffer[2] * buffer[0] * buffer[1] / ((diffAC*diffBC)); } else { // Secant method epochOfStep = epochBuffer[1] - buffer[1] * (epochBuffer[0] - epochBuffer[1])/diffAB; } // Figure out if we need to drop back to bisection Real delta = 1.0e-8; // Numerical tolerance for epochs; set to ~1 msec Real deltaC, bMinusC, sMinusB; deltaC = GmatMathUtil::Abs(epochBuffer[2] - oldCValue); bMinusC = GmatMathUtil::Abs(epochBuffer[1]-epochBuffer[2]); sMinusB = GmatMathUtil::Abs(epochOfStep - epochBuffer[1]); if ( ((epochOfStep >= (3.0 * epochBuffer[0] + epochBuffer[1]) / 4.0) && (epochOfStep <= epochBuffer[1])) || (bisectionUsed && (sMinusB >= bMinusC / 2.0)) || (!bisectionUsed && (sMinusB >= deltaC / 2.0)) || (bisectionUsed && (bMinusC < delta)) || (!bisectionUsed && deltaC < delta) ) { // Drop back to bisection. Sigh. epochOfStep = 0.5 * (epochBuffer[0] + epochBuffer[1]); bisectionUsed = true; } else bisectionUsed = false; } // Get the step in seconds to the epochOfStep if input in days was set if (currentEpoch != -1.0) step = (epochOfStep - currentEpoch) * GmatTimeConstants::SECS_PER_DAY; else step = epochOfStep; #ifdef DEBUG_BRENT MessageInterface::ShowMessage("Brent's Method: Current Epoch: %15.9lf, " "Epoch of Step: %15.9lf, step: %15.9lf\n", currentEpoch, epochOfStep, step); #endif return step; } //------------------------------------------------------------------------------ // Real GetStepMeasure() //------------------------------------------------------------------------------ /** * Retrieves the size of the epoch brackets * * @return The difference, in seconds, between the two epochs bracketing the * zero */ //------------------------------------------------------------------------------ Real Brent::GetStepMeasure() { GmatEpoch start, end; GetBrackets(start, end); return (end - start) * GmatTimeConstants::SECS_PER_DAY; } //------------------------------------------------------------------------------ // void GetBrackets(GmatEpoch &start, GmatEpoch &end) //------------------------------------------------------------------------------ /** * Retrieves the bracketing epochs from the epoch buffer. * * @param start The epoch earlier than the zero value * @param end The epoch later than the zero value */ //------------------------------------------------------------------------------ void Brent::GetBrackets(GmatEpoch &start, GmatEpoch &end) { Real val = GmatMathUtil::Abs(buffer[0]), temp; GmatEpoch locT = epochBuffer[0], t2, dt = 9.0e9; Integer found = 0; // Find the index of the closest to zero function value for (Integer i = 1; i < 3; ++i) { temp = GmatMathUtil::Abs(buffer[i]); if (temp < val) { val = temp; locT = epochBuffer[i]; found = i; } } // Find the index of the other side t2 = epochBuffer[0]; for (Integer i = 0; i < 3; ++i) { if (found != i) { if (buffer[found] * buffer[i] < 0.0) { if (GmatMathUtil::Abs(locT - epochBuffer[i]) < dt) t2 = epochBuffer[i]; } } } start = (locT < t2 ? locT : t2); end = (locT > t2 ? locT : t2); #ifdef DEBUG_BRACKETACCESS MessageInterface::ShowMessage("Buffer data:\n"); for (Integer i = 0; i < 3; ++i) MessageInterface::ShowMessage(" %.12lf %le\n", epochBuffer[i], buffer[i]); MessageInterface::ShowMessage("Bracketing epochs: [%.12lf %.12lf]\n", start, end); #endif }
11,613
3,603
// // ulib - a collection of useful classes // Copyright (C) 2007,2008,2012,2014,2017,2020 Michael Fink // /// \file ITextStream.hpp text stream interface // #pragma once namespace Stream { /// text stream interface class ITextStream { public: /// text encoding that is possible for text files enum ETextEncoding { textEncodingNative, ///< native encoding; compiler options decide if ANSI or Unicode is used for output textEncodingAnsi, ///< ANSI text encoding; depends on the current codepage (not recommended) textEncodingUTF8, ///< UTF-8 encoding textEncodingUCS2, ///< UCS-2 encoding }; /// line ending mode used to detect lines or is used for writing enum ELineEndingMode { lineEndingCRLF, ///< a CR and LF char (\\r\\n) is used to separate lines; Win32-style lineEndingLF, ///< a LF char (\\n) is used to separate lines; Linux-style lineEndingCR, ///< a CR char (\\r) is used to separate lines; Mac-style lineEndingReadAny,///< when reading, any of the above line ending modes are detected when using ReadLine() lineEndingNative, ///< native mode is used }; /// ctor ITextStream(ETextEncoding textEncoding = textEncodingNative, ELineEndingMode lineEndingMode = lineEndingNative) :m_textEncoding(textEncoding), m_lineEndingMode(lineEndingMode) { } /// dtor virtual ~ITextStream() { // nothing to cleanup } // stream capabilities /// returns text encoding currently in use ETextEncoding TextEncoding() const { return m_textEncoding; } /// returns line ending mode currently in use ELineEndingMode LineEndingMode() const { return m_lineEndingMode; } /// returns true when stream can be read virtual bool CanRead() const = 0; /// returns true when stream can be written to virtual bool CanWrite() const = 0; /// returns true when the stream end is reached virtual bool AtEndOfStream() const = 0; // read support /// reads a single character virtual TCHAR ReadChar() = 0; /// reads a whole line using line ending settings virtual void ReadLine(CString& line) = 0; // write support /// writes text virtual void Write(const CString& text) = 0; /// writes endline character virtual void WriteEndline() = 0; /// writes a line void WriteLine(const CString& line) { Write(line); WriteEndline(); } /// flushes out text stream virtual void Flush() = 0; private: friend class TextStreamFilter; /// current text encoding ETextEncoding m_textEncoding; /// current line ending mode ELineEndingMode m_lineEndingMode; }; } // namespace Stream
2,913
818
// Fill out your copyright notice in the Description page of Project Settings. #include "SampleSubSystem.h" #include "AsyncSample.h" //--------------------------------------------------------------------------------- // SampleSubSystem //--------------------------------------------------------------------------------- TStatId USampleSubSystem::GetStatId() const { RETURN_QUICK_DECLARE_CYCLE_STAT(SampleSubSystem, STATGROUP_Tickables); } void USampleSubSystem::Tick(float DeltaTime) { AsyncSample->Update(DeltaTime); } bool USampleSubSystem::IsTickable() const { return true; } ETickableTickType USampleSubSystem::GetTickableTickType() const { return IsTemplate() ? ETickableTickType::Never : ETickableTickType::Conditional; } void USampleSubSystem::StartAutoDeleteAsyncSample(float WaitSec) { AsyncSample->StartAutoDeleteAsync(WaitSec); } void USampleSubSystem::StartAsyncSample(float WaitSec) { AsyncSample->StartAsyncTask(WaitSec); } void USampleSubSystem::CheckAsyncTaskBehaviour() { AsyncSample->CheckAsyncTaskBehaviour(); } void USampleSubSystem::CancelAsyncSample() { AsyncSample->CancelAsyncTask(); } void USampleSubSystem::CheckAsyncCrash() { AsyncSample->CheckCrash(); } void USampleSubSystem::Initialize(FSubsystemCollectionBase& Collection) { Super::Initialize(Collection); AsyncSample = MakeShareable(new FAsyncSample()); }
1,362
416
#include "Particle.hpp" #include <device_launch_parameters.h> #include <mirror/simt_macros.hpp> #include <mirror/simt_allocator.hpp> #include <mirror/simt_vector.hpp> #include <mirror/simt_serialization.hpp> #include <mirror/simt_utilities.hpp> ParticleSquare::ParticleSquare(double L) : m_L(L) {} ParticleSquare::~ParticleSquare() { ; } HOSTDEVICE double ParticleSquare::area() const { return m_L * m_L; } HOSTDEVICE double ParticleSquare::mass() const { return 1.0; } HOST void ParticleSquare::write(mirror::serializer & io) const { io.write(m_L); } HOSTDEVICE void ParticleSquare::read(mirror::serializer::size_type startPosition, mirror::serializer & io) { io.read(startPosition, &m_L); } HOSTDEVICE ParticleSquare::type_id_t ParticleSquare::type() const { return ParticleTypes::eParticleSquare; } ParticleCircle::ParticleCircle(double radius) : m_radius(radius) {} ParticleCircle::~ParticleCircle() { ; } HOSTDEVICE double ParticleCircle::area() const { return 3.1415 * m_radius * m_radius; } HOSTDEVICE double ParticleCircle::mass() const { return 1.0; } HOST void ParticleCircle::write(mirror::serializer & io) const { io.write(m_radius); } HOSTDEVICE void ParticleCircle::read(mirror::serializer::size_type startPosition, mirror::serializer & io) { io.read(startPosition, &m_radius); } HOSTDEVICE ParticleCircle::type_id_t ParticleCircle::type() const { return ParticleTypes::eParticleCircle; } ParticleTriangle::ParticleTriangle(double base, double height) : m_base(base), m_height(height) {} ParticleTriangle::~ParticleTriangle() { ; } HOSTDEVICE double ParticleTriangle::area() const { return 0.5 * m_base * m_height; } HOSTDEVICE double ParticleTriangle::mass() const { return 1.0; } HOST void ParticleTriangle::write(mirror::serializer & io) const { io.write(m_base); io.write(m_height); } HOSTDEVICE void ParticleTriangle::read(mirror::serializer::size_type startPosition, mirror::serializer & io) { io.read(startPosition, &m_base); io.read(startPosition, &m_height); } HOSTDEVICE ParticleTriangle::type_id_t ParticleTriangle::type() const { return ParticleTypes::eParticleTriangle; } size_t mirror::polymorphic_traits<Particle>::cache[enum_type::Max_];
2,236
792
// ECS.cpp : Questo file contiene la funzione 'main', in cui inizia e termina l'esecuzione del programma. // #include <iostream> #include <vector> #include <time.h> #include "Heder/ECS_Context.h" #include "Heder/Component.h" class ClassTest { public: ClassTest(); ~ClassTest(); void Adding() { inttt += 5; } private: int inttt; }; ClassTest::ClassTest() { inttt = 5; } ClassTest::~ClassTest() { } using namespace std; int main() { size_t entttSNumber = 5; //Create ECS context ECS_Context* context = new ECS_Context(); for (int i = 0; i < entttSNumber; i++) { //Create entity context->CreateAndAddEntity(); //Link component to entity context->AddComponentToEntity<Integer>(context->GetEntity(i), Integer(0)); if (i % 2) { context->AddComponentToEntity<Boolean>(context->GetEntity(i), Boolean()); } } context->RemoveComponentToEntity<Integer>(context->GetEntity(3)); context->AddComponentToEntity<Integer>(context->GetEntity(3), Integer(0)); { std::vector< Integer*> ii; context->GetTypes<Integer>(ii); //___________________________________________________________ clock_t begin_time = clock(); for (size_t j = 0; j < ii.size(); j++) { ii[j]->integer += 5; } std::cout << "ecs time " << clock() - begin_time << std::endl; std::cout << "ecs time " << float(clock() - begin_time) << std::endl; ii.clear(); ii.shrink_to_fit(); //___________________________________________________________ std::list<ClassTest*> v; for (size_t i = 0; i < entttSNumber; i++) { v.emplace(v.end(), new ClassTest()); } clock_t begin_time0 = clock(); for (auto vEl : v) { vEl->Adding(); } std::cout << "class time " << clock() - begin_time << std::endl; std::cout << "class time " << float(clock() - begin_time0) << std::endl;; //___________________________________________________________ for (auto vEl : v) { delete vEl; } v.clear(); delete context; } }
1,959
761
#include "DBlmdb.hpp" #include <boost/lexical_cast.hpp> #include <iostream> #include "PathTools.hpp" using namespace platform; #ifdef _WIN32 #pragma comment(lib, "ntdll.lib") // dependency of lmdb, here to avoid linker arguments #endif static void lmdb_check(int rc, const char *msg) { if (rc != MDB_SUCCESS) throw platform::lmdb::Error(msg + std::to_string(rc)); } platform::lmdb::Env::Env() { lmdb_check(::mdb_env_create(&handle), "mdb_env_create "); } platform::lmdb::Env::~Env() { ::mdb_env_close(handle); handle = nullptr; } platform::lmdb::Txn::Txn(Env &db_env) { lmdb_check(::mdb_txn_begin(db_env.handle, nullptr, 0, &handle), "mdb_txn_begin "); } void platform::lmdb::Txn::commit() { lmdb_check(::mdb_txn_commit(handle), "mdb_txn_commit "); handle = nullptr; } platform::lmdb::Txn::~Txn() { ::mdb_txn_abort(handle); handle = nullptr; } // ::mdb_dbi_close should never be called according to docs platform::lmdb::Dbi::Dbi(Txn &db_txn) { lmdb_check(::mdb_dbi_open(db_txn.handle, nullptr, 0, &handle), "mdb_dbi_open "); } bool platform::lmdb::Dbi::get(Txn &db_txn, MDB_val *const key, MDB_val *const data) { const int rc = ::mdb_get(db_txn.handle, handle, key, data); if (rc != MDB_SUCCESS && rc != MDB_NOTFOUND) throw Error("mdb_get " + std::to_string(rc)); return (rc == MDB_SUCCESS); } platform::lmdb::Cur::Cur(Txn &db_txn, Dbi &db_dbi) { lmdb_check(::mdb_cursor_open(db_txn.handle, db_dbi.handle, &handle), "mdb_cursor_open "); } platform::lmdb::Cur::Cur(Cur &&other) noexcept { std::swap(handle, other.handle); } bool platform::lmdb::Cur::get(MDB_val *const key, MDB_val *const data, const MDB_cursor_op op) { const int rc = ::mdb_cursor_get(handle, key, data, op); if (rc != MDB_SUCCESS && rc != MDB_NOTFOUND) throw Error("mdb_cursor_get" + std::to_string(rc)); return (rc == MDB_SUCCESS); } platform::lmdb::Cur::~Cur() { ::mdb_cursor_close(handle); handle = nullptr; } DBlmdb::DBlmdb(const std::string &full_path, uint64_t max_db_size) : full_path(full_path) { std::cout << "lmdb libversion=" << mdb_version(nullptr, nullptr, nullptr) << std::endl; lmdb_check(::mdb_env_set_mapsize(db_env.handle, max_db_size), "mdb_env_set_mapsize "); create_directories_if_necessary(full_path); lmdb_check(::mdb_env_open(db_env.handle, full_path.c_str(), MDB_NOMETASYNC, 0644), "mdb_env_open "); // MDB_NOMETASYNC - We agree to trade chance of losing 1 last transaction for 2x performance boost db_txn.reset(new lmdb::Txn(db_env)); db_dbi.reset(new lmdb::Dbi(*db_txn)); } size_t DBlmdb::test_get_approximate_size() const { MDB_stat sta{}; lmdb_check(::mdb_env_stat(db_env.handle, &sta), "mdb_env_stat "); return sta.ms_psize * (sta.ms_branch_pages + sta.ms_leaf_pages + sta.ms_overflow_pages); } size_t DBlmdb::get_approximate_items_count() const { MDB_stat sta{}; lmdb_check(::mdb_env_stat(db_env.handle, &sta), "mdb_env_stat "); return sta.ms_entries; } DBlmdb::Cursor::Cursor( lmdb::Cur &&cur, const std::string &prefix, const std::string &middle, size_t max_key_size, bool forward) : db_cur(std::move(cur)), prefix(prefix), forward(forward) { std::string start = prefix + middle; lmdb::Val itkey(start); if (forward) is_end = !db_cur.get(itkey, data, start.empty() ? MDB_FIRST : MDB_SET_RANGE); else { if (start.empty()) is_end = !db_cur.get(itkey, data, MDB_LAST); else { if (start.size() < max_key_size) start += std::string(max_key_size - start.size(), char(0xff)); itkey = lmdb::Val(start); is_end = !db_cur.get(itkey, data, MDB_SET_RANGE); is_end = !db_cur.get(itkey, data, is_end ? MDB_LAST : MDB_PREV); // If failed to find a key >= prefix, then it should be last in db } } check_prefix(itkey); } void DBlmdb::Cursor::next() { lmdb::Val itkey; is_end = !db_cur.get(itkey, &*data, forward ? MDB_NEXT : MDB_PREV); check_prefix(itkey); } void DBlmdb::Cursor::erase() { if (is_end) return; // Some precaution lmdb_check(::mdb_cursor_del(db_cur.handle, 0), "mdb_cursor_del "); next(); } void DBlmdb::Cursor::check_prefix(const lmdb::Val &itkey) { if (is_end || itkey.size() < prefix.size() || std::char_traits<char>::compare(prefix.data(), itkey.data(), prefix.size()) != 0) { is_end = true; data = lmdb::Val{}; suffix = std::string(); return; } suffix = std::string(itkey.data() + prefix.size(), itkey.size() - prefix.size()); } std::string DBlmdb::Cursor::get_value_string() const { return std::string(data.data(), data.size()); } common::BinaryArray DBlmdb::Cursor::get_value_array() const { return common::BinaryArray(data.data(), data.data() + data.size()); } DBlmdb::Cursor DBlmdb::begin(const std::string &prefix, const std::string &middle) const { int max_key_size = ::mdb_env_get_maxkeysize(db_env.handle); return Cursor(lmdb::Cur(*db_txn, *db_dbi), prefix, middle, max_key_size, true); } DBlmdb::Cursor DBlmdb::rbegin(const std::string &prefix, const std::string &middle) const { int max_key_size = ::mdb_env_get_maxkeysize(db_env.handle); return Cursor(lmdb::Cur(*db_txn, *db_dbi), prefix, middle, max_key_size, false); } void DBlmdb::commit_db_txn() { db_txn->commit(); db_txn.reset(); db_txn.reset(new lmdb::Txn(db_env)); } void DBlmdb::put(const std::string &key, const common::BinaryArray &value, bool nooverwrite) { lmdb::Val temp_value(value.data(), value.size()); const int rc = ::mdb_put(db_txn->handle, db_dbi->handle, lmdb::Val(key), temp_value, nooverwrite ? MDB_NOOVERWRITE : 0); if (rc != MDB_SUCCESS && rc != MDB_KEYEXIST) throw lmdb::Error("DBlmdb::put failed " + std::string(key.data(), key.size())); if (nooverwrite && rc == MDB_KEYEXIST) throw lmdb::Error( "DBlmdb::put failed or nooverwrite key already exists " + std::string(key.data(), key.size())); } void DBlmdb::put(const std::string &key, const std::string &value, bool nooverwrite) { lmdb::Val temp_value(value.data(), value.size()); const int rc = ::mdb_put(db_txn->handle, db_dbi->handle, lmdb::Val(key), temp_value, nooverwrite ? MDB_NOOVERWRITE : 0); if (rc != MDB_SUCCESS && rc != MDB_KEYEXIST) throw lmdb::Error("DBlmdb::put failed " + std::string(key.data(), key.size())); if (nooverwrite && rc == MDB_KEYEXIST) throw lmdb::Error( "DBlmdb::put failed or nooverwrite key already exists " + std::string(key.data(), key.size())); } bool DBlmdb::get(const std::string &key, common::BinaryArray &value) const { lmdb::Val val1; if (!db_dbi->get(*db_txn, lmdb::Val(key), val1)) return false; value.assign(val1.data(), val1.data() + val1.size()); return true; } bool DBlmdb::get(const std::string &key, std::string &value) const { lmdb::Val val1; if (!db_dbi->get(*db_txn, lmdb::Val(key), val1)) return false; value = std::string(val1.data(), val1.size()); return true; } bool DBlmdb::get(const std::string &key, Value &value) const { return db_dbi->get(*db_txn, lmdb::Val(key), value); } void DBlmdb::del(const std::string &key, bool mustexist) { const int rc = ::mdb_del(db_txn->handle, db_dbi->handle, lmdb::Val(key), nullptr); if (rc != MDB_SUCCESS && rc != MDB_NOTFOUND) throw lmdb::Error("DBlmdb::del failed " + std::string(key.data(), key.size())); if (mustexist && rc == MDB_NOTFOUND) // Soemtimes lmdb returns 0 for non existing keys, we have to get our own check upwards throw lmdb::Error("DBlmdb::del key does not exist " + std::string(key.data(), key.size())); } std::string DBlmdb::to_ascending_key(uint32_t key) { char buf[32] = {}; sprintf(buf, "%08X", key); return std::string(buf); } uint32_t DBlmdb::from_ascending_key(const std::string &key) { return boost::lexical_cast<uint32_t>(std::stoull(key, nullptr, 16)); } std::string DBlmdb::clean_key(const std::string &key) { std::string result = key; for (char &ch : result) { unsigned char uch = ch; if (uch >= 128) uch -= 128; if (uch == 127) uch = 'F'; if (uch < 32) uch = '0' + uch; ch = uch; } return result; } void DBlmdb::delete_db(const std::string &path) { std::remove((path + "/data.mdb").c_str()); std::remove((path + "/lock.mdb").c_str()); std::remove(path.c_str()); } void DBlmdb::run_tests() { delete_db("temp_db"); { DBlmdb db("temp_db"); db.put("history/ha", "ua", false); db.put("history/hb", "ub", false); db.put("history/hc", "uc", false); db.put("unspent/ua", "ua", false); db.put("unspent/ub", "ub", false); db.put("unspent/uc", "uc", false); std::cout << "-- all keys forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- all keys backward --" << std::endl; for (auto cur = db.rbegin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- history forward --" << std::endl; for (auto cur = db.begin("history/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- history backward --" << std::endl; for (auto cur = db.rbegin("history/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- unspent forward --" << std::endl; for (auto cur = db.begin("unspent/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- unspent backward --" << std::endl; for (auto cur = db.rbegin("unspent/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- alpha forward --" << std::endl; for (auto cur = db.begin("alpha/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- alpha backward --" << std::endl; for (auto cur = db.rbegin("alpha/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- zero forward --" << std::endl; for (auto cur = db.begin("zero/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } std::cout << "-- zero backward --" << std::endl; for (auto cur = db.rbegin("zero/"); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } int c = 0; std::cout << "-- deleting c=2 iterating forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); ++c) { if (c == 2) { std::cout << "deleting " << cur.get_suffix() << std::endl; cur.erase(); } else { std::cout << cur.get_suffix() << std::endl; cur.next(); } } std::cout << "-- all keys forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } c = 0; std::cout << "-- deleting c=2 iterating backward --" << std::endl; for (auto cur = db.rbegin(std::string()); !cur.end(); ++c) { if (c == 2) { std::cout << "deleting " << cur.get_suffix() << std::endl; cur.erase(); } else { std::cout << cur.get_suffix() << std::endl; cur.next(); } } std::cout << "-- all keys forward --" << std::endl; for (auto cur = db.begin(std::string()); !cur.end(); cur.next()) { std::cout << cur.get_suffix() << std::endl; } } delete_db("temp_db"); }
11,430
4,775
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/dynamodb/model/AutoScalingSettingsDescription.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace DynamoDB { namespace Model { AutoScalingSettingsDescription::AutoScalingSettingsDescription() : m_minimumUnits(0), m_minimumUnitsHasBeenSet(false), m_maximumUnits(0), m_maximumUnitsHasBeenSet(false), m_autoScalingDisabled(false), m_autoScalingDisabledHasBeenSet(false), m_autoScalingRoleArnHasBeenSet(false), m_scalingPoliciesHasBeenSet(false) { } AutoScalingSettingsDescription::AutoScalingSettingsDescription(JsonView jsonValue) : m_minimumUnits(0), m_minimumUnitsHasBeenSet(false), m_maximumUnits(0), m_maximumUnitsHasBeenSet(false), m_autoScalingDisabled(false), m_autoScalingDisabledHasBeenSet(false), m_autoScalingRoleArnHasBeenSet(false), m_scalingPoliciesHasBeenSet(false) { *this = jsonValue; } AutoScalingSettingsDescription& AutoScalingSettingsDescription::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("MinimumUnits")) { m_minimumUnits = jsonValue.GetInt64("MinimumUnits"); m_minimumUnitsHasBeenSet = true; } if(jsonValue.ValueExists("MaximumUnits")) { m_maximumUnits = jsonValue.GetInt64("MaximumUnits"); m_maximumUnitsHasBeenSet = true; } if(jsonValue.ValueExists("AutoScalingDisabled")) { m_autoScalingDisabled = jsonValue.GetBool("AutoScalingDisabled"); m_autoScalingDisabledHasBeenSet = true; } if(jsonValue.ValueExists("AutoScalingRoleArn")) { m_autoScalingRoleArn = jsonValue.GetString("AutoScalingRoleArn"); m_autoScalingRoleArnHasBeenSet = true; } if(jsonValue.ValueExists("ScalingPolicies")) { Array<JsonView> scalingPoliciesJsonList = jsonValue.GetArray("ScalingPolicies"); for(unsigned scalingPoliciesIndex = 0; scalingPoliciesIndex < scalingPoliciesJsonList.GetLength(); ++scalingPoliciesIndex) { m_scalingPolicies.push_back(scalingPoliciesJsonList[scalingPoliciesIndex].AsObject()); } m_scalingPoliciesHasBeenSet = true; } return *this; } JsonValue AutoScalingSettingsDescription::Jsonize() const { JsonValue payload; if(m_minimumUnitsHasBeenSet) { payload.WithInt64("MinimumUnits", m_minimumUnits); } if(m_maximumUnitsHasBeenSet) { payload.WithInt64("MaximumUnits", m_maximumUnits); } if(m_autoScalingDisabledHasBeenSet) { payload.WithBool("AutoScalingDisabled", m_autoScalingDisabled); } if(m_autoScalingRoleArnHasBeenSet) { payload.WithString("AutoScalingRoleArn", m_autoScalingRoleArn); } if(m_scalingPoliciesHasBeenSet) { Array<JsonValue> scalingPoliciesJsonList(m_scalingPolicies.size()); for(unsigned scalingPoliciesIndex = 0; scalingPoliciesIndex < scalingPoliciesJsonList.GetLength(); ++scalingPoliciesIndex) { scalingPoliciesJsonList[scalingPoliciesIndex].AsObject(m_scalingPolicies[scalingPoliciesIndex].Jsonize()); } payload.WithArray("ScalingPolicies", std::move(scalingPoliciesJsonList)); } return payload; } } // namespace Model } // namespace DynamoDB } // namespace Aws
3,315
1,213
#include "AdcNode.hpp" extern int __get_adc_mode(); /** * TODO: * * manage status topic: isnan(ESP.getVcc()) => setProperty(cStatusTopic).send("error") * note: check what happen when no wire is connected to ADC pin */ AdcNode::AdcNode(const char *id, const char *name, uint32_t readInterval, float sendOnChangeAbs, const SensorBase<float>::ReadMeasurementFunc &readMeasurementFunc, const SensorBase<float>::SendMeasurementFunc &sendMeasurementFunc, const SensorBase<float>::OnChangeFunc &onChangeFunc) : BaseNode(id, name, "adc"), SensorBase(id, readInterval, 0, sendOnChangeAbs, readMeasurementFunc, sendMeasurementFunc, onChangeFunc) { // ADC pin used to measure VCC (e.g. on battery) // true if previously called macro ADC_MODE(ADC_VCC) mReadVcc = __get_adc_mode() == ADC_VCC; } void AdcNode::setup() { advertise(SensorBase::getName()) .setDatatype("float") .setFormat("0:1.00") .setUnit(cUnitVolt); } void AdcNode::loop() { SensorBase::loop(); } float AdcNode::readMeasurement() { if (mReadMeasurementFunc) { return mReadMeasurementFunc(); } return static_cast<float>(mReadVcc ? ESP.getVcc() : analogRead(A0)) / 1024.0f; } void AdcNode::sendMeasurement(float value) const { if (mSendMeasurementFunc) { return mSendMeasurementFunc(value); } if (Homie.isConnected()) { setProperty(SensorBase::getName()).send(String(value)); } }
1,578
530
//===- Timing.cpp - Execution time measurement facilities -----------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Facilities to measure and provide statistics on execution time. // //===----------------------------------------------------------------------===// #include "mlir/Support/Timing.h" #include "mlir/Support/ThreadLocalCache.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Format.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/RWMutex.h" #include "llvm/Support/Threading.h" #include "llvm/Support/raw_ostream.h" #include <atomic> #include <chrono> using namespace mlir; using namespace detail; using DisplayMode = DefaultTimingManager::DisplayMode; constexpr llvm::StringLiteral kTimingDescription = "... Execution time report ..."; //===----------------------------------------------------------------------===// // TimingManager //===----------------------------------------------------------------------===// namespace mlir { namespace detail { /// Private implementation details of the `TimingManager`. class TimingManagerImpl { public: // Identifier allocator, map, and mutex for thread safety. llvm::BumpPtrAllocator identifierAllocator; llvm::StringSet<llvm::BumpPtrAllocator &> identifiers; llvm::sys::SmartRWMutex<true> identifierMutex; /// A thread local cache of identifiers to reduce lock contention. ThreadLocalCache<llvm::StringMap<llvm::StringMapEntry<llvm::NoneType> *>> localIdentifierCache; TimingManagerImpl() : identifiers(identifierAllocator) {} }; } // namespace detail } // namespace mlir TimingManager::TimingManager() : impl(std::make_unique<TimingManagerImpl>()) {} TimingManager::~TimingManager() {} /// Get the root timer of this timing manager. Timer TimingManager::getRootTimer() { auto rt = rootTimer(); return rt.hasValue() ? Timer(*this, rt.getValue()) : Timer(); } /// Get the root timer of this timing manager wrapped in a `TimingScope`. TimingScope TimingManager::getRootScope() { return TimingScope(getRootTimer()); } //===----------------------------------------------------------------------===// // Identifier uniquing //===----------------------------------------------------------------------===// /// Return an identifier for the specified string. TimingIdentifier TimingIdentifier::get(StringRef str, TimingManager &tm) { // Check for an existing instance in the local cache. auto &impl = *tm.impl; auto *&localEntry = (*impl.localIdentifierCache)[str]; if (localEntry) return TimingIdentifier(localEntry); // Check for an existing identifier in read-only mode. { llvm::sys::SmartScopedReader<true> contextLock(impl.identifierMutex); auto it = impl.identifiers.find(str); if (it != impl.identifiers.end()) { localEntry = &*it; return TimingIdentifier(localEntry); } } // Acquire a writer-lock so that we can safely create the new instance. llvm::sys::SmartScopedWriter<true> contextLock(impl.identifierMutex); auto it = impl.identifiers.insert(str).first; localEntry = &*it; return TimingIdentifier(localEntry); } //===----------------------------------------------------------------------===// // Helpers for time record printing //===----------------------------------------------------------------------===// namespace { /// Simple record class to record timing information. struct TimeRecord { TimeRecord(double wall = 0.0, double user = 0.0) : wall(wall), user(user) {} TimeRecord &operator+=(const TimeRecord &other) { wall += other.wall; user += other.user; return *this; } TimeRecord &operator-=(const TimeRecord &other) { wall -= other.wall; user -= other.user; return *this; } /// Print the current time record to 'os', with a breakdown showing /// contributions to the give 'total' time record. void print(raw_ostream &os, const TimeRecord &total) { if (total.user != total.wall) os << llvm::format(" %8.4f (%5.1f%%)", user, 100.0 * user / total.user); os << llvm::format(" %8.4f (%5.1f%%) ", wall, 100.0 * wall / total.wall); } double wall, user; }; } // namespace /// Utility to print a single line entry in the timer output. static void printTimeEntry(raw_ostream &os, unsigned indent, StringRef name, TimeRecord time, TimeRecord total) { time.print(os, total); os.indent(indent) << name << "\n"; } /// Utility to print the timer heading information. static void printTimeHeader(raw_ostream &os, TimeRecord total) { // Figure out how many spaces to description name. unsigned padding = (80 - kTimingDescription.size()) / 2; os << "===" << std::string(73, '-') << "===\n"; os.indent(padding) << kTimingDescription << '\n'; os << "===" << std::string(73, '-') << "===\n"; // Print the total time followed by the section headers. os << llvm::format(" Total Execution Time: %.4f seconds\n\n", total.wall); if (total.user != total.wall) os << " ----User Time----"; os << " ----Wall Time---- ----Name----\n"; } //===----------------------------------------------------------------------===// // Timer Implementation for DefaultTimingManager //===----------------------------------------------------------------------===// namespace { /// A timer used to sample execution time. /// /// Separately tracks wall time and user time to account for parallel threads of /// execution. Timers are intended to be started and stopped multiple times. /// Each start and stop will add to the timer's wall and user time. class TimerImpl { public: using ChildrenMap = llvm::MapVector<const void *, std::unique_ptr<TimerImpl>>; using AsyncChildrenMap = llvm::DenseMap<uint64_t, ChildrenMap>; TimerImpl(std::string &&name) : threadId(llvm::get_threadid()), name(name) {} /// Start the timer. void start() { startTime = std::chrono::steady_clock::now(); } /// Stop the timer. void stop() { auto newTime = std::chrono::steady_clock::now() - startTime; wallTime += newTime; userTime += newTime; } /// Create a child timer nested within this one. Multiple calls to this /// function with the same unique identifier `id` will return the same child /// timer. /// /// This function can be called from other threads, as long as this timer /// outlives any uses of the child timer on the other thread. TimerImpl *nest(const void *id, function_ref<std::string()> nameBuilder) { auto tid = llvm::get_threadid(); if (tid == threadId) return nestTail(children[id], std::move(nameBuilder)); std::unique_lock<std::mutex> lock(asyncMutex); return nestTail(asyncChildren[tid][id], std::move(nameBuilder)); } /// Tail-called from `nest()`. TimerImpl *nestTail(std::unique_ptr<TimerImpl> &child, function_ref<std::string()> nameBuilder) { if (!child) child = std::make_unique<TimerImpl>(nameBuilder()); return child.get(); } /// Finalize this timer and all its children. /// /// If this timer has async children, which happens if `nest()` was called /// from another thread, this function merges the async childr timers into the /// main list of child timers. /// /// Caution: Call this function only after all nested timers running on other /// threads no longer need their timers! void finalize() { addAsyncUserTime(); mergeAsyncChildren(); } /// Add the user time of all async children to this timer's user time. This is /// necessary since the user time already contains all regular child timers, /// but not the asynchronous ones (by the nesting nature of the timers). std::chrono::nanoseconds addAsyncUserTime() { auto added = std::chrono::nanoseconds(0); for (auto &child : children) added += child.second->addAsyncUserTime(); for (auto &thread : asyncChildren) { for (auto &child : thread.second) { child.second->addAsyncUserTime(); added += child.second->userTime; } } userTime += added; return added; } /// Ensure that this timer and recursively all its children have their async /// children folded into the main map of children. void mergeAsyncChildren() { for (auto &child : children) child.second->mergeAsyncChildren(); mergeChildren(std::move(asyncChildren)); assert(asyncChildren.empty()); } /// Merge multiple child timers into this timer. /// /// Children in `other` are added as children to this timer, or, if this timer /// already contains a child with the corresponding unique identifier, are /// merged into the existing child. void mergeChildren(ChildrenMap &&other) { if (children.empty()) { children = std::move(other); for (auto &child : children) child.second->mergeAsyncChildren(); } else { for (auto &child : other) mergeChild(child.first, std::move(child.second)); other.clear(); } } /// See above. void mergeChildren(AsyncChildrenMap &&other) { for (auto &thread : other) { mergeChildren(std::move(thread.second)); assert(thread.second.empty()); } other.clear(); } /// Merge a child timer into this timer for a given unique identifier. /// /// Moves all child and async child timers of `other` into this timer's child /// for the given unique identifier. void mergeChild(const void *id, std::unique_ptr<TimerImpl> &&other) { auto &into = children[id]; if (!into) { into = std::move(other); into->mergeAsyncChildren(); } else { into->wallTime = std::max(into->wallTime, other->wallTime); into->userTime += other->userTime; into->mergeChildren(std::move(other->children)); into->mergeChildren(std::move(other->asyncChildren)); other.reset(); } } /// Dump a human-readable tree representation of the timer and its children. /// This is useful for debugging the timing mechanisms and structure of the /// timers. void dump(raw_ostream &os, unsigned indent = 0, unsigned markThreadId = 0) { auto time = getTimeRecord(); os << std::string(indent * 2, ' ') << name << " [" << threadId << "]" << llvm::format(" %7.4f / %7.4f", time.user, time.wall); if (threadId != markThreadId && markThreadId != 0) os << " (*)"; os << "\n"; for (auto &child : children) child.second->dump(os, indent + 1, threadId); for (auto &thread : asyncChildren) for (auto &child : thread.second) child.second->dump(os, indent + 1, threadId); } /// Returns the time for this timer in seconds. TimeRecord getTimeRecord() { return TimeRecord( std::chrono::duration_cast<std::chrono::duration<double>>(wallTime) .count(), std::chrono::duration_cast<std::chrono::duration<double>>(userTime) .count()); } /// Print the timing result in list mode. void printAsList(raw_ostream &os, TimeRecord total) { // Flatten the leaf timers in the tree and merge them by name. llvm::StringMap<TimeRecord> mergedTimers; std::function<void(TimerImpl *)> addTimer = [&](TimerImpl *timer) { mergedTimers[timer->name] += timer->getTimeRecord(); for (auto &children : timer->children) addTimer(children.second.get()); }; addTimer(this); // Sort the timing information by wall time. std::vector<std::pair<StringRef, TimeRecord>> timerNameAndTime; for (auto &it : mergedTimers) timerNameAndTime.emplace_back(it.first(), it.second); llvm::array_pod_sort(timerNameAndTime.begin(), timerNameAndTime.end(), [](const std::pair<StringRef, TimeRecord> *lhs, const std::pair<StringRef, TimeRecord> *rhs) { return llvm::array_pod_sort_comparator<double>( &rhs->second.wall, &lhs->second.wall); }); // Print the timing information sequentially. for (auto &timeData : timerNameAndTime) printTimeEntry(os, 0, timeData.first, timeData.second, total); } /// Print the timing result in tree mode. void printAsTree(raw_ostream &os, TimeRecord total, unsigned indent = 0) { unsigned childIndent = indent; if (!hidden) { printTimeEntry(os, indent, name, getTimeRecord(), total); childIndent += 2; } for (auto &child : children) { child.second->printAsTree(os, total, childIndent); } } /// Print the current timing information. void print(raw_ostream &os, DisplayMode displayMode) { // Print the banner. auto total = getTimeRecord(); printTimeHeader(os, total); // Defer to a specialized printer for each display mode. switch (displayMode) { case DisplayMode::List: printAsList(os, total); break; case DisplayMode::Tree: printAsTree(os, total); break; } // Print the top-level time not accounted for by child timers, and the // total. auto rest = total; for (auto &child : children) rest -= child.second->getTimeRecord(); printTimeEntry(os, 0, "Rest", rest, total); printTimeEntry(os, 0, "Total", total, total); os.flush(); } /// The last time instant at which the timer was started. std::chrono::time_point<std::chrono::steady_clock> startTime; /// Accumulated wall time. If multiple threads of execution are merged into /// this timer, the wall time will hold the maximum wall time of each thread /// of execution. std::chrono::nanoseconds wallTime = std::chrono::nanoseconds(0); /// Accumulated user time. If multiple threads of execution are merged into /// this timer, each thread's user time is added here. std::chrono::nanoseconds userTime = std::chrono::nanoseconds(0); /// The thread on which this timer is running. uint64_t threadId; /// A descriptive name for this timer. std::string name; /// Whether to omit this timer from reports and directly show its children. bool hidden = false; /// Child timers on the same thread the timer itself. We keep at most one /// timer per unique identifier. ChildrenMap children; /// Child timers on other threads. We keep at most one timer per unique /// identifier. AsyncChildrenMap asyncChildren; /// Mutex for the async children. std::mutex asyncMutex; }; } // namespace //===----------------------------------------------------------------------===// // DefaultTimingManager //===----------------------------------------------------------------------===// namespace mlir { namespace detail { /// Implementation details of the `DefaultTimingManager`. class DefaultTimingManagerImpl { public: /// Whether we should do our work or not. bool enabled = false; /// The configured display mode. DisplayMode displayMode = DisplayMode::Tree; /// The stream where we should print our output. This will always be non-null. raw_ostream *output = &llvm::errs(); /// The root timer. std::unique_ptr<TimerImpl> rootTimer; }; } // namespace detail } // namespace mlir DefaultTimingManager::DefaultTimingManager() : impl(std::make_unique<DefaultTimingManagerImpl>()) { clear(); // initializes the root timer } DefaultTimingManager::~DefaultTimingManager() { print(); } /// Enable or disable execution time sampling. void DefaultTimingManager::setEnabled(bool enabled) { impl->enabled = enabled; } /// Return whether execution time sampling is enabled. bool DefaultTimingManager::isEnabled() const { return impl->enabled; } /// Change the display mode. void DefaultTimingManager::setDisplayMode(DisplayMode displayMode) { impl->displayMode = displayMode; } /// Return the current display mode; DefaultTimingManager::DisplayMode DefaultTimingManager::getDisplayMode() const { return impl->displayMode; } /// Change the stream where the output will be printed to. void DefaultTimingManager::setOutput(raw_ostream &os) { impl->output = &os; } /// Return the current output stream where the output will be printed to. raw_ostream &DefaultTimingManager::getOutput() const { assert(impl->output); return *impl->output; } /// Print and clear the timing results. void DefaultTimingManager::print() { if (impl->enabled) { impl->rootTimer->finalize(); impl->rootTimer->print(*impl->output, impl->displayMode); } clear(); } /// Clear the timing results. void DefaultTimingManager::clear() { impl->rootTimer = std::make_unique<TimerImpl>("root"); impl->rootTimer->hidden = true; } /// Debug print the timer data structures to an output stream. void DefaultTimingManager::dumpTimers(raw_ostream &os) { impl->rootTimer->dump(os); } /// Debug print the timers as a list. void DefaultTimingManager::dumpAsList(raw_ostream &os) { impl->rootTimer->finalize(); impl->rootTimer->print(os, DisplayMode::List); } /// Debug print the timers as a tree. void DefaultTimingManager::dumpAsTree(raw_ostream &os) { impl->rootTimer->finalize(); impl->rootTimer->print(os, DisplayMode::Tree); } Optional<void *> DefaultTimingManager::rootTimer() { if (impl->enabled) return impl->rootTimer.get(); return llvm::None; } void DefaultTimingManager::startTimer(void *handle) { static_cast<TimerImpl *>(handle)->start(); } void DefaultTimingManager::stopTimer(void *handle) { static_cast<TimerImpl *>(handle)->stop(); } void *DefaultTimingManager::nestTimer(void *handle, const void *id, function_ref<std::string()> nameBuilder) { return static_cast<TimerImpl *>(handle)->nest(id, std::move(nameBuilder)); } void DefaultTimingManager::hideTimer(void *handle) { static_cast<TimerImpl *>(handle)->hidden = true; } //===----------------------------------------------------------------------===// // DefaultTimingManager Command Line Options //===----------------------------------------------------------------------===// namespace { struct DefaultTimingManagerOptions { llvm::cl::opt<bool> timing{"mlir-timing", llvm::cl::desc("Display execution times"), llvm::cl::init(false)}; llvm::cl::opt<DisplayMode> displayMode{ "mlir-timing-display", llvm::cl::desc("Display method for timing data"), llvm::cl::init(DisplayMode::Tree), llvm::cl::values( clEnumValN(DisplayMode::List, "list", "display the results in a list sorted by total time"), clEnumValN(DisplayMode::Tree, "tree", "display the results ina with a nested tree view"))}; }; } // end anonymous namespace static llvm::ManagedStatic<DefaultTimingManagerOptions> options; void mlir::registerDefaultTimingManagerCLOptions() { // Make sure that the options struct has been constructed. *options; } void mlir::applyDefaultTimingManagerCLOptions(DefaultTimingManager &tm) { if (!options.isConstructed()) return; tm.setEnabled(options->timing); tm.setDisplayMode(options->displayMode); }
19,394
5,619
// 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 <stout/lambda.hpp> #include <stout/numify.hpp> struct OnlyMoveable { OnlyMoveable() : i(-1) {} OnlyMoveable(int i) : i(i) {} OnlyMoveable(OnlyMoveable&& that) { *this = std::move(that); } OnlyMoveable(const OnlyMoveable&) = delete; OnlyMoveable& operator=(OnlyMoveable&& that) { i = that.i; j = that.j; that.valid = false; return *this; } OnlyMoveable& operator=(const OnlyMoveable&) = delete; int i; int j = 0; bool valid = true; }; std::vector<std::string> function() { return {"1", "2", "3"}; } TEST(LambdaTest, Map) { std::vector<int> expected = {1, 2, 3}; EXPECT_EQ( expected, lambda::map( [](std::string s) { return numify<int>(s).get(); }, std::vector<std::string>{"1", "2", "3"})); EXPECT_EQ( expected, lambda::map( [](const std::string& s) { return numify<int>(s).get(); }, std::vector<std::string>{"1", "2", "3"})); EXPECT_EQ( expected, lambda::map( [](std::string&& s) { return numify<int>(s).get(); }, std::vector<std::string>{"1", "2", "3"})); std::vector<std::string> concat = {"11", "22", "33"}; EXPECT_EQ( concat, lambda::map( [](std::string&& s) { return s + s; }, function())); std::vector<OnlyMoveable> v; v.emplace_back(1); v.emplace_back(2); std::vector<OnlyMoveable> result = lambda::map( [](OnlyMoveable&& o) { o.j = o.i; return std::move(o); }, std::move(v)); for (const OnlyMoveable& o : result) { EXPECT_EQ(o.i, o.j); } } namespace { template <typename F, typename ...Args> auto callable(F&& f, Args&&... args) -> decltype(std::forward<F>(f)(std::forward<Args>(args)...), void(), std::true_type()); template <typename F> std::false_type callable(F&& f, ...); // Compile-time check that f cannot be called with specified arguments. // This is implemented by defining two callable function overloads and // differentiating on return type. The first overload is selected only // when call expression is valid, and it has return type of std::true_type, // while second overload is selected for everything else. template <typename F, typename ...Args> void EXPECT_CALL_INVALID(F&& f, Args&&... args) { static_assert( !decltype( callable(std::forward<F>(f), std::forward<Args>(args)...))::value, "call expression is expected to be invalid"); } } // namespace { namespace { int returnIntNoParams() { return 8; } void returnVoidStringParam(std::string s) {} void returnVoidStringCRefParam(const std::string& s) {} int returnIntOnlyMovableParam(OnlyMoveable o) { EXPECT_TRUE(o.valid); return 1; } } // namespace { // This is mostly a compile time test of lambda::partial, // verifying that it works for different types of expressions. TEST(PartialTest, Test) { // standalone functions auto p1 = lambda::partial(returnIntNoParams); int p1r1 = p1(); int p1r2 = std::move(p1)(); EXPECT_EQ(p1r1, p1r2); auto p2 = lambda::partial(returnVoidStringParam, ""); p2(); std::move(p2)(); auto p3 = lambda::partial(returnVoidStringParam, lambda::_1); p3(""); std::move(p3)(""); auto p4 = lambda::partial(&returnVoidStringCRefParam, lambda::_1); p4(""); std::move(p4)(""); auto p5 = lambda::partial(&returnIntOnlyMovableParam, lambda::_1); p5(OnlyMoveable()); p5(10); std::move(p5)(OnlyMoveable()); auto p6 = lambda::partial(&returnIntOnlyMovableParam, OnlyMoveable()); EXPECT_CALL_INVALID(p6); std::move(p6)(); // lambdas auto l1 = [](const OnlyMoveable& m) { EXPECT_TRUE(m.valid); }; auto pl1 = lambda::partial(l1, OnlyMoveable()); pl1(); pl1(); std::move(pl1)(); auto pl2 = lambda::partial([](OnlyMoveable&& m) { EXPECT_TRUE(m.valid); }, lambda::_1); pl2(OnlyMoveable()); pl2(OnlyMoveable()); std::move(pl2)(OnlyMoveable()); auto pl3 = lambda::partial([](OnlyMoveable&& m) { EXPECT_TRUE(m.valid); }, OnlyMoveable()); EXPECT_CALL_INVALID(pl3); std::move(pl3)(); // member functions struct Object { int method() { return 0; }; }; auto mp1 = lambda::partial(&Object::method, lambda::_1); mp1(Object()); std::move(mp1)(Object()); auto mp2 = lambda::partial(&Object::method, Object()); mp2(); std::move(mp2)(); }
5,049
1,812
/*------------------------------------------------------------------------- * drawElements Quality Program OpenGL ES 3.0 Module * ------------------------------------------------- * * Copyright 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Sync tests. *//*--------------------------------------------------------------------*/ #include "es3fSyncTests.hpp" #include "tcuTestLog.hpp" #include "tcuVector.hpp" #include "gluShaderProgram.hpp" #include "gluCallLogWrapper.hpp" #include "gluRenderContext.hpp" #include "glwEnums.hpp" #include "deRandom.hpp" #include "deStringUtil.hpp" #include "deString.h" #include <vector> using tcu::TestLog; namespace deqp { namespace gles3 { namespace Functional { using namespace glw; // GL types static const int NUM_CASE_ITERATIONS = 5; enum WaitCommand { COMMAND_WAIT_SYNC = 1 << 0, COMMAND_CLIENT_WAIT_SYNC = 1 << 1 }; enum CaseOptions { CASE_FLUSH_BEFORE_WAIT = 1 << 0, CASE_FINISH_BEFORE_WAIT = 1 << 1 }; class FenceSyncCase : public TestCase, private glu::CallLogWrapper { public: FenceSyncCase (Context& context, const char* name, const char* description, int numPrimitives, deUint32 waitCommand, deUint32 waitFlags, deUint64 timeout, deUint32 options); ~FenceSyncCase (void); void init (void); void deinit (void); IterateResult iterate (void); private: FenceSyncCase (const FenceSyncCase& other); FenceSyncCase& operator= (const FenceSyncCase& other); int m_numPrimitives; deUint32 m_waitCommand; deUint32 m_waitFlags; deUint64 m_timeout; deUint32 m_caseOptions; glu::ShaderProgram* m_program; GLsync m_syncObject; int m_iterNdx; de::Random m_rnd; }; FenceSyncCase::FenceSyncCase (Context& context, const char* name, const char* description, int numPrimitives, deUint32 waitCommand, deUint32 waitFlags, deUint64 timeout, deUint32 options) : TestCase (context, name, description) , CallLogWrapper (context.getRenderContext().getFunctions(), context.getTestContext().getLog()) , m_numPrimitives (numPrimitives) , m_waitCommand (waitCommand) , m_waitFlags (waitFlags) , m_timeout (timeout) , m_caseOptions (options) , m_program (DE_NULL) , m_syncObject (DE_NULL) , m_iterNdx (0) , m_rnd (deStringHash(name)) { } FenceSyncCase::~FenceSyncCase (void) { FenceSyncCase::deinit(); } static void generateVertices (std::vector<float>& dst, int numPrimitives, de::Random& rnd) { int numVertices = 3*numPrimitives; dst.resize(numVertices * 4); for (int i = 0; i < numVertices; i++) { dst[i*4 ] = rnd.getFloat(-1.0f, 1.0f); // x dst[i*4 + 1] = rnd.getFloat(-1.0f, 1.0f); // y dst[i*4 + 2] = rnd.getFloat( 0.0f, 1.0f); // z dst[i*4 + 3] = 1.0f; // w } } void FenceSyncCase::init (void) { const char* vertShaderSource = "#version 300 es\n" "layout(location = 0) in mediump vec4 a_position;\n" "\n" "void main (void)\n" "{\n" " gl_Position = a_position;\n" "}\n"; const char* fragShaderSource = "#version 300 es\n" "layout(location = 0) out mediump vec4 o_color;\n" "\n" "void main (void)\n" "{\n" " o_color = vec4(0.25, 0.5, 0.75, 1.0);\n" "}\n"; DE_ASSERT(!m_program); m_program = new glu::ShaderProgram(m_context.getRenderContext(), glu::makeVtxFragSources(vertShaderSource, fragShaderSource)); if (!m_program->isOk()) { m_testCtx.getLog() << *m_program; TCU_FAIL("Failed to compile shader program"); } m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "Pass"); // Initialize test result to pass. GLU_CHECK_MSG("Case initialization finished"); } void FenceSyncCase::deinit (void) { if (m_program) { delete m_program; m_program = DE_NULL; } if (m_syncObject) { glDeleteSync(m_syncObject); m_syncObject = DE_NULL; } } FenceSyncCase::IterateResult FenceSyncCase::iterate (void) { TestLog& log = m_testCtx.getLog(); std::vector<float> vertices; bool testOk = true; std::string header = "Case iteration " + de::toString(m_iterNdx+1) + " / " + de::toString(NUM_CASE_ITERATIONS); log << TestLog::Section(header, header); enableLogging(true); DE_ASSERT (m_program); glUseProgram (m_program->getProgram()); glEnable (GL_DEPTH_TEST); glClearColor (0.3f, 0.3f, 0.3f, 1.0f); glClearDepthf (1.0f); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Generate vertices glEnableVertexAttribArray (0); generateVertices (vertices, m_numPrimitives, m_rnd); glVertexAttribPointer (0, 4, GL_FLOAT, GL_FALSE, 0, &vertices[0]); // Draw glDrawArrays(GL_TRIANGLES, 0, (int)vertices.size() / 4); log << TestLog::Message << "// Primitives drawn." << TestLog::EndMessage; // Create sync object m_syncObject = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); GLU_CHECK_MSG ("Sync object created"); log << TestLog::Message << "// Sync object created." << TestLog::EndMessage; if (m_caseOptions & CASE_FLUSH_BEFORE_WAIT) glFlush(); if (m_caseOptions & CASE_FINISH_BEFORE_WAIT) glFinish(); // Wait for sync object GLenum waitValue = 0; if (m_waitCommand & COMMAND_WAIT_SYNC) { DE_ASSERT(m_timeout == GL_TIMEOUT_IGNORED); DE_ASSERT(m_waitFlags == 0); glWaitSync(m_syncObject, m_waitFlags, m_timeout); GLU_CHECK_MSG ("glWaitSync called"); log << TestLog::Message << "// Wait command glWaitSync called with GL_TIMEOUT_IGNORED." << TestLog::EndMessage; } if (m_waitCommand & COMMAND_CLIENT_WAIT_SYNC) { waitValue = glClientWaitSync(m_syncObject, m_waitFlags, m_timeout); GLU_CHECK_MSG ("glClientWaitSync called"); log << TestLog::Message << "// glClientWaitSync return value:" << TestLog::EndMessage; switch (waitValue) { case GL_ALREADY_SIGNALED: log << TestLog::Message << "// GL_ALREADY_SIGNALED" << TestLog::EndMessage; break; case GL_TIMEOUT_EXPIRED: log << TestLog::Message << "// GL_TIMEOUT_EXPIRED" << TestLog::EndMessage; break; case GL_CONDITION_SATISFIED: log << TestLog::Message << "// GL_CONDITION_SATISFIED" << TestLog::EndMessage; break; case GL_WAIT_FAILED: log << TestLog::Message << "// GL_WAIT_FAILED" << TestLog::EndMessage; testOk = false; break; default: log << TestLog::EndSection; TCU_FAIL("// Illegal return value!"); } } glFinish(); if (m_caseOptions & CASE_FINISH_BEFORE_WAIT && waitValue != GL_ALREADY_SIGNALED) { testOk = false; log << TestLog::Message << "// Expected glClientWaitSync to return GL_ALREADY_SIGNALED." << TestLog::EndMessage; } // Delete sync object if (m_syncObject) { glDeleteSync(m_syncObject); m_syncObject = DE_NULL; GLU_CHECK_MSG ("Sync object deleted"); log << TestLog::Message << "// Sync object deleted." << TestLog::EndMessage; } // Evaluate test result log << TestLog::Message << "// Test result: " << (testOk ? "Passed!" : "Failed!") << TestLog::EndMessage; if (!testOk) { m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Fail"); log << TestLog::EndSection; return STOP; } log << TestLog::Message << "// Sync objects created and deleted successfully." << TestLog::EndMessage << TestLog::EndSection; return (++m_iterNdx < NUM_CASE_ITERATIONS) ? CONTINUE : STOP; } SyncTests::SyncTests (Context& context) : TestCaseGroup(context, "fence_sync", "Fence Sync Tests") { } SyncTests::~SyncTests (void) { } void SyncTests::init (void) { // Fence sync tests. addChild(new FenceSyncCase(m_context, "wait_sync_smalldraw", "", 10, COMMAND_WAIT_SYNC, 0, GL_TIMEOUT_IGNORED, 0)); addChild(new FenceSyncCase(m_context, "wait_sync_largedraw", "", 100000, COMMAND_WAIT_SYNC, 0, GL_TIMEOUT_IGNORED, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_smalldraw", "", 10, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_largedraw", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_timeout_smalldraw", "", 10, COMMAND_CLIENT_WAIT_SYNC, 0, 10, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_timeout_largedraw", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 10, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_flush_auto", "", 100000, COMMAND_CLIENT_WAIT_SYNC, GL_SYNC_FLUSH_COMMANDS_BIT, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_flush_manual", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, CASE_FLUSH_BEFORE_WAIT)); addChild(new FenceSyncCase(m_context, "client_wait_sync_noflush", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, 0)); addChild(new FenceSyncCase(m_context, "client_wait_sync_finish", "", 100000, COMMAND_CLIENT_WAIT_SYNC, 0, 0, CASE_FINISH_BEFORE_WAIT)); } } // Functional } // gles3 } // deqp
9,218
3,944
/* * The Sleuth Kit * * Contact: Brian Carrier [carrier <at> sleuthkit [dot] org] * Copyright (c) 2011-2012 Basis Technology Corporation. All Rights * reserved. * * This software is distributed under the Common Public License 1.0 */ /** \file TskHashLookupModule.cpp * Contains an implementation of a hash look up file analysis module that uses one or more * TSK hash database indexes to check a given file's MD5 hash against known bad file and * known file hash sets. Hash set hits are posted to the blackboard and the module can be * configured to issue a pipeline stop request if there is a hit. */ // System includes #include <string> #include <vector> #include <sstream> // Framework includes #include "tsk/framework/utilities/TskModuleDev.h" // Poco includes #include "Poco/StringTokenizer.h" namespace { const char *MODULE_NAME = "TskHashLookup"; const char *MODULE_DESCRIPTION = "Looks up a file's MD5 hash value in one or more hash databases that have been indexed using the Sleuth Kit's hfind tool"; const char *MODULE_VERSION = "1.0.0"; static bool issueStopRequestsOnHits = false; static TSK_HDB_INFO* knownHashDBInfo = NULL; static std::vector<TSK_HDB_INFO*> knownBadHashDBInfos; } /** * Helper function to open the index file for a TSK-indexed hash database. * * @param hashDatabasePath The path to a TSK-indexed hash database file. * @param option The option argument associated with the file, * for logging purposes. * @return A TSK_HDB_INFO pointer if the index file is * successfully opened, NULL otherwise. */ static TSK_HDB_INFO* openHashDatabaseIndexFile(const std::string& hashDatabasePath, const std::string& option) { // Was the hash database path specified? if (hashDatabasePath.empty()) { std::wstringstream msg; msg << L"TskHashLookupModule::initialize - missing hash database path for " << option.c_str() << L" option."; LOGERROR(msg.str()); return NULL; } // Get a hash database info record for the hash database. std::vector<TSK_TCHAR> hashDbPath(hashDatabasePath.length() + 1); std::copy(hashDatabasePath.begin(), hashDatabasePath.end(), hashDbPath.begin()); hashDbPath[hashDatabasePath.length()] = '\0'; TSK_HDB_INFO* hashDBInfo = tsk_hdb_open(&hashDbPath[0], TSK_HDB_OPEN_IDXONLY); if (!hashDBInfo) { std::wstringstream msg; msg << L"TskHashLookupModule::initialize - failed to hash database info record for '" << hashDatabasePath.c_str() << L"'"; LOGERROR(msg.str()); return NULL; } // Is there an MD5 index? if (!tsk_hdb_has_idx(hashDBInfo, TSK_HDB_HTYPE_MD5_ID)) { std::wstringstream msg; msg << L"TskHashLookupModule::initialize - failed to find MD5 index for '" << hashDatabasePath.c_str() << L"'"; LOGERROR(msg.str()); return NULL; } return hashDBInfo; } extern "C" { /** * Module identification function. * * @return The name of the module. */ TSK_MODULE_EXPORT const char *name() { return MODULE_NAME; } /** * Module identification function. * * @return A description of the module. */ TSK_MODULE_EXPORT const char *description() { return MODULE_DESCRIPTION; } /** * Module identification function. * * @return The version of the module. */ TSK_MODULE_EXPORT const char *version() { return MODULE_VERSION; } /** * Module initialization function. * * @param args A semicolon delimited list of arguments: * -k <path> The path of a TSK-indexed hash database for a known files * hash set. * -b <path> The path of a TSK-indexed hash database for a known bad * files hash set. Multiple known bad hash sets may be * specified. * -s A flag directing the module to issue a pipeline stop * request if a hash set hit occurs. * @return TskModule::OK if initialization succeeded, otherwise TskModule::FAIL. */ TskModule::Status TSK_MODULE_EXPORT initialize(const char* arguments) { std::string args(arguments); // At least one hash database path must be provided. if (args.empty()) { LOGERROR(L"TskHashLookupModule::initialize - passed empty argument string."); return TskModule::FAIL; } // Parse and process the arguments. Poco::StringTokenizer tokenizer(args, ";"); std::vector<std::string> argsVector(tokenizer.begin(), tokenizer.end()); for (std::vector<std::string>::const_iterator it = argsVector.begin(); it < argsVector.end(); ++it) { if ((*it).find("-s") == 0) { issueStopRequestsOnHits = true; } else if ((*it).find("-k") == 0) { // Only one known files hash set may be specified. if (knownHashDBInfo) { LOGERROR(L"TskHashLookupModule::initialize - multiple known hash databases specified, only one is allowed."); return TskModule::FAIL; } knownHashDBInfo = openHashDatabaseIndexFile((*it).substr(3), "-k"); if (!knownHashDBInfo) return TskModule::FAIL; } else if ((*it).find("-b") == 0) { // Any number of known bad files hash sets may be specified. TSK_HDB_INFO* hashDBInfo = openHashDatabaseIndexFile((*it).substr(3), "-b"); if (hashDBInfo) knownBadHashDBInfos.push_back(hashDBInfo); else return TskModule::FAIL; } else { LOGERROR(L"TskHashLookupModule::initialize - unrecognized option in argument string."); return TskModule::FAIL; } } // At least one hash database file path must be provided. if (!knownHashDBInfo && knownBadHashDBInfos.empty()) { LOGERROR(L"TskHashLookupModule::initialize - no hash database paths specified in argument string."); return TskModule::FAIL; } return TskModule::OK; } /** * Module execution function. Receives a pointer to a file the module is to * process. The file is represented by a TskFile interface which is queried * to get the MD5 hash of the file. The hash is then used do a lookup in * the hash database. If the lookup succeeds, a request to terminate * processing of the file is issued. * * @param pFile File for which the hash database lookup is to be performed. * @returns TskModule::FAIL if an error occurs, otherwise TskModule::OK * or TskModule::STOP. TskModule::STOP is returned if the look * up succeeds and the module is configured to request a * pipeline stop when a hash set hit occurs. */ TskModule::Status TSK_MODULE_EXPORT run(TskFile * pFile) { // Received a file to analyze? if (pFile == NULL) { LOGERROR(L"TskHashLookupModule::run passed NULL file pointer."); return TskModule::FAIL; } // Need at least one hash database index file to run. if (!knownHashDBInfo && knownBadHashDBInfos.empty()) { LOGERROR(L"TskHashLookupModule::run - no hash database index files to search."); return TskModule::FAIL; } // Check for hash set hits. TskBlackboard &blackBoard = TskServices::Instance().getBlackboard(); TskImgDB& imageDB = TskServices::Instance().getImgDB(); bool hashSetHit = false; try { std::string md5 = pFile->getHash(TskImgDB::MD5); // Check for known bad files hash set hits. If a hit occurs, mark the file as IMGDB_FILES_KNOWN_BAD // and post the hit to the blackboard. for (std::vector<TSK_HDB_INFO*>::iterator it = knownBadHashDBInfos.begin(); it < knownBadHashDBInfos.end(); ++it) { if (tsk_hdb_lookup_str(*it, md5.c_str(), TSK_HDB_FLAG_QUICK, NULL, NULL)) { if (!hashSetHit) { imageDB.updateKnownStatus(pFile->getId(), TskImgDB::IMGDB_FILES_KNOWN_BAD); hashSetHit = true; } TskBlackboardArtifact artifact = blackBoard.createArtifact(pFile->getId(), TSK_HASHSET_HIT); TskBlackboardAttribute attribute(TSK_SET_NAME, "TskHashLookupModule", "", (*it)->db_name); artifact.addAttribute(attribute); } } // If there were no known bad file hits, check for a known file hash set hit. if a hit occurs, // mark the file as IMGDB_FILES_KNOWN and post the hit to the blackboard. if (knownHashDBInfo && !hashSetHit && tsk_hdb_lookup_str(knownHashDBInfo, md5.c_str(), TSK_HDB_FLAG_QUICK, NULL, NULL)) { imageDB.updateKnownStatus(pFile->getId(), TskImgDB::IMGDB_FILES_KNOWN); hashSetHit = true; TskBlackboardArtifact artifact = blackBoard.createArtifact(pFile->getId(), TSK_HASHSET_HIT); TskBlackboardAttribute attribute(TSK_SET_NAME, "TskHashLookupModule", "", knownHashDBInfo->db_name); artifact.addAttribute(attribute); } } catch (TskException& ex) { std::wstringstream msg; msg << L"TskHashLookupModule::run - error on lookup for file id " << pFile->getId() << L": " << ex.what(); LOGERROR(msg.str()); return TskModule::FAIL; } return hashSetHit && issueStopRequestsOnHits ? TskModule::STOP : TskModule::OK; } /** * Module cleanup function that closes the hash database index files. * * @returns TskModule::OK */ TskModule::Status TSK_MODULE_EXPORT finalize() { if (knownHashDBInfo != NULL) tsk_hdb_close(knownHashDBInfo); // Closes the index file and frees the memory for the TSK_HDB_INFO struct. for (std::vector<TSK_HDB_INFO*>::iterator it = knownBadHashDBInfos.begin(); it < knownBadHashDBInfos.end(); ++it) tsk_hdb_close(*it); // Closes the index file and frees the memory for the TSK_HDB_INFO struct. return TskModule::OK; } }
10,570
3,099
#include "network_common.h" #include <server_lib/platform_config.h> #if defined(SERVER_LIB_PLATFORM_LINUX) #include <sys/socket.h> #include <netinet/ip.h> #include <sys/types.h> #endif namespace server_lib { namespace tests { uint16_t basic_network_fixture::get_free_port() { int result = 0; #if defined(SERVER_LIB_PLATFORM_LINUX) int max_loop = 5; int socket_fd = -1; while (result < 1024 && --max_loop > 0) { struct sockaddr_in sin; socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (socket_fd == -1) return -1; sin.sin_family = AF_INET; sin.sin_port = 0; sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); if (bind(socket_fd, (struct sockaddr*)&sin, sizeof(struct sockaddr_in)) == -1) break; socklen_t len = sizeof(sin); if (getsockname(socket_fd, (struct sockaddr*)&sin, &len) == -1) break; result = sin.sin_port; close(socket_fd); socket_fd = -1; } if (socket_fd > 0) close(socket_fd); #endif if (result < 1024) return get_default_port(); return static_cast<uint16_t>(result); } } // namespace tests } // namespace server_lib
1,330
468
#include "template.hpp" int main() { ll(N, Q); vll(A, N); vll(L, R, X, Q); set<ll> S; each(a, A) { if (S.count(a)) { S.erase(a); } else { S.insert(a); } } rep(i, Q) { ll ans = 0; ll c = 0; vi D; for (auto j = S.lower_bound(L[i]); j != S.end() and *j <= R[i]; ++j) { ans ^= *j; D.push_back(*j); ++c; } each(d, D) { S.erase(d); } out(ans); if (c & 1) { if (S.count(X[i])) { S.erase(X[i]); } else { S.insert(X[i]); } } } }
549
275
/** * @file HeatMapView.hpp * @brief The HeatMapView class. * @author Dominique LaSalle <dominique@solidlake.com> * Copyright 2017 * @version 1 */ #ifndef MATRIXINSPECTOR_VIEW_HEATMAPVIEW_HPP #define MATRIXINSPECTOR_VIEW_HEATMAPVIEW_HPP #include "View.hpp" #include "HeatMap.hpp" namespace MatrixInspector { class HeatMapView : public View { public: HeatMapView( wxFrame * parent); ~HeatMapView(); void draw() override; void refresh() override; private: HeatMap m_heatmap; GLuint m_glTexture; wxPoint m_mousePos; float m_zoom; float m_originX; float m_originY; void onMouseMove( wxMouseEvent& event); void onKey( wxKeyEvent& event); void onWheel( wxMouseEvent& event); void releaseTexture(); // disable copying HeatMapView( HeatMapView const & rhs); HeatMapView& operator=( HeatMapView const & rhs); wxDECLARE_EVENT_TABLE(); }; } #endif
1,016
408
#include <eosiolib/asset.hpp> #include <eosiolib/eosio.hpp> #include <eosiolib/types.hpp> #include <iostream> #include "../pradata.hpp" using namespace eosio; using namespace prochain; class demo : public contract { public: demo(account_name self) : contract(self){}; // @abi action void check(const account_name &account) { eosio_assert(is_account(account), "account is not valid"); //声明rating.pra的trating表 rating_index list(N(rating.pra), N(rating.pra)); //检查账号是否存在 auto check = list.find(account); //trating表中存储了全量链上合约账号,并实时更新 //如果找不到,则该账号是普通账号 if (check != list.end()) { //获取账号类型:普通账号 或 合约账号 auto account_type = check->account_type; //此处可应用场景:拒绝合约账号调用 //获取普通账号的评分 if (account_type == normal_account) { //此处可应用场景:拒绝黑名单账号、羊毛党账号、灰名单账号调用 //此处可应用场景:用户免人机滑块验证 action( permission_level{_self, N(active)}, _self, N(logreceipt), std::make_tuple(account, account_type, check->normal_account_level)) .send(); } //获取合约账号的评分 else if (account_type == code_account) { //此处可应用场景:拒绝恶意合约账号调用 action( permission_level{_self, N(active)}, _self, N(logreceipt), std::make_tuple(account, account_type, check->code_account_level)) .send(); } } else { //普通账号默认评分 action( permission_level{_self, N(active)}, _self, N(logreceipt), std::make_tuple(account, normal_account, ACCOUNT_LEVEL_DEFAULT)) .send(); } } // @abi action void logreceipt(const account_name &account, const uint8_t &account_type, const uint8_t &account_level) { require_auth(_self); } }; EOSIO_ABI(demo, (check)(logreceipt));
2,034
809
/* Generated by re2c 0.13.5 on Thu May 27 03:14:47 2010 */ #line 1 "fastpath.re" /* +----------------------------------------------------------------------+ | XHP | +----------------------------------------------------------------------+ | Copyright (c) 2009 - 2010 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE.PHP, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "fastpath.hpp" #include <stdio.h> #include <stdlib.h> #include <string.h> bool xhp_fastpath(const char* yy, const size_t len, const xhp_flags_t &flags) { const char* YYMARKER = NULL; char* heredoc_marker = NULL; size_t heredoc_marker_len = NULL; bool result = false; enum { HTML, PHP, HEREDOC, HEREDOC_START, COMMENT_EOL, COMMENT_BLOCK } state = flags.eval ? PHP : HTML; #define YYCURSOR yy #define YYCTYPE char #define YYGETCONDITION() state #define YYFILL(ii) #define YYDEBUG(s, c) printf("%03d: %c [%d]\n", s, c, c) for (;;) { const char* yystart = yy; #line 48 "fastpath.cpp" { YYCTYPE yych; unsigned int yyaccept = 0; switch (YYGETCONDITION()) { case COMMENT_BLOCK: goto yyc_COMMENT_BLOCK; case COMMENT_EOL: goto yyc_COMMENT_EOL; case HEREDOC: goto yyc_HEREDOC; case HEREDOC_START: goto yyc_HEREDOC_START; case HTML: goto yyc_HTML; case PHP: goto yyc_PHP; } /* *********************************** */ yyc_COMMENT_BLOCK: YYFILL(2); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy6; case '*': goto yy4; default: goto yy2; } yy2: ++YYCURSOR; #line 141 "fastpath.re" { continue; } #line 74 "fastpath.cpp" yy4: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '/': goto yy8; default: goto yy5; } yy5: #line 55 "fastpath.re" { continue; } #line 84 "fastpath.cpp" yy6: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 92 "fastpath.cpp" yy8: ++YYCURSOR; #line 142 "fastpath.re" { state = PHP; continue; } #line 100 "fastpath.cpp" /* *********************************** */ yyc_COMMENT_EOL: YYFILL(2); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy18; case '\n': goto yy14; case '\r': goto yy16; case '?': goto yy17; default: goto yy12; } yy12: ++YYCURSOR; yy13: #line 55 "fastpath.re" { continue; } #line 117 "fastpath.cpp" yy14: ++YYCURSOR; yy15: #line 132 "fastpath.re" { state = PHP; continue; } #line 126 "fastpath.cpp" yy16: yych = *++YYCURSOR; switch (yych) { case '\n': goto yy22; default: goto yy15; } yy17: yych = *++YYCURSOR; switch (yych) { case '>': goto yy20; default: goto yy13; } yy18: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 146 "fastpath.cpp" yy20: ++YYCURSOR; #line 136 "fastpath.re" { state = HTML; continue; } #line 154 "fastpath.cpp" yy22: ++YYCURSOR; yych = *YYCURSOR; goto yy15; /* *********************************** */ yyc_HEREDOC: YYFILL(2); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy29; case '\n': case '\r': goto yy27; default: goto yy25; } yy25: ++YYCURSOR; yych = *YYCURSOR; goto yy34; yy26: #line 117 "fastpath.re" { continue; } #line 178 "fastpath.cpp" yy27: ++YYCURSOR; yych = *YYCURSOR; goto yy32; yy28: #line 120 "fastpath.re" { if (strncmp(yy, heredoc_marker, heredoc_marker_len) == 0 && ( yy[heredoc_marker_len] == ';' || yy[heredoc_marker_len] == '\r' || yy[heredoc_marker_len] == '\n') ) { free(heredoc_marker); heredoc_marker = NULL; state = PHP; } continue; } #line 196 "fastpath.cpp" yy29: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 204 "fastpath.cpp" yy31: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy32: switch (yych) { case '\n': case '\r': goto yy31; default: goto yy28; } yy33: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy34: switch (yych) { case 0x00: case '\n': case '\r': goto yy26; default: goto yy33; } /* *********************************** */ yyc_HEREDOC_START: YYFILL(2); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy41; case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case '\t': case '\n': case '\v': case '\f': case '\r': case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case '[': case '\\': case ']': case '^': case '`': case '{': case '|': case '}': case '~': goto yy37; default: goto yy39; } yy37: ++YYCURSOR; #line 55 "fastpath.re" { continue; } #line 311 "fastpath.cpp" yy39: ++YYCURSOR; yych = *YYCURSOR; goto yy44; yy40: #line 108 "fastpath.re" { heredoc_marker_len = yy - yystart; heredoc_marker = (char*)malloc(heredoc_marker_len + 1); memcpy(heredoc_marker, yystart, heredoc_marker_len); heredoc_marker[heredoc_marker_len] = 0; state = HEREDOC; continue; } #line 326 "fastpath.cpp" yy41: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 334 "fastpath.cpp" yy43: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy44: switch (yych) { case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case '\t': case '\n': case '\v': case '\f': case '\r': case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case '[': case '\\': case ']': case '^': case '`': case '{': case '|': case '}': case '~': goto yy40; default: goto yy43; } /* *********************************** */ yyc_HTML: YYFILL(7); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy50; case '<': goto yy49; default: goto yy47; } yy47: ++YYCURSOR; yy48: #line 55 "fastpath.re" { continue; } #line 421 "fastpath.cpp" yy49: yych = *++YYCURSOR; switch (yych) { case '%': goto yy52; case '?': goto yy54; default: goto yy48; } yy50: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 436 "fastpath.cpp" yy52: ++YYCURSOR; switch ((yych = *YYCURSOR)) { case '=': goto yy64; default: goto yy53; } yy53: #line 67 "fastpath.re" { if (flags.asp_tags) { state = PHP; } continue; } #line 451 "fastpath.cpp" yy54: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case '=': goto yy58; case 'P': case 'p': goto yy56; default: goto yy55; } yy55: #line 61 "fastpath.re" { if (flags.short_tags) { state = PHP; } continue; } #line 469 "fastpath.cpp" yy56: yych = *++YYCURSOR; switch (yych) { case 'H': case 'h': goto yy59; default: goto yy57; } yy57: YYCURSOR = YYMARKER; goto yy55; yy58: yych = *++YYCURSOR; goto yy55; yy59: yych = *++YYCURSOR; switch (yych) { case 'P': case 'p': goto yy60; default: goto yy57; } yy60: yych = *++YYCURSOR; switch (yych) { case '\t': case '\n': case ' ': goto yy61; case '\r': goto yy63; default: goto yy57; } yy61: ++YYCURSOR; yy62: #line 57 "fastpath.re" { state = PHP; continue; } #line 507 "fastpath.cpp" yy63: yych = *++YYCURSOR; switch (yych) { case '\n': goto yy61; default: goto yy62; } yy64: ++YYCURSOR; yych = *YYCURSOR; goto yy53; /* *********************************** */ yyc_PHP: YYFILL(8); yych = *YYCURSOR; switch (yych) { case 0x00: goto yy81; case '"': goto yy69; case '#': goto yy70; case '%': goto yy72; case '&': goto yy73; case '\'': goto yy74; case ')': goto yy75; case '/': goto yy76; case ':': goto yy77; case '<': goto yy78; case '?': goto yy79; case 'B': case 'b': goto yy80; default: goto yy67; } yy67: ++YYCURSOR; yy68: #line 55 "fastpath.re" { continue; } #line 543 "fastpath.cpp" yy69: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 0x00) goto yy68; goto yy84; yy70: ++YYCURSOR; yy71: #line 86 "fastpath.re" { state = COMMENT_EOL; continue; } #line 557 "fastpath.cpp" yy72: yych = *++YYCURSOR; switch (yych) { case '>': goto yy115; default: goto yy68; } yy73: yych = *++YYCURSOR; switch (yych) { case '#': goto yy107; default: goto yy68; } yy74: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); if (yych <= 0x00) goto yy68; goto yy87; yy75: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case '\t': case '\n': case '\r': case ' ': goto yy113; case '[': goto yy107; default: goto yy68; } yy76: yych = *++YYCURSOR; switch (yych) { case '*': goto yy110; case '/': goto yy112; case '>': goto yy107; default: goto yy68; } yy77: yych = *++YYCURSOR; switch (yych) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': goto yy107; case ':': goto yy108; default: goto yy68; } yy78: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case '/': goto yy94; case '<': goto yy96; default: goto yy68; } yy79: yych = *++YYCURSOR; switch (yych) { case '>': goto yy92; default: goto yy68; } yy80: yyaccept = 0; yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case '"': goto yy83; case '\'': goto yy86; default: goto yy68; } yy81: ++YYCURSOR; #line 51 "fastpath.re" { result = false; break; } #line 691 "fastpath.cpp" yy83: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy84: switch (yych) { case 0x00: goto yy85; case '"': goto yy89; case '\\': goto yy91; default: goto yy83; } yy85: YYCURSOR = YYMARKER; switch (yyaccept) { case 0: goto yy68; case 1: goto yy95; } yy86: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; yy87: switch (yych) { case 0x00: goto yy85; case '\'': goto yy89; case '\\': goto yy88; default: goto yy86; } yy88: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; goto yy86; yy89: ++YYCURSOR; #line 85 "fastpath.re" { continue; } #line 729 "fastpath.cpp" yy91: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; goto yy83; yy92: ++YYCURSOR; #line 74 "fastpath.re" { state = HTML; continue; } #line 742 "fastpath.cpp" yy94: yyaccept = 1; yych = *(YYMARKER = ++YYCURSOR); switch (yych) { case 'S': case 's': goto yy100; default: goto yy95; } yy95: #line 103 "fastpath.re" { result = true; break; } #line 757 "fastpath.cpp" yy96: yych = *++YYCURSOR; switch (yych) { case '<': goto yy97; default: goto yy85; } yy97: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; switch (yych) { case '\t': case ' ': case '"': case '\'': goto yy97; default: goto yy99; } yy99: #line 94 "fastpath.re" { state = HEREDOC_START; continue; } #line 781 "fastpath.cpp" yy100: yych = *++YYCURSOR; switch (yych) { case 'C': case 'c': goto yy101; default: goto yy85; } yy101: yych = *++YYCURSOR; switch (yych) { case 'R': case 'r': goto yy102; default: goto yy85; } yy102: yych = *++YYCURSOR; switch (yych) { case 'I': case 'i': goto yy103; default: goto yy85; } yy103: yych = *++YYCURSOR; switch (yych) { case 'P': case 'p': goto yy104; default: goto yy85; } yy104: yych = *++YYCURSOR; switch (yych) { case 'T': case 't': goto yy105; default: goto yy85; } yy105: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; switch (yych) { case '\t': case '\n': case '\r': case ' ': goto yy105; case '>': goto yy92; default: goto yy85; } yy107: yych = *++YYCURSOR; goto yy95; yy108: ++YYCURSOR; #line 98 "fastpath.re" { continue; } #line 836 "fastpath.cpp" yy110: ++YYCURSOR; #line 90 "fastpath.re" { state = COMMENT_BLOCK; continue; } #line 844 "fastpath.cpp" yy112: yych = *++YYCURSOR; goto yy71; yy113: ++YYCURSOR; YYFILL(1); yych = *YYCURSOR; switch (yych) { case '\t': case '\n': case '\r': case ' ': goto yy113; case '[': goto yy107; default: goto yy85; } yy115: ++YYCURSOR; #line 78 "fastpath.re" { if (flags.asp_tags) { state = PHP; } continue; } #line 869 "fastpath.cpp" } #line 146 "fastpath.re" } if (heredoc_marker) { free(heredoc_marker); } return result; }
14,020
7,264
#include "GenerateTrainingSetView.h" //qt #include <QFileDialog> //qf #include "iqf_main.h" //mipf #include "MitkMain/IQF_MitkIO.h" #include "MitkMain/IQF_MitkDataManager.h" #include "ITKImageTypeDef.h" //itk #include <itkImage.h> #include <itkChangeInformationImageFilter.h> //mitk #include "mitkImage.h" #include "mitkImageCast.h" #include "mitkDataNode.h" #include "mitkRenderingManager.h" #include "ITK_Helpers.h" GenerateTrainingSetView::GenerateTrainingSetView(QF::IQF_Main* pMain, QWidget* parent) :QWidget(parent), m_pMain(pMain) { m_ui.setupUi(this); m_ui.ImageList->setHeaderLabels(QStringList() << "Name" << "Path"); connect(m_ui.DataDirBrowseBtn, &QPushButton::clicked, this, &GenerateTrainingSetView::DataDirBrowseFile); connect(m_ui.OutputDirBrowseBtn, &QPushButton::clicked, this, &GenerateTrainingSetView::OutputDirBrowseFile); connect(m_ui.ApplyBtn, &QPushButton::clicked, this, &GenerateTrainingSetView::Apply); } GenerateTrainingSetView::~GenerateTrainingSetView() { } void GenerateTrainingSetView::DataDirBrowseFile() { QString dirStr = QFileDialog::getExistingDirectory(this, "Select An Directory."); if (dirStr.isEmpty()) { return; } m_ui.DataDirLE->setText(dirStr); QDir dir(dirStr); QFileInfoList files = dir.entryInfoList(QDir::Files, QDir::Name); m_ui.ImageList->clear(); QList<QTreeWidgetItem*> items; foreach(QFileInfo fileInfo, files) { QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << fileInfo.fileName() << fileInfo.filePath()); items.append(item); } m_ui.ImageList->addTopLevelItems(items); } void GenerateTrainingSetView::OutputDirBrowseFile() { QString dirStr = QFileDialog::getExistingDirectory(this, "Select An Directory."); if (dirStr.isEmpty()) { return; } m_ui.OutputDirLE->setText(dirStr); } template <class TImageType> void CreateBaseImage(TImageType* input, TImageType*output) { } void GenerateTrainingSetView::Apply() { IQF_MitkDataManager* pDataManager = (IQF_MitkDataManager*)m_pMain->GetInterfacePtr(QF_MitkMain_DataManager); IQF_MitkIO* pIO = (IQF_MitkIO*)m_pMain->GetInterfacePtr(QF_MitkMain_IO); for (int i=0;i<m_ui.ImageList->topLevelItemCount();i++) { QString resultName = QString("TrainData%1").arg(i); mitk::DataNode* node = pIO->Load(m_ui.ImageList->topLevelItem(i)->text(1).toStdString().c_str()); if (!node) { return; } mitk::Image* mitkImage = dynamic_cast<mitk::Image*>(node->GetData()); UChar3DImageType::Pointer itkImage; mitk::CastToItkImage(mitkImage, itkImage); UChar3DImageType::Pointer output = UChar3DImageType::New(); int size[3] = { 256,128,256 }; double spacing[3] = {2,4,2}; ITKHelpers::ExtractCentroidImageWithGivenSize(itkImage.GetPointer(), output.GetPointer(), size, spacing); typedef itk::ChangeInformationImageFilter< UChar3DImageType > CenterFilterType; CenterFilterType::Pointer center = CenterFilterType::New(); center->CenterImageOn(); center->SetInput(output); center->Update(); mitk::Image::Pointer image; mitk::CastToMitkImage(center->GetOutput(), image); mitk::DataNode::Pointer on = mitk::DataNode::New(); on->SetData(image); on->SetName(resultName.toStdString().c_str()); pDataManager->GetDataStorage()->Add(on); pDataManager->GetDataStorage()->Remove(node); ITKHelpers::SaveImage(center->GetOutput(), m_ui.OutputDirLE->text().append("/%1.mha").arg(resultName).toStdString()); } }
3,677
1,322
#include "charts.hpp" #include "forcing_phase.hpp" #include "gnuplot_if.hpp" using namespace dynamics; namespace charts { void plot_impacts(const std::vector<Impact> &impacts, const std::string &outfile, const Parameters &params) { do_plot( {prepare_plot(impacts, "", "dots")}, outfile, params); } }
310
116
/* * Copyright 2006, Haiku. * * Copyright (c) 2002-2004 Matthijs Hollemans * Distributed under the terms of the MIT License. * * Authors: * Matthijs Hollemans */ #include <kits/debug/Debug.h> #include <MidiConsumer.h> #include <MidiProducer.h> #include <MidiRoster.h> #include <MidiRosterLooper.h> #include <protocol.h> using namespace BPrivate; BMidiRosterLooper::BMidiRosterLooper() : BLooper("MidiRosterLooper") { fInitLock = -1; fRoster = NULL; fWatcher = NULL; } BMidiRosterLooper::~BMidiRosterLooper() { StopWatching(); if (fInitLock >= B_OK) { delete_sem(fInitLock); } // At this point, our list may still contain endpoints with a // zero reference count. These objects are proxies for remote // endpoints, so we can safely delete them. If the list also // contains endpoints with a non-zero refcount (which can be // either remote or local), we will output a warning message. // It would have been better to jump into the debugger, but I // did not want to risk breaking any (misbehaving) old apps. for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->fRefCount > 0) { fprintf( stderr, "[midi] WARNING: Endpoint %" B_PRId32 " (%p) has " "not been Release()d properly (refcount = %" B_PRId32 ")\n", endp->ID(), endp, endp->fRefCount); } else { delete endp; } } } bool BMidiRosterLooper::Init(BMidiRoster* roster_) { ASSERT(roster_ != NULL) fRoster = roster_; // We create a semaphore with a zero count. BMidiRoster's // MidiRoster() method will try to acquire this semaphore, // but blocks because the count is 0. When we receive the // "app registered" message in our MessageReceived() hook, // we release the semaphore and MidiRoster() will unblock. fInitLock = create_sem(0, "InitLock"); if (fInitLock < B_OK) { WARN("Could not create semaphore") return false; } thread_id threadId = Run(); if (threadId < B_OK) { WARN("Could not start looper thread") return false; } return true; } BMidiEndpoint* BMidiRosterLooper::NextEndpoint(int32* id) { ASSERT(id != NULL) for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->ID() > *id) { if (endp->IsRemote() && endp->IsRegistered()) { *id = endp->ID(); return endp; } } } return NULL; } BMidiEndpoint* BMidiRosterLooper::FindEndpoint(int32 id) { for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->ID() == id) { return endp; } } return NULL; } void BMidiRosterLooper::AddEndpoint(BMidiEndpoint* endp) { ASSERT(endp != NULL) ASSERT(!fEndpoints.HasItem(endp)) // We store the endpoints sorted by ID, because that // simplifies the implementation of NextEndpoint(). // Although the midi_server assigns IDs in ascending // order, we can't assume that the mNEW messages also // are delivered in this order (mostly they will be). int32 t; for (t = CountEndpoints(); t > 0; --t) { BMidiEndpoint* other = EndpointAt(t - 1); if (endp->ID() > other->ID()) { break; } } fEndpoints.AddItem(endp, t); #ifdef DEBUG DumpEndpoints(); #endif } void BMidiRosterLooper::RemoveEndpoint(BMidiEndpoint* endp) { ASSERT(endp != NULL) ASSERT(fEndpoints.HasItem(endp)) fEndpoints.RemoveItem(endp); if (endp->IsConsumer()) { DisconnectDeadConsumer((BMidiConsumer*) endp); } else { DisconnectDeadProducer((BMidiProducer*) endp); } #ifdef DEBUG DumpEndpoints(); #endif } void BMidiRosterLooper::StartWatching(const BMessenger* watcher_) { ASSERT(watcher_ != NULL) StopWatching(); fWatcher = new BMessenger(*watcher_); AllEndpoints(); AllConnections(); } void BMidiRosterLooper::StopWatching() { delete fWatcher; fWatcher = NULL; } void BMidiRosterLooper::MessageReceived(BMessage* msg) { #ifdef DEBUG printf("IN "); msg->PrintToStream(); #endif switch (msg->what) { case MSG_APP_REGISTERED: OnAppRegistered(msg); break; case MSG_ENDPOINT_CREATED: OnEndpointCreated(msg); break; case MSG_ENDPOINT_DELETED: OnEndpointDeleted(msg); break; case MSG_ENDPOINT_CHANGED: OnEndpointChanged(msg); break; case MSG_ENDPOINTS_CONNECTED: OnConnectedDisconnected(msg); break; case MSG_ENDPOINTS_DISCONNECTED: OnConnectedDisconnected(msg); break; default: super::MessageReceived(msg); break; } } void BMidiRosterLooper::OnAppRegistered(BMessage* msg) { release_sem(fInitLock); } void BMidiRosterLooper::OnEndpointCreated(BMessage* msg) { int32 id; bool isRegistered; BString name; BMessage properties; bool isConsumer; if ((msg->FindInt32("midi:id", &id) == B_OK) && (msg->FindBool("midi:registered", &isRegistered) == B_OK) && (msg->FindString("midi:name", &name) == B_OK) && (msg->FindMessage("midi:properties", &properties) == B_OK) && (msg->FindBool("midi:consumer", &isConsumer) == B_OK)) { if (isConsumer) { int32 port; bigtime_t latency; if ((msg->FindInt32("midi:port", &port) == B_OK) && (msg->FindInt64("midi:latency", &latency) == B_OK)) { BMidiConsumer* cons = new BMidiConsumer(); cons->fName = name; cons->fId = id; cons->fIsRegistered = isRegistered; cons->fPort = port; cons->fLatency = latency; *(cons->fProperties) = properties; AddEndpoint(cons); return; } } else { // producer BMidiProducer* prod = new BMidiProducer(); prod->fName = name; prod->fId = id; prod->fIsRegistered = isRegistered; *(prod->fProperties) = properties; AddEndpoint(prod); return; } } WARN("Could not create proxy for remote endpoint") } void BMidiRosterLooper::OnEndpointDeleted(BMessage* msg) { int32 id; if (msg->FindInt32("midi:id", &id) == B_OK) { BMidiEndpoint* endp = FindEndpoint(id); if (endp != NULL) { RemoveEndpoint(endp); // If the client is watching, and the endpoint is // registered remote, we need to let it know that // the endpoint is now unregistered. if (endp->IsRemote() && endp->IsRegistered()) { if (fWatcher != NULL) { BMessage notify; notify.AddInt32("be:op", B_MIDI_UNREGISTERED); ChangeEvent(&notify, endp); } } // If the proxy object for this endpoint is no // longer being used, we can delete it. However, // if the refcount is not zero, we must defer // destruction until the client Release()'s the // object. We clear the "isRegistered" flag to // let the client know the object is now invalid. if (endp->fRefCount == 0) { delete endp; } else { // still being used endp->fIsRegistered = false; endp->fIsAlive = false; } return; } } WARN("Could not delete proxy for remote endpoint") } void BMidiRosterLooper::OnEndpointChanged(BMessage* msg) { int32 id; if (msg->FindInt32("midi:id", &id) == B_OK) { BMidiEndpoint* endp = FindEndpoint(id); if ((endp != NULL) && endp->IsRemote()) { ChangeRegistered(msg, endp); ChangeName(msg, endp); ChangeProperties(msg, endp); ChangeLatency(msg, endp); #ifdef DEBUG DumpEndpoints(); #endif return; } } WARN("Could not change endpoint attributes") } void BMidiRosterLooper::OnConnectedDisconnected(BMessage* msg) { int32 prodId, consId; if ((msg->FindInt32("midi:producer", &prodId) == B_OK) && (msg->FindInt32("midi:consumer", &consId) == B_OK)) { BMidiEndpoint* endp1 = FindEndpoint(prodId); BMidiEndpoint* endp2 = FindEndpoint(consId); if ((endp1 != NULL) && endp1->IsProducer()) { if ((endp2 != NULL) && endp2->IsConsumer()) { BMidiProducer* prod = (BMidiProducer*) endp1; BMidiConsumer* cons = (BMidiConsumer*) endp2; bool mustConnect = (msg->what == MSG_ENDPOINTS_CONNECTED); if (mustConnect) { prod->ConnectionMade(cons); } else { prod->ConnectionBroken(cons); } if (fWatcher != NULL) { ConnectionEvent(prod, cons, mustConnect); } #ifdef DEBUG DumpEndpoints(); #endif return; } } } WARN("Could not connect/disconnect endpoints") } void BMidiRosterLooper::ChangeRegistered(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) bool isRegistered; if (msg->FindBool("midi:registered", &isRegistered) == B_OK) { if (endp->fIsRegistered != isRegistered) { endp->fIsRegistered = isRegistered; if (fWatcher != NULL) { BMessage notify; if (isRegistered) { notify.AddInt32("be:op", B_MIDI_REGISTERED); } else { notify.AddInt32("be:op", B_MIDI_UNREGISTERED); } ChangeEvent(&notify, endp); } } } } void BMidiRosterLooper::ChangeName(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) BString name; if (msg->FindString("midi:name", &name) == B_OK) { if (endp->fName != name) { endp->fName = name; if ((fWatcher != NULL) && endp->IsRegistered()) { BMessage notify; notify.AddInt32("be:op", B_MIDI_CHANGED_NAME); notify.AddString("be:name", name); ChangeEvent(&notify, endp); } } } } void BMidiRosterLooper::ChangeProperties(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) BMessage properties; if (msg->FindMessage("midi:properties", &properties) == B_OK) { *(endp->fProperties) = properties; if ((fWatcher != NULL) && endp->IsRegistered()) { BMessage notify; notify.AddInt32("be:op", B_MIDI_CHANGED_PROPERTIES); notify.AddMessage("be:properties", &properties); ChangeEvent(&notify, endp); } } } void BMidiRosterLooper::ChangeLatency(BMessage* msg, BMidiEndpoint* endp) { ASSERT(msg != NULL) ASSERT(endp != NULL) bigtime_t latency; if (msg->FindInt64("midi:latency", &latency) == B_OK) { if (endp->IsConsumer()) { BMidiConsumer* cons = (BMidiConsumer*) endp; if (cons->fLatency != latency) { cons->fLatency = latency; if ((fWatcher != NULL) && cons->IsRegistered()) { BMessage notify; notify.AddInt32("be:op", B_MIDI_CHANGED_LATENCY); notify.AddInt64("be:latency", latency); ChangeEvent(&notify, endp); } } } } } void BMidiRosterLooper::AllEndpoints() { BMessage notify; for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->IsRemote() && endp->IsRegistered()) { notify.MakeEmpty(); notify.AddInt32("be:op", B_MIDI_REGISTERED); ChangeEvent(&notify, endp); } } } void BMidiRosterLooper::AllConnections() { for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->IsRemote() && endp->IsRegistered()) { if (endp->IsProducer()) { BMidiProducer* prod = (BMidiProducer*) endp; if (prod->LockProducer()) { for (int32 k = 0; k < prod->CountConsumers(); ++k) { ConnectionEvent(prod, prod->ConsumerAt(k), true); } prod->UnlockProducer(); } } } } } void BMidiRosterLooper::ChangeEvent(BMessage* msg, BMidiEndpoint* endp) { ASSERT(fWatcher != NULL) ASSERT(msg != NULL) ASSERT(endp != NULL) msg->what = B_MIDI_EVENT; msg->AddInt32("be:id", endp->ID()); if (endp->IsConsumer()) { msg->AddString("be:type", "consumer"); } else { msg->AddString("be:type", "producer"); } fWatcher->SendMessage(msg); } void BMidiRosterLooper::ConnectionEvent( BMidiProducer* prod, BMidiConsumer* cons, bool mustConnect) { ASSERT(fWatcher != NULL) ASSERT(prod != NULL) ASSERT(cons != NULL) BMessage notify; notify.what = B_MIDI_EVENT; notify.AddInt32("be:producer", prod->ID()); notify.AddInt32("be:consumer", cons->ID()); if (mustConnect) { notify.AddInt32("be:op", B_MIDI_CONNECTED); } else { notify.AddInt32("be:op", B_MIDI_DISCONNECTED); } fWatcher->SendMessage(&notify); } void BMidiRosterLooper::DisconnectDeadConsumer(BMidiConsumer* cons) { ASSERT(cons != NULL) // Note: Rather than looping through each producer's list // of connected consumers, we let ConnectionBroken() tell // us whether the consumer really was connected. for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); if (endp->IsProducer()) { BMidiProducer* prod = (BMidiProducer*) endp; if (prod->ConnectionBroken(cons)) { if (cons->IsRemote() && (fWatcher != NULL)) { ConnectionEvent(prod, cons, false); } } } } } void BMidiRosterLooper::DisconnectDeadProducer(BMidiProducer* prod) { ASSERT(prod != NULL) // We don't need to lock or remove the consumers from // the producer's list of connections, because when this // function is called, we're destroying the object. if (prod->IsRemote() && (fWatcher != NULL)) { for (int32 t = 0; t < prod->CountConsumers(); ++t) { ConnectionEvent(prod, prod->ConsumerAt(t), false); } } } int32 BMidiRosterLooper::CountEndpoints() { return fEndpoints.CountItems(); } BMidiEndpoint* BMidiRosterLooper::EndpointAt(int32 index) { ASSERT(index >= 0 && index < CountEndpoints()) return (BMidiEndpoint*) fEndpoints.ItemAt(index); } #ifdef DEBUG void BMidiRosterLooper::DumpEndpoints() { if (Lock()) { printf("*** START DumpEndpoints\n"); for (int32 t = 0; t < CountEndpoints(); ++t) { BMidiEndpoint* endp = EndpointAt(t); printf("\tendpoint %" B_PRId32 " (%p):\n", t, endp); printf( "\t\tid %" B_PRId32 ", name '%s', %s, %s, %s, %s, refcount %" B_PRId32 "\n", endp->ID(), endp->Name(), endp->IsConsumer() ? "consumer" : "producer", endp->IsRegistered() ? "registered" : "unregistered", endp->IsLocal() ? "local" : "remote", endp->IsValid() ? "valid" : "invalid", endp->fRefCount); printf("\t\tproperties: "); endp->fProperties->PrintToStream(); if (endp->IsConsumer()) { BMidiConsumer* cons = (BMidiConsumer*) endp; printf("\t\tport %" B_PRId32 ", latency %" B_PRIdBIGTIME "\n", cons->fPort, cons->fLatency); } else { BMidiProducer* prod = (BMidiProducer*) endp; if (prod->LockProducer()) { printf("\t\tconnections:\n"); for (int32 k = 0; k < prod->CountConsumers(); ++k) { BMidiConsumer* cons = prod->ConsumerAt(k); printf("\t\t\tid %" B_PRId32 " (%p)\n", cons->ID(), cons); } prod->UnlockProducer(); } } } printf("*** END DumpEndpoints\n"); Unlock(); } } #endif
14,275
6,121
#include <string> #include <iostream> #include <SFML/Window/Joystick.hpp> #include "code/utilities/peripheral/keyboard/F310_gamepad/functions/f310_gamepads_state_getter.hpp" #include "code/utilities/formats/json/converters/lib.hpp" #include "code/utilities/formats/json/converters/type_to_json_string.hpp", int main() { // i bought two Logitech Gamepad F310 controllers //this dumps their state in json while (true){ auto controllers = F310_Gamepads_State_Getter::Get(); std::cout << Type_To_Json_String::As_JSON_String(controllers) << std::endl; } return 0; }
598
220
// -*- C++ -*- #include "SAXPrint_Handler.h" #include "ace/ACE.h" #include "ace/Log_Msg.h" #if !defined (__ACEXML_INLINE__) # include "SAXPrint_Handler.inl" #endif /* __ACEXML_INLINE__ */ ACEXML_SAXPrint_Handler::ACEXML_SAXPrint_Handler (const ACEXML_Char* filename) : indent_ (0), fileName_(ACE::strnew (filename)), locator_ (0) { // no-op } ACEXML_SAXPrint_Handler::~ACEXML_SAXPrint_Handler (void) { delete [] this->fileName_; } void ACEXML_SAXPrint_Handler::characters (const ACEXML_Char *cdata, size_t, size_t) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%s"), cdata)); } void ACEXML_SAXPrint_Handler::endDocument (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); } void ACEXML_SAXPrint_Handler::endElement (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *qName) { this->dec_indent (); this->print_indent (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("</%s>"), qName)); } void ACEXML_SAXPrint_Handler::endPrefixMapping (const ACEXML_Char *) { // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("* Event endPrefixMapping (%s) ***************\n"), // prefix)); } void ACEXML_SAXPrint_Handler::ignorableWhitespace (const ACEXML_Char * cdata, int, int) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%s"), cdata)); // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("* Event ignorableWhitespace () ***************\n"))); } void ACEXML_SAXPrint_Handler::processingInstruction (const ACEXML_Char *target, const ACEXML_Char *data) { this->print_indent (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("<?%s %s>\n"), target, data)); } void ACEXML_SAXPrint_Handler::setDocumentLocator (ACEXML_Locator * locator) { this->locator_ = locator; //ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("* Event setDocumentLocator () ***************\n"))); } void ACEXML_SAXPrint_Handler::skippedEntity (const ACEXML_Char *name) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("* Event skippedEntity (%s) ***************\n"), name)); } void ACEXML_SAXPrint_Handler::startDocument (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("* Event startDocument () ***************\n"))); } void ACEXML_SAXPrint_Handler::startElement (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *qName, ACEXML_Attributes *alist) { this->print_indent (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("<%s"), qName)); if (alist != 0) for (size_t i = 0; i < alist->getLength (); ++i) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" %s = \"%s\""), alist->getQName (i), alist->getValue (i))); } ACE_DEBUG ((LM_DEBUG, ACE_TEXT (">"))); this->inc_indent (); } void ACEXML_SAXPrint_Handler::startPrefixMapping (const ACEXML_Char * , const ACEXML_Char *) { // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("* Event startPrefixMapping () ***************\n"))); // ACE_DEBUG ((LM_DEBUG, // ACE_TEXT ("Prefix = %s, URI = %s\n"), prefix, uri)); } // *** Methods inherited from ACEXML_DTDHandler. void ACEXML_SAXPrint_Handler::notationDecl (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *) { // No-op. } void ACEXML_SAXPrint_Handler::unparsedEntityDecl (const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *, const ACEXML_Char *) { // No-op. } // Methods inherited from ACEXML_EnitityResolver. ACEXML_InputSource * ACEXML_SAXPrint_Handler::resolveEntity (const ACEXML_Char *, const ACEXML_Char *) { // No-op. return 0; } // Methods inherited from ACEXML_ErrorHandler. /* * Receive notification of a recoverable error. */ void ACEXML_SAXPrint_Handler::error (ACEXML_SAXParseException & ex) { ACE_DEBUG ((LM_DEBUG, "%s: line: %d col: %d ", (this->locator_->getSystemId() == 0 ? this->fileName_ : this->locator_->getSystemId()), this->locator_->getLineNumber(), this->locator_->getColumnNumber())); ex.print(); } void ACEXML_SAXPrint_Handler::fatalError (ACEXML_SAXParseException & ex) { ACE_DEBUG ((LM_DEBUG, "%s: line: %d col: %d ", (this->locator_->getSystemId() == 0 ? this->fileName_ : this->locator_->getSystemId()), this->locator_->getLineNumber(), this->locator_->getColumnNumber())); ex.print(); } void ACEXML_SAXPrint_Handler::warning (ACEXML_SAXParseException & ex) { ACE_DEBUG ((LM_DEBUG, "%s: line: %d col: %d ", (this->locator_->getSystemId() == 0 ? this->fileName_ : this->locator_->getSystemId()), this->locator_->getLineNumber(), this->locator_->getColumnNumber())); ex.print(); } void ACEXML_SAXPrint_Handler::print_indent (void) { ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n"))); for (size_t i = 0; i < this->indent_; ++i) ACE_DEBUG ((LM_DEBUG, ACE_TEXT (" "))); }
5,574
1,895
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: WavmUtils.cpp * Author: ubuntu * * Created on April 22, 2018, 5:42 PM */ #include <string> #include <iostream> #include "keto/common/Log.hpp" #include "keto/wavm_common/WavmUtils.hpp" namespace keto { namespace wavm_common { std::string WavmUtils::readCString(Runtime::MemoryInstance* memory,I32 stringAddress) { // Validate the path name and make a local copy of it. std::string returnString; int index = 0; while(true) { int c = Runtime::memoryRef<char>(memory,stringAddress + index); if(c == 0) { break; } else { returnString += c; } index ++; }; return returnString; } std::string WavmUtils::readTypeScriptString(Runtime::MemoryInstance* memory,I32 stringAddress) { // Validate the path name and make a local copy of it. std::string returnString; int size = Runtime::memoryRef<char>(memory,stringAddress); size += Runtime::memoryRef<char>(memory,stringAddress+1) * 100; size += Runtime::memoryRef<char>(memory,stringAddress+2) * 10000; for (int index = 0; index < (size * 2); index++) { if ((int)Runtime::memoryRef<char>(memory,stringAddress + 4 + index) != 0) { returnString += (int)Runtime::memoryRef<char>(memory,stringAddress + 4 + index); } } return returnString; } std::vector<char> WavmUtils::buildTypeScriptString(const std::string& value) { int currentValue = value.length(); std::vector<char> result; for (int count = 0 ; count < 4; count++) { int mod = currentValue % 100; result.push_back((char)mod); currentValue = currentValue / 100; } for (const char character : value) { result.push_back(character); result.push_back(0); } return result; } void WavmUtils::log(uint32_t intLevel,const std::string& msg) { switch(intLevel) { case 1 : KETO_LOG_DEBUG << msg; break; case 2 : KETO_LOG_INFO << msg; break; case 3 : KETO_LOG_WARNING << msg; break; case 4 : KETO_LOG_ERROR << msg; break; case 5 : KETO_LOG_FATAL << msg; break; }; } } }
2,463
803
#include "Box.h" #include "gl/glut.h" Box::Box(): bIsOverlapping(false) { body = new cyclone::RigidBody(); } Box::~Box() { delete body; } void Box::Render() const { // Get the OpenGL transformation GLfloat mat[16]; body->GetGLTransform(mat); if (bIsOverlapping) { glColor3f(0.7f, 1.f, 0.7f); } else if (body->GetAwake()) { glColor3f(1.f, 0.7f, 0.7f); } else { glColor3f(0.7f, 0.7f, 1.f); } glPushMatrix(); glMultMatrixf(mat); glScalef(halfSize.x * 2, halfSize.y * 2, halfSize.z * 2); glutSolidCube(1.f); glPopMatrix(); } void Box::RenderShadow() const { // Get the OpenGL transformation GLfloat matrix[16]; body->GetGLTransform(matrix); glPushMatrix(); glScalef(1.f, 0.f, 1.f); glMultMatrixf(matrix); glScalef(halfSize.x * 2, halfSize.y * 2, halfSize.z * 2); glutSolidCube(1.f); glPopMatrix(); } void Box::SetState(const cyclone::Vector3& position, const cyclone::Quaternion& orientation, const cyclone::Vector3& extents, const cyclone::Vector3& velocity) { body->SetPosition(position); body->SetOrientation(orientation); body->SetVelocity(velocity); body->SetRotation(cyclone::Vector3()); halfSize = extents; const auto mass = halfSize.x * halfSize.y * halfSize.z * 8.f; body->SetMass(mass); cyclone::Matrix tensor; const auto squares = halfSize * halfSize; tensor.M[0][0] = 0.3f * mass * (squares.y + squares.z); tensor.M[0][1] = tensor.M[1][0] = 0.f; tensor.M[0][2] = tensor.M[2][0] = 0.f; tensor.M[1][1] = 0.3f * mass * (squares.x + squares.z); tensor.M[1][2] = tensor.M[2][1] = 0.f; tensor.M[2][2] = 0.3f * mass * (squares.x + squares.y); tensor.M[3][3] = 1.f; body->SetInertiaTensor(tensor); body->SetLinearDamping(0.95f); body->SetAngularDamping(0.8f); body->ClearAccumulators(); body->SetAcceleration(0.f, -10.f, 0.f); body->SetAwake(); body->CalculateDerivedData(); } void Box::Random(cyclone::Random* random) { if (random != nullptr) { const static cyclone::Vector3 minPosition(-5.f, 5.f, -5.f); const static cyclone::Vector3 maxPosition(5.f, 10.0, 5.f); const static cyclone::Vector3 minSize(0.5f, 0.5f, 0.5f); const static cyclone::Vector3 maxSize(4.5f, 1.5f, 1.5f); SetState(random->RandomVector(minPosition, maxPosition), random->RandomQuaternion(), random->RandomVector(minSize, maxSize), cyclone::Vector3()); } }
2,591
1,068
#include "precompiled.hpp" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wglobal-constructors" #endif // __clang__ #if defined __GNUC__ \ && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) ) \ && !defined __clang__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-local-typedefs" #endif #include <boost/test/unit_test.hpp> namespace error_propagation { class PolicyMock; } #define DEFAULT_POLICY_CLASS error_propagation::PolicyMock #include "ValueWithError.hpp" #include "PolicyMock.hpp" using namespace error_propagation; namespace { typedef ValueWithError<double,PolicyMock> VD; typedef ValueWithError<float,PolicyMock> VF; } // anonymous namespace BOOST_AUTO_TEST_SUITE(Test_ValueWithError_Policy) BOOST_AUTO_TEST_CASE(make_val) { VD a; a = make_value(1.0, 1.0); BOOST_CHECK(true); } BOOST_AUTO_TEST_SUITE_END() // Test_ValueWithError_Policy #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ #if defined __GNUC__ \ && ( __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7) ) \ && !defined __clang__ #pragma GCC diagnostic pop #endif
1,189
447
//============================================================================== #ifndef ArseAbout #define ArseAbout #pragma once #include <context.hpp> //------------------------------------------------------------------------------ class Credits : public Context { public: Credits(); virtual ~Credits(); private: Credits( const Credits & ); Credits & operator=( const Credits & ); public: virtual void init(); virtual void fini(); virtual bool update( float dt ); virtual void render(); private: bool m_interact; }; #endif //==============================================================================
659
162
// Time: O(n^2 * n!) // Space: O(n^2) class Solution { private: struct TrieNode { vector<int> indices; vector<TrieNode *> children; TrieNode() : children(26, nullptr) {} }; TrieNode *buildTrie(const vector<string>& words) { TrieNode *root = new TrieNode(); for (int j = 0; j < words.size(); ++j) { TrieNode* t = root; for (int i = 0; i < words[j].size(); ++i) { if (!t->children[words[j][i] - 'a']) { t->children[words[j][i] - 'a'] = new TrieNode(); } t = t->children[words[j][i] - 'a']; t->indices.push_back(j); } } return root; } public: vector<vector<string>> wordSquares(vector<string>& words) { vector<vector<string>> result; TrieNode *trie = buildTrie(words); vector<string> curr; for (const auto& s : words) { curr.emplace_back(s); wordSquaresHelper(words, trie, &curr, &result); curr.pop_back(); } return result; } private: void wordSquaresHelper(const vector<string>& words, TrieNode *trie, vector<string> *curr, vector<vector<string>> *result) { if (curr->size() >= words[0].length()) { return result->emplace_back(*curr); } TrieNode *node = trie; for (int i = 0; i < curr->size(); ++i) { if (!(node = node->children[(*curr)[i][curr->size()] - 'a'])) { return; } } for (const auto& i : node->indices) { curr->emplace_back(words[i]); wordSquaresHelper(words, trie, curr, result); curr->pop_back(); } } };
1,799
581
/* Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "flutter/sky/engine/platform/text/SegmentedString.h" namespace blink { unsigned SegmentedString::length() const { unsigned length = m_currentString.m_length; if (m_pushedChar1) { ++length; if (m_pushedChar2) ++length; } if (isComposite()) { Deque<SegmentedSubstring>::const_iterator it = m_substrings.begin(); Deque<SegmentedSubstring>::const_iterator e = m_substrings.end(); for (; it != e; ++it) length += it->m_length; } return length; } void SegmentedString::setExcludeLineNumbers() { m_currentString.setExcludeLineNumbers(); if (isComposite()) { Deque<SegmentedSubstring>::iterator it = m_substrings.begin(); Deque<SegmentedSubstring>::iterator e = m_substrings.end(); for (; it != e; ++it) it->setExcludeLineNumbers(); } } void SegmentedString::clear() { m_pushedChar1 = 0; m_pushedChar2 = 0; m_currentChar = 0; m_currentString.clear(); m_numberOfCharactersConsumedPriorToCurrentString = 0; m_numberOfCharactersConsumedPriorToCurrentLine = 0; m_currentLine = 0; m_substrings.clear(); m_closed = false; m_empty = true; m_fastPathFlags = NoFastPath; m_advanceFunc = &SegmentedString::advanceEmpty; m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty; } void SegmentedString::append(const SegmentedSubstring& s) { ASSERT(!m_closed); if (!s.m_length) return; if (!m_currentString.m_length) { m_numberOfCharactersConsumedPriorToCurrentString += m_currentString.numberOfCharactersConsumed(); m_currentString = s; updateAdvanceFunctionPointers(); } else { m_substrings.append(s); } m_empty = false; } void SegmentedString::prepend(const SegmentedSubstring& s) { ASSERT(!escaped()); ASSERT(!s.numberOfCharactersConsumed()); if (!s.m_length) return; // FIXME: We're assuming that the prepend were originally consumed by // this SegmentedString. We're also ASSERTing that s is a fresh // SegmentedSubstring. These assumptions are sufficient for our // current use, but we might need to handle the more elaborate // cases in the future. m_numberOfCharactersConsumedPriorToCurrentString += m_currentString.numberOfCharactersConsumed(); m_numberOfCharactersConsumedPriorToCurrentString -= s.m_length; if (!m_currentString.m_length) { m_currentString = s; updateAdvanceFunctionPointers(); } else { // Shift our m_currentString into our list. m_substrings.prepend(m_currentString); m_currentString = s; updateAdvanceFunctionPointers(); } m_empty = false; } void SegmentedString::close() { // Closing a stream twice is likely a coding mistake. ASSERT(!m_closed); m_closed = true; } void SegmentedString::append(const SegmentedString& s) { ASSERT(!m_closed); if (s.m_pushedChar1) { Vector<UChar, 2> unconsumedData; unconsumedData.append(s.m_pushedChar1); if (s.m_pushedChar2) unconsumedData.append(s.m_pushedChar2); append(SegmentedSubstring(String(unconsumedData))); } append(s.m_currentString); if (s.isComposite()) { Deque<SegmentedSubstring>::const_iterator it = s.m_substrings.begin(); Deque<SegmentedSubstring>::const_iterator e = s.m_substrings.end(); for (; it != e; ++it) append(*it); } m_currentChar = m_pushedChar1 ? m_pushedChar1 : (m_currentString.m_length ? m_currentString.getCurrentChar() : 0); } void SegmentedString::prepend(const SegmentedString& s) { ASSERT(!escaped()); ASSERT(!s.escaped()); if (s.isComposite()) { Deque<SegmentedSubstring>::const_reverse_iterator it = s.m_substrings.rbegin(); Deque<SegmentedSubstring>::const_reverse_iterator e = s.m_substrings.rend(); for (; it != e; ++it) prepend(*it); } prepend(s.m_currentString); m_currentChar = m_currentString.m_length ? m_currentString.getCurrentChar() : 0; } void SegmentedString::advanceSubstring() { if (isComposite()) { m_numberOfCharactersConsumedPriorToCurrentString += m_currentString.numberOfCharactersConsumed(); m_currentString = m_substrings.takeFirst(); // If we've previously consumed some characters of the non-current // string, we now account for those characters as part of the current // string, not as part of "prior to current string." m_numberOfCharactersConsumedPriorToCurrentString -= m_currentString.numberOfCharactersConsumed(); updateAdvanceFunctionPointers(); } else { m_currentString.clear(); m_empty = true; m_fastPathFlags = NoFastPath; m_advanceFunc = &SegmentedString::advanceEmpty; m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty; } } String SegmentedString::toString() const { StringBuilder result; if (m_pushedChar1) { result.append(m_pushedChar1); if (m_pushedChar2) result.append(m_pushedChar2); } m_currentString.appendTo(result); if (isComposite()) { Deque<SegmentedSubstring>::const_iterator it = m_substrings.begin(); Deque<SegmentedSubstring>::const_iterator e = m_substrings.end(); for (; it != e; ++it) it->appendTo(result); } return result.toString(); } void SegmentedString::advance(unsigned count, UChar* consumedCharacters) { ASSERT_WITH_SECURITY_IMPLICATION(count <= length()); for (unsigned i = 0; i < count; ++i) { consumedCharacters[i] = currentChar(); advance(); } } void SegmentedString::advance8() { ASSERT(!m_pushedChar1); decrementAndCheckLength(); m_currentChar = m_currentString.incrementAndGetCurrentChar8(); } void SegmentedString::advance16() { ASSERT(!m_pushedChar1); decrementAndCheckLength(); m_currentChar = m_currentString.incrementAndGetCurrentChar16(); } void SegmentedString::advanceAndUpdateLineNumber8() { ASSERT(!m_pushedChar1); ASSERT(m_currentString.getCurrentChar() == m_currentChar); if (m_currentChar == '\n') { ++m_currentLine; m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + 1; } decrementAndCheckLength(); m_currentChar = m_currentString.incrementAndGetCurrentChar8(); } void SegmentedString::advanceAndUpdateLineNumber16() { ASSERT(!m_pushedChar1); ASSERT(m_currentString.getCurrentChar() == m_currentChar); if (m_currentChar == '\n') { ++m_currentLine; m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + 1; } decrementAndCheckLength(); m_currentChar = m_currentString.incrementAndGetCurrentChar16(); } void SegmentedString::advanceSlowCase() { if (m_pushedChar1) { m_pushedChar1 = m_pushedChar2; m_pushedChar2 = 0; if (m_pushedChar1) { m_currentChar = m_pushedChar1; return; } updateAdvanceFunctionPointers(); } else if (m_currentString.m_length) { if (!--m_currentString.m_length) advanceSubstring(); } else if (!isComposite()) { m_currentString.clear(); m_empty = true; m_fastPathFlags = NoFastPath; m_advanceFunc = &SegmentedString::advanceEmpty; m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty; } m_currentChar = m_currentString.m_length ? m_currentString.getCurrentChar() : 0; } void SegmentedString::advanceAndUpdateLineNumberSlowCase() { if (m_pushedChar1) { m_pushedChar1 = m_pushedChar2; m_pushedChar2 = 0; if (m_pushedChar1) { m_currentChar = m_pushedChar1; return; } updateAdvanceFunctionPointers(); } else if (m_currentString.m_length) { if (m_currentString.getCurrentChar() == '\n' && m_currentString.doNotExcludeLineNumbers()) { ++m_currentLine; // Plus 1 because numberOfCharactersConsumed value hasn't incremented yet; it does with m_length decrement below. m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + 1; } if (!--m_currentString.m_length) advanceSubstring(); else m_currentString.incrementAndGetCurrentChar(); // Only need the ++ } else if (!isComposite()) { m_currentString.clear(); m_empty = true; m_fastPathFlags = NoFastPath; m_advanceFunc = &SegmentedString::advanceEmpty; m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceEmpty; } m_currentChar = m_currentString.m_length ? m_currentString.getCurrentChar() : 0; } void SegmentedString::advanceEmpty() { ASSERT(!m_currentString.m_length && !isComposite()); m_currentChar = 0; } void SegmentedString::updateSlowCaseFunctionPointers() { m_fastPathFlags = NoFastPath; m_advanceFunc = &SegmentedString::advanceSlowCase; m_advanceAndUpdateLineNumberFunc = &SegmentedString::advanceAndUpdateLineNumberSlowCase; } OrdinalNumber SegmentedString::currentLine() const { return OrdinalNumber::fromZeroBasedInt(m_currentLine); } OrdinalNumber SegmentedString::currentColumn() const { int zeroBasedColumn = numberOfCharactersConsumed() - m_numberOfCharactersConsumedPriorToCurrentLine; return OrdinalNumber::fromZeroBasedInt(zeroBasedColumn); } void SegmentedString::setCurrentPosition(OrdinalNumber line, OrdinalNumber columnAftreProlog, int prologLength) { m_currentLine = line.zeroBasedInt(); m_numberOfCharactersConsumedPriorToCurrentLine = numberOfCharactersConsumed() + prologLength - columnAftreProlog.zeroBasedInt(); } }
10,711
3,487
#include "headers/instruction.h" #include "headers/functions.h" #include "headers/utilities.h" #include "headers/global_vars.h" Instruction::Instruction(int addr, uint OP, Builder *Maker) { OPCode = OP; this->Maker = Maker; this->addr_instr = addr; } Instruction::Instruction(int addr, QString name, uint OP, Builder *Maker){ this->addr_instr = addr; OPCode = OP; this->name = name; this->Maker = Maker; } Instruction::~Instruction(){ } Instruction::Instruction(int &addr, int idx_row, QXlsx::Document &excelScenarioSheet, QString name, uint OP,Builder *Maker){ this->name = name; this->OPCode = OP; this->Maker = Maker; addr_instr = addr; if (OPCode<=0xFF) addr++; int idx_operande = 3; QString type = excelScenarioSheet.read(idx_row, idx_operande).toString(); while(!type.isEmpty()){ QByteArray Value; operande op; if (type == "int"){ int Operande = excelScenarioSheet.read(idx_row+1, idx_operande).toInt(); Value = GetBytesFromInt(Operande); op = operande(addr,"int", Value); } else if (type == "float"){ float Operande = excelScenarioSheet.read(idx_row+1, idx_operande).toFloat(); Value = GetBytesFromFloat(Operande); op = operande(addr,"float", Value); } else if (type == "short"){ ushort Operande = excelScenarioSheet.read(idx_row+1, idx_operande).toInt(); Value = GetBytesFromShort(Operande); op = operande(addr,"short", Value); } else if ((type == "byte")||(type == "OP Code")){ int OP = excelScenarioSheet.read(idx_row+1, idx_operande).toInt(); if (OP<=0xFF){ // actually the opposite never happens. unsigned char Operande = ((OP)& 0x000000FF); Value.push_back(Operande); op = operande(addr,"byte", Value);} } else if (type == "fill"){ QString Operande_prev = excelScenarioSheet.read(idx_row+1, idx_operande-1).toString(); QString Operande = excelScenarioSheet.read(idx_row+1, idx_operande).toString(); QString str_max_length = Operande.mid(1,Operande.indexOf('-')-1); //apparently it is not possible to get the result of the formula... for (int id = 0; id < str_max_length.toInt()-Operande_prev.toUtf8().size()-1; id++) Value.push_back('\0'); op = operande(addr,"fill", Value); } else if ((type == "string")||(type == "dialog")){ QString Operande = (excelScenarioSheet.read(idx_row+1, idx_operande).toString()); Value = Operande.toUtf8(); QTextCodec *codec = QTextCodec::codecForName(OutputDatFileEncoding.toUtf8()); QByteArray Value = codec->fromUnicode(Operande); Value.replace('\n', 1); op = operande(addr,type, Value); } else if (type == "bytearray"){ while(type == "bytearray"){ unsigned char Operande = ((excelScenarioSheet.read(idx_row+1, idx_operande).toInt())& 0x000000FF); Value.push_back(Operande); idx_operande++; type = excelScenarioSheet.read(idx_row, idx_operande).toString(); } op = operande(addr,"bytearray", Value); idx_operande--; } else if (type == "pointer"){ QString Operande = (excelScenarioSheet.read(idx_row+1, idx_operande).toString()); QString RowPointedStr = Operande.right(Operande.length()-2); int actual_row = RowPointedStr.toInt(); Value = GetBytesFromInt(actual_row); op = operande(addr,"pointer", Value); } this->AddOperande(op); idx_operande++; addr = addr + op.getLength(); type = excelScenarioSheet.read(idx_row, idx_operande).toString(); } } int Instruction::get_Nb_operandes(){ return operandes.size(); } operande Instruction::get_operande(int i){ return operandes[i]; } int Instruction::get_addr_instr(){ return this->addr_instr; } void Instruction::WriteDat() { } int Instruction::WriteXLSX(QXlsx::Document &excelScenarioSheet, std::vector<function> funs, int row, int &col) { QXlsx::Format FormatInstr; QXlsx::Format FormatType; QXlsx::Format FormatOP; QColor ColorBg = QColor(qRgb(255,230,210)); FormatType.setHorizontalAlignment(QXlsx::Format::AlignHCenter); FormatType.setVerticalAlignment(QXlsx::Format::AlignVCenter); FormatType.setTextWrap(true); FormatInstr.setHorizontalAlignment(QXlsx::Format::AlignHCenter); FormatInstr.setVerticalAlignment(QXlsx::Format::AlignVCenter); FormatType.setBottomBorderStyle(QXlsx::Format::BorderThin); FormatType.setLeftBorderStyle(QXlsx::Format::BorderThin); FormatType.setRightBorderStyle(QXlsx::Format::BorderThin); FormatType.setTopBorderStyle(QXlsx::Format::BorderThin); FormatType.setPatternBackgroundColor(ColorBg); FormatInstr.setBottomBorderStyle(QXlsx::Format::BorderThin); FormatInstr.setLeftBorderStyle(QXlsx::Format::BorderThin); FormatInstr.setRightBorderStyle(QXlsx::Format::BorderThin); FormatInstr.setTopBorderStyle(QXlsx::Format::BorderThin); FormatOP.setBottomBorderStyle(QXlsx::Format::BorderThin); FormatOP.setLeftBorderStyle(QXlsx::Format::BorderThin); FormatOP.setRightBorderStyle(QXlsx::Format::BorderThin); FormatOP.setTopBorderStyle(QXlsx::Format::BorderThin); FormatType.setFontBold(true); QColor color; color = QColor::fromHsl((int)OPCode,255,185,255); FormatOP.setPatternBackgroundColor(color); excelScenarioSheet.write(row, col + 2, "OP Code",FormatType); excelScenarioSheet.write(row+1, col + 2, OPCode,FormatOP); int col_cnt = 0; for (int idx_op = 0; idx_op<operandes.size(); idx_op++){ QString type = operandes[idx_op].getType(); QByteArray Value = operandes[idx_op].getValue(); if (type == "int"){ excelScenarioSheet.write(row, col + 3+col_cnt, type,FormatType); excelScenarioSheet.write(row+1, col + 3+col_cnt, ReadIntegerFromByteArray(0,Value),FormatInstr); col_cnt++; } else if (type == "float"){ excelScenarioSheet.write(row, col + 3+col_cnt, type,FormatType); excelScenarioSheet.write(row+1, col + 3+col_cnt, ReadFloatFromByteArray(0,Value),FormatInstr); col_cnt++; } else if (type == "short"){ excelScenarioSheet.write(row, col + 3+col_cnt, type,FormatType); excelScenarioSheet.write(row+1, col + 3+col_cnt, (ushort)ReadShortFromByteArray(0,Value),FormatInstr); col_cnt++; } else if (type == "byte"){ excelScenarioSheet.write(row, col + 3+col_cnt, type,FormatType); excelScenarioSheet.write(row+1, col + 3+col_cnt, (unsigned char)Value[0],FormatInstr); col_cnt++; } else if (type == "fill"){ excelScenarioSheet.write(row, col + 3+col_cnt, type,FormatType); excelScenarioSheet.write(row+1, col + 3+col_cnt, "="+QString::number(operandes[idx_op].getBytesToFill())+"-LENB(INDIRECT(ADDRESS("+QString::number(row+1)+","+QString::number(3+col_cnt-1)+")))",FormatInstr); col_cnt++; } else if (type == "bytearray"){ for (int idx_byte = 0; idx_byte<Value.size(); idx_byte++){ excelScenarioSheet.write(row, col + 3+col_cnt, type,FormatType); excelScenarioSheet.write(row+1, col + 3+col_cnt, (unsigned char)Value[idx_byte],FormatInstr); col_cnt++; } } else if (type == "instruction"){ int addr = 0; std::shared_ptr<Instruction> instr = Maker->CreateInstructionFromDAT(addr,Value,0);//function type is 0 here because sub05 is only called by OP Code instructions. int column_instr = col + 3+col_cnt - 2; int cnt; cnt = instr->WriteXLSX(excelScenarioSheet,funs,row,column_instr); col = col + cnt+1; } else if ((type == "string")||(type == "dialog")){ excelScenarioSheet.write(row, col + 3+col_cnt, type,FormatType); QByteArray value_ = Value; value_.replace(1, "\n"); QTextCodec *codec = QTextCodec::codecForName(InputDatFileEncoding.toUtf8()); QString string = codec->toUnicode(value_); excelScenarioSheet.write(row+1, col + 3+col_cnt, string,FormatInstr); col_cnt++; } else if (type == "pointer"){ excelScenarioSheet.write(row, col + 3+col_cnt, type,FormatType); int ID = funs[0].ID; int nb_row = 3; int idx_fun = 0; while (ID != operandes[idx_op].getDestination().FunctionID){ nb_row = nb_row + 1; //row with function name nb_row = nb_row + 2 * funs[idx_fun].InstructionsInFunction.size(); idx_fun++; ID = funs[idx_fun].ID; } nb_row = nb_row + 1; //row with function name nb_row = nb_row + 2 * (operandes[idx_op].getDestination().InstructionID+1); QString ptrExcel = "=A"+QString::number((nb_row)); QXlsx::Format format; format.setBottomBorderStyle(QXlsx::Format::BorderThin); format.setLeftBorderStyle(QXlsx::Format::BorderThin); format.setRightBorderStyle(QXlsx::Format::BorderThin); format.setTopBorderStyle(QXlsx::Format::BorderThin); format.setFontBold(true); QColor FontColor = QColor(qRgb(255,0,0)); format.setFontColor(FontColor); excelScenarioSheet.write(row+1, col + 3+col_cnt, ptrExcel,format); col_cnt++; } } return col_cnt; } void Instruction::set_addr_instr(int i){ addr_instr = i; } /*This version of AddOperande is supposed to check if a string contain illegal xml characters, but I didn't finish it yet. If there is any illegal xml character, every string in the sheet disappears and the file can't be decompiled, this is a problem for some broken files that we would want to restore (example is ply000 from CS3)*/ void Instruction::AddOperande(operande op){ QByteArray value = op.getValue(); if (op.getType()=="string"){ QTextCodec::ConverterState state; QTextCodec *codec = QTextCodec::codecForName(InputDatFileEncoding.toUtf8()); const QString text = codec->toUnicode(value, value.size(), &state); if ((state.invalidChars > 0)||text.contains('\x0B')||text.contains('\x06')||text.contains('\x07')||text.contains('\x08')||text.contains('\x05')||text.contains('\x04')||text.contains('\x03')||text.contains('\x02')) { op.setValue(QByteArray(0)); //operandes.push_back(op); } else{ //qDebug() << "value: " << value; operandes.push_back(op); } } else { operandes.push_back(op); } //if (op.getType()=="pointer") qDebug() << "pointer: " << hex << ReadIntegerFromByteArray(0,value); //if (op.getType()=="string") qDebug() << value; //if (op.getType()=="pointer") qDebug() << "pointer: " << hex << ReadIntegerFromByteArray(0,value); } /*void Instruction::AddOperande(operande op){ operandes.push_back(op); QByteArray value = op.getValue(); QTextCodec *codec = QTextCodec::codecForName("UTF-8"); QString string = codec->toUnicode(value); //if (op.getType()=="string") qDebug() << value; //if (op.getType()=="pointer") qDebug() << "pointer: " << hex << ReadIntegerFromByteArray(0,value); }*/ int Instruction::get_length_in_bytes(){ return getBytes().size(); } uint Instruction::get_OP(){ return OPCode; } QByteArray Instruction::getBytes(){ QByteArray bytes; if (OPCode<=0xFF) bytes.push_back((unsigned char) OPCode); for (std::vector<operande>::iterator it = operandes.begin(); it!=operandes.end();it++) { QByteArray op_bytes = it->getValue(); if (it->getType()=="string") op_bytes.push_back('\x0'); for (int i = 0; i < op_bytes.size(); i++) bytes.push_back(op_bytes[i]); } return bytes; }
12,844
4,101
/* Copyright (c) 2020, Eric Hyer All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "AbstractTab.h" #include <ncurses.h> #include "AbstractWindow.h" #include "EnablednessSetting.h" #include "Layer.h" #include "VisibilityAspect.h" #include "key_codes.h" AbstractTab::AbstractTab() : layers{ std::make_shared< matchable::MatchBox< Layer::Type, std::pair<std::vector<AbstractWindow *>, AbstractWindow *> > >() } { for (auto l : Layer::variants()) layers->mut_at(l).second = nullptr; EnablednessSetting::Borders::grab().add_enabledness_observer([&](){ draw(true); }); Tab::nil.set_AbstractTab(nullptr); } AbstractTab::~AbstractTab() { layers.reset(); active_tab() = nullptr; left_neighbor = Tab::nil; right_neighbor = Tab::nil; } void AbstractTab::add_window(AbstractWindow * win) { if (nullptr == win) return; layers->mut_at(win->get_layer()).first.push_back(win); win->add_tab(AccessKey_AbstractWindow_add_tab(), as_handle()); // guarantee active window by setting first window active if (layers->at(win->get_layer()).first.size() == 1) layers->mut_at(win->get_layer()).second = win; } void AbstractTab::resize() { if (is_active()) for (auto l : Layer::variants()) for (auto w : layers->mut_at(l).first) w->resize(); } void AbstractTab::draw(bool clear_first) { if (is_active()) { for (auto w : layers->mut_at(Layer::Bottom::grab()).first) w->draw(clear_first); if (layer_F_enabled) for (auto w : layers->mut_at(Layer::F::grab()).first) w->draw(clear_first); if (layer_Help_enabled) for (auto w : layers->mut_at(Layer::Help::grab()).first) w->draw(clear_first); } } void AbstractTab::set_active_tab(Tab::Type tab) { if (tab.is_nil()) return; if (nullptr != active_tab()) for (auto l : Layer::variants()) for (auto w : active_tab()->layers->mut_at(l).first) w->disable(VisibilityAspect::TabVisibility::grab()); AbstractWindow const * tab_act_win = tab.as_AbstractTab()->get_active_window(); // synce WindowVisibility aspect for Help layer, specifically: // // if help enabled for old tab then enable help for new tab if not already // and... // if help disabled for old tab then disable help for new tab if not already if (nullptr != active_tab() && nullptr != tab_act_win) { // if help enabled for old/current active_tab() if (nullptr != active_tab()->get_active_window() && active_tab()->get_active_window()->get_layer() == Layer::Help::grab()) { // then enable if help disabled for new active_tab() if (tab_act_win->get_layer() != Layer::Help::grab()) tab.as_AbstractTab()->on_COMMA(); } else // otherwise if help disabled for old/current active_tab() { // then disable if help enabled for new active_tab() if (tab_act_win->get_layer() == Layer::Help::grab()) tab.as_AbstractTab()->on_COMMA(); } } active_tab() = tab.as_AbstractTab(); // enable TabVisibility aspect for each window within each layer if (nullptr != active_tab()) for (auto l : Layer::variants()) for (auto w : active_tab()->layers->mut_at(l).first) w->enable(VisibilityAspect::TabVisibility::grab()); } Tab::Type AbstractTab::get_active_tab() { if (nullptr == active_tab()) return Tab::nil; return active_tab()->as_handle(); } void AbstractTab::set_active_window(AbstractWindow * win) { if (nullptr == win) return; // verify given window exists in the given layer { bool found = false; for (auto w : layers->at(win->get_layer()).first) { if (w == win) { found = true; break; } } if (!found) return; } // need to redraw both old and new active windows layers->mut_at(win->get_layer()).second->mark_dirty(); win->mark_dirty(); layers->mut_at(win->get_layer()).second = win; } AbstractWindow * AbstractTab::get_active_window() { if (layer_Help_enabled) return layers->mut_at(Layer::Help::grab()).second; if (layer_F_enabled) return layers->mut_at(Layer::F::grab()).second; return layers->mut_at(Layer::Bottom::grab()).second; } AbstractWindow * AbstractTab::get_active_window(Layer::Type layer) { return layers->mut_at(layer).second; } void AbstractTab::on_KEY(int key) { if (!is_active()) return; switch (key) { case KEY_F(1) : case KEY_F(2) : case KEY_F(3) : case KEY_F(4) : case KEY_F(5) : case KEY_F(6) : case KEY_F(7) : case KEY_F(8) : case KEY_F(9) : case KEY_F(10) : case KEY_F(11) : case KEY_F(12) : on_ANY_F(); return; case ',' : on_COMMA(); return; case SHIFT_LEFT : on_SHIFT_LEFT(); return; case SHIFT_RIGHT : on_SHIFT_RIGHT(); return; } auto active_win = get_active_window(); if (nullptr != active_win) { if (active_win->get_layer() == Layer::Help::grab()) { switch (key) { case KEY_LEFT : on_SHIFT_LEFT(); return; case KEY_RIGHT : on_SHIFT_RIGHT(); return; } } active_win->on_KEY(key); } } void AbstractTab::on_ANY_F() { if (layer_Help_enabled) return; if (layers->at(Layer::F::grab()).first.size() > 0) toggle_layer(Layer::F::grab(), layer_F_enabled); } void AbstractTab::on_COMMA() { toggle_layer(Layer::Help::grab(), layer_Help_enabled); } void AbstractTab::toggle_layer(Layer::Type layer, bool & layer_enabled) { if (layer_enabled) { // disable layer layer_enabled = false; for (auto w : layers->mut_at(layer).first) w->disable(VisibilityAspect::WindowVisibility::grab()); // mark other layers dirty for (auto l : Layer::variants()) if (l != layer) for (auto w : layers->mut_at(l).first) w->mark_dirty(); } else { // enable layer layer_enabled = true; for (auto w : layers->mut_at(layer).first) w->enable(VisibilityAspect::WindowVisibility::grab()); } } void AbstractTab::on_SHIFT_LEFT() { if (!left_neighbor.is_nil()) AbstractTab::set_active_tab(left_neighbor); } void AbstractTab::on_SHIFT_RIGHT() { if (!right_neighbor.is_nil()) AbstractTab::set_active_tab(right_neighbor); }
8,370
2,741
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CAutoTraceFlag.cpp // // @doc: // Auto object to toggle TF in scope //--------------------------------------------------------------------------- #include "gpos/base.h" #include "gpos/task/CAutoTraceFlag.h" using namespace gpos; //--------------------------------------------------------------------------- // @function: // CAutoTraceFlag::CAutoTraceFlag // // @doc: // ctor // //--------------------------------------------------------------------------- CAutoTraceFlag::CAutoTraceFlag ( ULONG ulTrace, BOOL fVal ) : m_ulTrace(ulTrace), m_fOrig(false) { GPOS_ASSERT(NULL != ITask::PtskSelf()); m_fOrig = ITask::PtskSelf()->FTrace(m_ulTrace, fVal); } //--------------------------------------------------------------------------- // @function: // CAutoTraceFlag::~CAutoTraceFlag // // @doc: // dtor // //--------------------------------------------------------------------------- CAutoTraceFlag::~CAutoTraceFlag() { GPOS_ASSERT(NULL != ITask::PtskSelf()); // reset original value ITask::PtskSelf()->FTrace(m_ulTrace, m_fOrig); } // EOF
1,216
394
/*************************************************************************************************** LICENSE: 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. Author:liu.hao(33852613@163.com) Time:2021-4 info: ***************************************************************************************************/ #include <markcore.h> #include "mkLIRSReplacement.h" MK_DEFINE_MODULE_INSTANCE_VERSION(1, 0, 0); class mkLIRSReplacementOption : public mkIOption { public: virtual bool OnSetValue(const string& key, const string& value) { if("--lir_size" == key) { lir_size = std::stoi(value); return true; } if("--hir_Size" == key) { hir_Size = std::stoi(value); return true; } return false; } virtual void OnApply() { } public: int lir_size = 100; int hir_Size = 100; }; void mkIReplacementBuilder::PushOptions(const string& key, const string& value) { MK_CALL_ONCE_BEGIN g_switch->ClearOption<mkLIRSReplacementOption>(); MK_CALL_ONCE_END g_switch->SetOptions(key, value, false); } std::shared_ptr<mkIReplacement> mkIReplacementBuilder::LIRS(shared_ptr<mkIReplaceValueBuilder> pBuilder) { const auto& lir_size = g_switch->GetOption<mkLIRSReplacementOption>()->lir_size; const auto& hir_Size = g_switch->GetOption<mkLIRSReplacementOption>()->hir_Size; return make_shared<mkLIRSReplacement>(lir_size, hir_Size, pBuilder); }
2,005
647
//========= Copyright Valve Corporation, All rights reserved. ============// #include "cbase.h" #include "ai_basenpc.h" #include "ai_behavior_lead.h" #include "entityapi.h" #include "saverestore.h" #include "saverestoretypes.h" #include "triggers.h" #include "entities/triggers/CChangeLevel.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar g_debug_transitions("g_debug_transitions", "0", FCVAR_NONE, "Set to 1 and restart the map to be warned if the map has no trigger_transition volumes. Set to 2 to see a dump of all entities & associated results during a transition."); LINK_ENTITY_TO_CLASS( trigger_changelevel, CChangeLevel ); // Global Savedata for changelevel trigger BEGIN_DATADESC( CChangeLevel ) DEFINE_AUTO_ARRAY( m_szMapName, FIELD_CHARACTER ), DEFINE_AUTO_ARRAY( m_szLandmarkName, FIELD_CHARACTER ), // DEFINE_FIELD( m_touchTime, FIELD_TIME ), // don't save // DEFINE_FIELD( m_bTouched, FIELD_BOOLEAN ), // Function Pointers DEFINE_FUNCTION( TouchChangeLevel ), DEFINE_INPUTFUNC( FIELD_VOID, "ChangeLevel", InputChangeLevel ), // Outputs DEFINE_OUTPUT( m_OnChangeLevel, "OnChangeLevel"), END_DATADESC() // // Cache user-entity-field values until spawn is called. // bool CChangeLevel::KeyValue( const char *szKeyName, const char *szValue ) { if (FStrEq(szKeyName, "map")) { if (strlen(szValue) >= cchMapNameMost) { Warning( "Map name '%s' too long (32 chars)\n", szValue ); Assert(0); } Q_strncpy(m_szMapName, szValue, sizeof(m_szMapName)); } else if (FStrEq(szKeyName, "landmark")) { if (strlen(szValue) >= cchMapNameMost) { Warning( "Landmark name '%s' too long (32 chars)\n", szValue ); Assert(0); } Q_strncpy(m_szLandmarkName, szValue, sizeof( m_szLandmarkName )); } else return BaseClass::KeyValue( szKeyName, szValue ); return true; } void CChangeLevel::Spawn( void ) { if ( FStrEq( m_szMapName, "" ) ) { Msg( "a trigger_changelevel doesn't have a map" ); } if ( FStrEq( m_szLandmarkName, "" ) ) { Msg( "trigger_changelevel to %s doesn't have a landmark", m_szMapName ); } InitTrigger(); if ( !HasSpawnFlags(SF_CHANGELEVEL_NOTOUCH) ) { SetTouch( &CChangeLevel::TouchChangeLevel ); } // Msg( "TRANSITION: %s (%s)\n", m_szMapName, m_szLandmarkName ); } void CChangeLevel::Activate( void ) { BaseClass::Activate(); if ( gpGlobals->eLoadType == MapLoad_NewGame ) { if ( HasSpawnFlags( SF_CHANGELEVEL_CHAPTER ) ) { VPhysicsInitStatic(); RemoveSolidFlags( FSOLID_NOT_SOLID | FSOLID_TRIGGER ); SetTouch( NULL ); return; } } // Level transitions will bust if they are in solid CBaseEntity *pLandmark = FindLandmark( m_szLandmarkName ); if ( pLandmark ) { int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() ); if ( clusterIndex < 0 ) { Warning( "trigger_changelevel to map %s has a landmark embedded in solid!\n" "This will break level transitions!\n", m_szMapName ); } if ( g_debug_transitions.GetInt() ) { if ( !gEntList.FindEntityByClassname( NULL, "trigger_transition" ) ) { Warning( "Map has no trigger_transition volumes for landmark %s\n", m_szLandmarkName ); } } } m_bTouched = false; } static char st_szNextMap[cchMapNameMost]; static char st_szNextSpot[cchMapNameMost]; // Used to show debug for only the transition volume we're currently in static int g_iDebuggingTransition = 0; CBaseEntity *CChangeLevel::FindLandmark( const char *pLandmarkName ) { CBaseEntity *pentLandmark; pentLandmark = gEntList.FindEntityByName( NULL, pLandmarkName ); while ( pentLandmark ) { // Found the landmark if ( FClassnameIs( pentLandmark, "info_landmark" ) ) return pentLandmark; else pentLandmark = gEntList.FindEntityByName( pentLandmark, pLandmarkName ); } Warning( "Can't find landmark %s\n", pLandmarkName ); return NULL; } //----------------------------------------------------------------------------- // Purpose: Allows level transitions to be triggered by buttons, etc. //----------------------------------------------------------------------------- void CChangeLevel::InputChangeLevel( inputdata_t &inputdata ) { // Ignore changelevel transitions if the player's dead or attempting a challenge if ( gpGlobals->maxClients == 1 ) { CBasePlayer *pPlayer = UTIL_GetLocalPlayer(); if ( pPlayer && ( !pPlayer->IsAlive() || pPlayer->GetBonusChallenge() > 0 ) ) return; } ChangeLevelNow( inputdata.pActivator ); } //----------------------------------------------------------------------------- // Purpose: Performs the level change and fires targets. // Input : pActivator - //----------------------------------------------------------------------------- bool CChangeLevel::IsEntityInTransition( CBaseEntity *pEntity ) { int transitionState = InTransitionVolume(pEntity, m_szLandmarkName); if ( transitionState == TRANSITION_VOLUME_SCREENED_OUT ) { return false; } // look for a landmark entity CBaseEntity *pLandmark = FindLandmark( m_szLandmarkName ); if ( !pLandmark ) return false; // Check to make sure it's also in the PVS of landmark byte pvs[MAX_MAP_CLUSTERS/8]; int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() ); engine->GetPVSForCluster( clusterIndex, sizeof(pvs), pvs ); Vector vecSurroundMins, vecSurroundMaxs; pEntity->CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs ); return engine->CheckBoxInPVS( vecSurroundMins, vecSurroundMaxs, pvs, sizeof( pvs ) ); } void CChangeLevel::NotifyEntitiesOutOfTransition() { CBaseEntity *pEnt = gEntList.FirstEnt(); while ( pEnt ) { // Found the landmark if ( pEnt->ObjectCaps() & FCAP_NOTIFY_ON_TRANSITION ) { variant_t emptyVariant; if ( !(pEnt->ObjectCaps() & (FCAP_ACROSS_TRANSITION|FCAP_FORCE_TRANSITION)) || !IsEntityInTransition( pEnt ) ) { pEnt->AcceptInput( "OutsideTransition", this, this, emptyVariant, 0 ); } else { pEnt->AcceptInput( "InsideTransition", this, this, emptyVariant, 0 ); } } pEnt = gEntList.NextEnt( pEnt ); } } //------------------------------------------------------------------------------ // Purpose : Checks all spawned AIs and prints a warning if any are actively leading // Input : // Output : //------------------------------------------------------------------------------ void CChangeLevel::WarnAboutActiveLead( void ) { int i; CAI_BaseNPC * ai; CAI_BehaviorBase * behavior; for ( i = 0; i < g_AI_Manager.NumAIs(); i++ ) { ai = g_AI_Manager.AccessAIs()[i]; behavior = ai->GetRunningBehavior(); if ( behavior ) { if ( dynamic_cast<CAI_LeadBehavior *>( behavior ) ) { Warning( "Entity '%s' is still actively leading\n", STRING( ai->GetEntityName() ) ); } } } } void CChangeLevel::ChangeLevelNow( CBaseEntity *pActivator ) { CBaseEntity *pLandmark; levellist_t levels[16]; Assert(!FStrEq(m_szMapName, "")); // Don't work in deathmatch if ( g_pGameRules->IsDeathmatch() ) return; // Some people are firing these multiple times in a frame, disable if ( m_bTouched ) return; m_bTouched = true; CBaseEntity *pPlayer = (pActivator && pActivator->IsPlayer()) ? pActivator : UTIL_GetLocalPlayer(); int transitionState = InTransitionVolume(pPlayer, m_szLandmarkName); if ( transitionState == TRANSITION_VOLUME_SCREENED_OUT ) { DevMsg( 2, "Player isn't in the transition volume %s, aborting\n", m_szLandmarkName ); return; } // look for a landmark entity pLandmark = FindLandmark( m_szLandmarkName ); if ( !pLandmark ) return; // no transition volumes, check PVS of landmark if ( transitionState == TRANSITION_VOLUME_NOT_FOUND ) { byte pvs[MAX_MAP_CLUSTERS/8]; int clusterIndex = engine->GetClusterForOrigin( pLandmark->GetAbsOrigin() ); engine->GetPVSForCluster( clusterIndex, sizeof(pvs), pvs ); if ( pPlayer ) { Vector vecSurroundMins, vecSurroundMaxs; pPlayer->CollisionProp()->WorldSpaceSurroundingBounds( &vecSurroundMins, &vecSurroundMaxs ); bool playerInPVS = engine->CheckBoxInPVS( vecSurroundMins, vecSurroundMaxs, pvs, sizeof( pvs ) ); //Assert( playerInPVS ); if ( !playerInPVS ) { Warning( "Player isn't in the landmark's (%s) PVS, aborting\n", m_szLandmarkName ); #ifndef HL1_DLL // HL1 works even with these errors! return; #endif } } } WarnAboutActiveLead(); g_iDebuggingTransition = 0; st_szNextSpot[0] = 0; // Init landmark to NULL Q_strncpy(st_szNextSpot, m_szLandmarkName,sizeof(st_szNextSpot)); // This object will get removed in the call to engine->ChangeLevel, copy the params into "safe" memory Q_strncpy(st_szNextMap, m_szMapName, sizeof(st_szNextMap)); m_hActivator = pActivator; m_OnChangeLevel.FireOutput(pActivator, this); NotifyEntitiesOutOfTransition(); //// Msg( "Level touches %d levels\n", ChangeList( levels, 16 ) ); if ( g_debug_transitions.GetInt() ) { Msg( "CHANGE LEVEL: %s %s\n", st_szNextMap, st_szNextSpot ); } // If we're debugging, don't actually change level if ( g_debug_transitions.GetInt() == 0 ) { engine->ChangeLevel( st_szNextMap, st_szNextSpot ); } else { // Build a change list so we can see what would be transitioning CSaveRestoreData *pSaveData = SaveInit( 0 ); if ( pSaveData ) { g_pGameSaveRestoreBlockSet->PreSave( pSaveData ); pSaveData->levelInfo.connectionCount = BuildChangeList( pSaveData->levelInfo.levelList, MAX_LEVEL_CONNECTIONS ); g_pGameSaveRestoreBlockSet->PostSave(); } SetTouch( NULL ); } } // // GLOBALS ASSUMED SET: st_szNextMap // void CChangeLevel::TouchChangeLevel( CBaseEntity *pOther ) { CBasePlayer *pPlayer = ToBasePlayer(pOther); if ( !pPlayer ) return; if( pPlayer->IsSinglePlayerGameEnding() ) { // Some semblance of deceleration, but allow player to fall normally. // Also, disable controls. Vector vecVelocity = pPlayer->GetAbsVelocity(); vecVelocity.x *= 0.5f; vecVelocity.y *= 0.5f; pPlayer->SetAbsVelocity( vecVelocity ); pPlayer->AddFlag( FL_FROZEN ); return; } if ( !pPlayer->IsInAVehicle() && pPlayer->GetMoveType() == MOVETYPE_NOCLIP ) { DevMsg("In level transition: %s %s\n", st_szNextMap, st_szNextSpot ); return; } ChangeLevelNow( pOther ); } // Add a transition to the list, but ignore duplicates // (a designer may have placed multiple trigger_changelevels with the same landmark) int CChangeLevel::AddTransitionToList( levellist_t *pLevelList, int listCount, const char *pMapName, const char *pLandmarkName, edict_t *pentLandmark ) { int i; if ( !pLevelList || !pMapName || !pLandmarkName || !pentLandmark ) return 0; // Ignore changelevels to the level we're ready in. Mapmakers love to do this! if ( stricmp( pMapName, STRING(gpGlobals->mapname) ) == 0 ) return 0; for ( i = 0; i < listCount; i++ ) { if ( pLevelList[i].pentLandmark == pentLandmark && stricmp( pLevelList[i].mapName, pMapName ) == 0 ) return 0; } Q_strncpy( pLevelList[listCount].mapName, pMapName, sizeof(pLevelList[listCount].mapName) ); Q_strncpy( pLevelList[listCount].landmarkName, pLandmarkName, sizeof(pLevelList[listCount].landmarkName) ); pLevelList[listCount].pentLandmark = pentLandmark; CBaseEntity *ent = CBaseEntity::Instance( pentLandmark ); Assert( ent ); pLevelList[listCount].vecLandmarkOrigin = ent->GetAbsOrigin(); return 1; } int BuildChangeList( levellist_t *pLevelList, int maxList ) { return CChangeLevel::ChangeList( pLevelList, maxList ); } struct collidelist_t { const CPhysCollide *pCollide; Vector origin; QAngle angles; }; // NOTE: This routine is relatively slow. If you need to use it for per-frame work, consider that fact. // UNDONE: Expand this to the full matrix of solid types on each side and move into enginetrace static bool TestEntityTriggerIntersection_Accurate(CBaseEntity *pTrigger, CBaseEntity *pEntity) { Assert(pTrigger->GetSolid() == SOLID_BSP); if (pTrigger->Intersects(pEntity)) // It touches one, it's in the volume { switch (pEntity->GetSolid()) { case SOLID_BBOX: { ICollideable *pCollide = pTrigger->CollisionProp(); Ray_t ray; trace_t tr; ray.Init(pEntity->GetAbsOrigin(), pEntity->GetAbsOrigin(), pEntity->WorldAlignMins(), pEntity->WorldAlignMaxs()); enginetrace->ClipRayToCollideable(ray, MASK_ALL, pCollide, &tr); if (tr.startsolid) return true; } break; case SOLID_BSP: case SOLID_VPHYSICS: { CPhysCollide *pTriggerCollide = modelinfo->GetVCollide(pTrigger->GetModelIndex())->solids[0]; Assert(pTriggerCollide); CUtlVector<collidelist_t> collideList; IPhysicsObject *pList[VPHYSICS_MAX_OBJECT_LIST_COUNT]; int physicsCount = pEntity->VPhysicsGetObjectList(pList, ARRAYSIZE(pList)); if (physicsCount) { for (int i = 0; i < physicsCount; i++) { const CPhysCollide *pCollide = pList[i]->GetCollide(); if (pCollide) { collidelist_t element; element.pCollide = pCollide; pList[i]->GetPosition(&element.origin, &element.angles); collideList.AddToTail(element); } } } else { vcollide_t *pVCollide = modelinfo->GetVCollide(pEntity->GetModelIndex()); if (pVCollide && pVCollide->solidCount) { collidelist_t element; element.pCollide = pVCollide->solids[0]; element.origin = pEntity->GetAbsOrigin(); element.angles = pEntity->GetAbsAngles(); collideList.AddToTail(element); } } for (int i = collideList.Count() - 1; i >= 0; --i) { const collidelist_t &element = collideList[i]; trace_t tr; physcollision->TraceCollide(element.origin, element.origin, element.pCollide, element.angles, pTriggerCollide, pTrigger->GetAbsOrigin(), pTrigger->GetAbsAngles(), &tr); if (tr.startsolid) return true; } } break; default: return true; } } return false; } int CChangeLevel::InTransitionVolume(CBaseEntity *pEntity, const char *pVolumeName) { CBaseEntity *pVolume; if (pEntity->ObjectCaps() & FCAP_FORCE_TRANSITION) return TRANSITION_VOLUME_PASSED; // If you're following another entity, follow it through the transition (weapons follow the player) pEntity = pEntity->GetRootMoveParent(); int inVolume = TRANSITION_VOLUME_NOT_FOUND; // Unless we find a trigger_transition, everything is in the volume pVolume = gEntList.FindEntityByName(NULL, pVolumeName); while (pVolume) { if (pVolume && FClassnameIs(pVolume, "trigger_transition")) { if (TestEntityTriggerIntersection_Accurate(pVolume, pEntity)) // It touches one, it's in the volume return TRANSITION_VOLUME_PASSED; inVolume = TRANSITION_VOLUME_SCREENED_OUT; // Found a trigger_transition, but I don't intersect it -- if I don't find another, don't go! } pVolume = gEntList.FindEntityByName(pVolume, pVolumeName); } return inVolume; } //------------------------------------------------------------------------------ // Builds the list of entities to save when moving across a transition //------------------------------------------------------------------------------ int CChangeLevel::BuildChangeLevelList(levellist_t *pLevelList, int maxList) { int nCount = 0; CBaseEntity *pentChangelevel = gEntList.FindEntityByClassname(NULL, "trigger_changelevel"); while (pentChangelevel) { CChangeLevel *pTrigger = dynamic_cast<CChangeLevel *>(pentChangelevel); if (pTrigger) { // Find the corresponding landmark CBaseEntity *pentLandmark = FindLandmark(pTrigger->m_szLandmarkName); if (pentLandmark) { // Build a list of unique transitions if (AddTransitionToList(pLevelList, nCount, pTrigger->m_szMapName, pTrigger->m_szLandmarkName, pentLandmark->edict())) { ++nCount; if (nCount >= maxList) // FULL!! break; } } } pentChangelevel = gEntList.FindEntityByClassname(pentChangelevel, "trigger_changelevel"); } return nCount; } //------------------------------------------------------------------------------ // Adds a single entity to the transition list, if appropriate. Returns the new count //------------------------------------------------------------------------------ int CChangeLevel::ComputeEntitySaveFlags(CBaseEntity *pEntity) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { Msg("Trying %s (%s): ", pEntity->GetClassname(), pEntity->GetDebugName()); } int caps = pEntity->ObjectCaps(); if (caps & FCAP_DONT_SAVE) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { Msg("IGNORED due to being marked \"Don't save\".\n"); } return 0; } // If this entity can be moved or is global, mark it int flags = 0; if (caps & FCAP_ACROSS_TRANSITION) { flags |= FENTTABLE_MOVEABLE; } if (pEntity->m_iGlobalname != NULL_STRING && !pEntity->IsDormant()) { flags |= FENTTABLE_GLOBAL; } if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE && !flags) { Msg("IGNORED, no across_transition flag & no globalname\n"); } return flags; } //------------------------------------------------------------------------------ // Adds a single entity to the transition list, if appropriate. Returns the new count //------------------------------------------------------------------------------ inline int CChangeLevel::AddEntityToTransitionList(CBaseEntity *pEntity, int flags, int nCount, CBaseEntity **ppEntList, int *pEntityFlags) { ppEntList[nCount] = pEntity; pEntityFlags[nCount] = flags; ++nCount; // If we're debugging, make it visible if (g_iDebuggingTransition) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { // In verbose mode we've already printed out what the entity is Msg("ADDED.\n"); } else { // In non-verbose mode, we just print this line Msg("ADDED %s (%s) to transition.\n", pEntity->GetClassname(), pEntity->GetDebugName()); } pEntity->m_debugOverlays |= (OVERLAY_BBOX_BIT | OVERLAY_NAME_BIT); } return nCount; } //------------------------------------------------------------------------------ // Builds the list of entities to bring across a particular transition //------------------------------------------------------------------------------ int CChangeLevel::BuildEntityTransitionList(CBaseEntity *pLandmarkEntity, const char *pLandmarkName, CBaseEntity **ppEntList, int *pEntityFlags, int nMaxList) { int iEntity = 0; // Only show debug for the transition to the level we're going to if (g_debug_transitions.GetInt() && pLandmarkEntity->NameMatches(st_szNextSpot)) { g_iDebuggingTransition = g_debug_transitions.GetInt(); // Show us where the landmark entity is pLandmarkEntity->m_debugOverlays |= (OVERLAY_PIVOT_BIT | OVERLAY_BBOX_BIT | OVERLAY_NAME_BIT); } else { g_iDebuggingTransition = 0; } // Follow the linked list of entities in the PVS of the transition landmark CBaseEntity *pEntity = NULL; while ((pEntity = UTIL_EntitiesInPVS(pLandmarkEntity, pEntity)) != NULL) { int flags = ComputeEntitySaveFlags(pEntity); if (!flags) continue; // Check to make sure the entity isn't screened out by a trigger_transition if (!InTransitionVolume(pEntity, pLandmarkName)) { if (g_iDebuggingTransition == DEBUG_TRANSITIONS_VERBOSE) { Msg("IGNORED, outside transition volume.\n"); } continue; } if (iEntity >= nMaxList) { Warning("Too many entities across a transition!\n"); Assert(0); return iEntity; } iEntity = AddEntityToTransitionList(pEntity, flags, iEntity, ppEntList, pEntityFlags); } return iEntity; } //------------------------------------------------------------------------------ // Tests bits in a bitfield //------------------------------------------------------------------------------ static inline bool IsBitSet(char *pBuf, int nBit) { return (pBuf[nBit >> 3] & (1 << (nBit & 0x7))) != 0; } static inline void Set(char *pBuf, int nBit) { pBuf[nBit >> 3] |= 1 << (nBit & 0x7); } //------------------------------------------------------------------------------ // Adds in all entities depended on by entities near the transition //------------------------------------------------------------------------------ #define MAX_ENTITY_BYTE_COUNT (NUM_ENT_ENTRIES >> 3) int CChangeLevel::AddDependentEntities(int nCount, CBaseEntity **ppEntList, int *pEntityFlags, int nMaxList) { char pEntitiesSaved[MAX_ENTITY_BYTE_COUNT]; memset(pEntitiesSaved, 0, MAX_ENTITY_BYTE_COUNT * sizeof(char)); // Populate the initial bitfield int i; for (i = 0; i < nCount; ++i) { // NOTE: Must use GetEntryIndex because we're saving non-networked entities int nEntIndex = ppEntList[i]->GetRefEHandle().GetEntryIndex(); // We shouldn't already have this entity in the list! Assert(!IsBitSet(pEntitiesSaved, nEntIndex)); // Mark the entity as being in the list Set(pEntitiesSaved, nEntIndex); } IEntitySaveUtils *pSaveUtils = GetEntitySaveUtils(); // Iterate over entities whose dependencies we've not yet processed // NOTE: nCount will change value during this loop in AddEntityToTransitionList for (i = 0; i < nCount; ++i) { CBaseEntity *pEntity = ppEntList[i]; // Find dependencies in the hash. int nDepCount = pSaveUtils->GetEntityDependencyCount(pEntity); if (!nDepCount) continue; CBaseEntity **ppDependentEntities = (CBaseEntity**)stackalloc(nDepCount * sizeof(CBaseEntity*)); pSaveUtils->GetEntityDependencies(pEntity, nDepCount, ppDependentEntities); for (int j = 0; j < nDepCount; ++j) { CBaseEntity *pDependent = ppDependentEntities[j]; if (!pDependent) continue; // NOTE: Must use GetEntryIndex because we're saving non-networked entities int nEntIndex = pDependent->GetRefEHandle().GetEntryIndex(); // Don't re-add it if it's already in the list if (IsBitSet(pEntitiesSaved, nEntIndex)) continue; // Mark the entity as being in the list Set(pEntitiesSaved, nEntIndex); int flags = ComputeEntitySaveFlags(pEntity); if (flags) { if (nCount >= nMaxList) { Warning("Too many entities across a transition!\n"); Assert(0); return false; } if (g_debug_transitions.GetInt()) { Msg("ADDED DEPENDANCY: %s (%s)\n", pEntity->GetClassname(), pEntity->GetDebugName()); } nCount = AddEntityToTransitionList(pEntity, flags, nCount, ppEntList, pEntityFlags); } else { Warning("Warning!! Save dependency is linked to an entity that doesn't want to be saved!\n"); } } } return nCount; } //------------------------------------------------------------------------------ // This builds the list of all transitions on this level and which entities // are in their PVS's and can / should be moved across. //------------------------------------------------------------------------------ // We can only ever move 512 entities across a transition #define MAX_ENTITY 512 // FIXME: This has grown into a complicated beast. Can we make this more elegant? int CChangeLevel::ChangeList(levellist_t *pLevelList, int maxList) { // Find all of the possible level changes on this BSP int count = BuildChangeLevelList(pLevelList, maxList); if (!gpGlobals->pSaveData || (static_cast<CSaveRestoreData *>(gpGlobals->pSaveData)->NumEntities() == 0)) return count; CSave saveHelper(static_cast<CSaveRestoreData *>(gpGlobals->pSaveData)); // For each level change, find nearby entities and save them int i; for (i = 0; i < count; i++) { CBaseEntity *pEntList[MAX_ENTITY]; int entityFlags[MAX_ENTITY]; // First, figure out which entities are near the transition CBaseEntity *pLandmarkEntity = CBaseEntity::Instance(pLevelList[i].pentLandmark); int iEntity = BuildEntityTransitionList(pLandmarkEntity, pLevelList[i].landmarkName, pEntList, entityFlags, MAX_ENTITY); // FIXME: Activate if we have a dependency problem on level transition // Next, add in all entities depended on by entities near the transition // iEntity = AddDependentEntities( iEntity, pEntList, entityFlags, MAX_ENTITY ); int j; for (j = 0; j < iEntity; j++) { // Mark entity table with 1<<i int index = saveHelper.EntityIndex(pEntList[j]); // Flag it with the level number saveHelper.EntityFlagsSet(index, entityFlags[j] | (1 << i)); } } return count; }
24,133
8,979
// Copyright (c) 2007-2009 Google Inc. // Copyright (c) 2006-2007 Jaiku Ltd. // Copyright (c) 2002-2006 Mika Raento and Renaud Petit // // This software is licensed at your choice under either 1 or 2 below. // // 1. MIT License // // 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. // // 2. Gnu General Public license 2.0 // // 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. // // // This file is part of the JaikuEngine mobile client. #include "csd_calendar.h" EXPORT_C const TTypeName& TBBCalendarEvent::Type() const { return KCalendarEventType; } EXPORT_C TBool TBBCalendarEvent::Equals(const MBBData* aRhs) const { const TBBCalendarEvent* rhs=bb_cast<TBBCalendarEvent>(aRhs); return (rhs && *this==*rhs); } EXPORT_C const TTypeName& TBBCalendarEvent::StaticType() { return KCalendarEventType; } EXPORT_C const MBBData* TBBCalendarEvent::Part(TUint aPartNo) const { switch(aPartNo) { case 0: return &iStartTime; case 1: return &iDescription; case 2: return &iEndTime; case 3: return &iEventId; default: return 0; } } _LIT(KDescription, "description"); _LIT(KStartTime, "start_time"); _LIT(KEndTime, "end_time"); _LIT(KEventId, "eventid"); EXPORT_C TBBCalendarEvent::TBBCalendarEvent(const TDesC& aName) : TBBCompoundData(aName), iDescription(KDescription), iStartTime(KStartTime), iEndTime(KEndTime), iEventId(KEventId) { } EXPORT_C bool TBBCalendarEvent::operator==(const TBBCalendarEvent& aRhs) const { return ( iDescription==aRhs.iDescription && iStartTime()==aRhs.iStartTime() && iEndTime()==aRhs.iEndTime() && iEventId()==aRhs.iEventId() ); } _LIT(KSemicolon, ";"); EXPORT_C const TDesC& TBBCalendarEvent::StringSep(TUint aBeforePart) const { if (aBeforePart>0 && aBeforePart<=3) return KSemicolon; else return KNullDesC; } EXPORT_C TBBCalendarEvent& TBBCalendarEvent::operator=(const TBBCalendarEvent& aRhs) { iDescription()=aRhs.iDescription(); iStartTime()=aRhs.iStartTime(); iEndTime()=aRhs.iEndTime(); iEventId()=aRhs.iEventId(); return *this; } EXPORT_C MBBData* TBBCalendarEvent::CloneL(const TDesC& Name) const { TBBCalendarEvent* ret=new (ELeave) TBBCalendarEvent(Name); *ret=*this; return ret; } EXPORT_C const TTypeName& TBBCalendar::Type() const { return KCalendarType; } EXPORT_C TBool TBBCalendar::Equals(const MBBData* aRhs) const { const TBBCalendar* rhs=bb_cast<TBBCalendar>(aRhs); return (rhs && *this==*rhs); } EXPORT_C const TTypeName& TBBCalendar::StaticType() { return KCalendarType; } EXPORT_C const MBBData* TBBCalendar::Part(TUint aPartNo) const { switch (aPartNo) { case 0: return &iPrevious; case 1: return &iCurrent; case 2: return &iNext; default: return 0; } } _LIT(KPrevious, "previous"); _LIT(KCurrent, "current"); _LIT(KNext, "next"); EXPORT_C TBBCalendar::TBBCalendar() : TBBCompoundData(KCalendar), iPrevious(KPrevious), iCurrent(KCurrent), iNext(KNext), iCreatedVersion(2), iUseVersion(2) { } EXPORT_C TBBCalendar::TBBCalendar(TUint aVersion) : TBBCompoundData(KCalendar), iPrevious(KPrevious), iCurrent(KCurrent), iNext(KNext), iCreatedVersion(aVersion), iUseVersion(2) { } EXPORT_C void TBBCalendar::InternalizeL(RReadStream& aStream) { iUseVersion=iCreatedVersion; TBBCompoundData::InternalizeL(aStream); iUseVersion=2; } EXPORT_C bool TBBCalendar::operator==(const TBBCalendar& aRhs) const { return ( iPrevious==aRhs.iPrevious && iCurrent==aRhs.iCurrent && iNext == aRhs.iNext ); } _LIT(KHash, "#"); EXPORT_C const TDesC& TBBCalendar::StringSep(TUint aBeforePart) const { if (aBeforePart>0 && aBeforePart<=2) return KHash; else return KNullDesC; } EXPORT_C TBBCalendar& TBBCalendar::operator=(const TBBCalendar& aRhs) { iPrevious=aRhs.iPrevious; iCurrent=aRhs.iCurrent; iNext = aRhs.iNext; return *this; } EXPORT_C MBBData* TBBCalendar::CloneL(const TDesC& ) const { TBBCalendar* ret=new (ELeave) TBBCalendar; *ret=*this; return ret; } EXPORT_C MNestedXmlHandler* TBBCalendar::FromXmlL(MNestedXmlHandler* aParent, CXmlParser* aParser, HBufC*& aBuf, TBool aCheckType) { MNestedXmlHandler* ret=TBBCompoundData::FromXmlL(aParent, aParser, aBuf, aCheckType); ret->iIgnoreOffset=ETrue; return ret; } EXPORT_C void TBBCalendar::IntoXmlL(MBBExternalizer* aBuf, TBool aIncludeType) const { TTimeIntervalSeconds offs=aBuf->iOffset; aBuf->iOffset=TTimeIntervalSeconds(0); TRAPD(err, TBBCompoundData::IntoXmlL(aBuf, aIncludeType)); aBuf->iOffset==offs; User::LeaveIfError(err); }
6,148
2,434
class Solution { public: vector<int> addToArrayForm(vector<int>& A, int K) { vector<int> result; int i = A.size(); int carry = K; while(--i >= 0 || carry > 0) { if(i >= 0) carry += A[i]; result.push_back(carry % 10); carry /= 10; } reverse(result.begin(), result.end()); return result; } };
453
147
/* * Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2012 - 2012 FrenchCORE <http://www.frcore.com/> * * 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, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Boss_Onyxia SD%Complete: 95 SDComment: <Known bugs> Ground visual for Deep Breath effect; Not summoning whelps on phase 3 (lacks info) </Known bugs> SDCategory: Onyxia's Lair EndScriptData */ #include "ScriptPCH.h" #include "onyxias_lair.h" enum eYells { SAY_AGGRO = -1249000, SAY_KILL = -1249001, SAY_PHASE_2_TRANS = -1249002, SAY_PHASE_3_TRANS = -1249003, EMOTE_BREATH = -1249004, }; enum eSpells { // Phase 1 spells SPELL_WING_BUFFET = 18500, SPELL_FLAME_BREATH = 18435, SPELL_CLEAVE = 68868, SPELL_TAIL_SWEEP = 68867, // Phase 2 spells SPELL_DEEP_BREATH = 23461, SPELL_FIREBALL = 18392, //Not much choise about these. We have to make own defintion on the direction/start-end point SPELL_BREATH_NORTH_TO_SOUTH = 17086, // 20x in "array" SPELL_BREATH_SOUTH_TO_NORTH = 18351, // 11x in "array" SPELL_BREATH_EAST_TO_WEST = 18576, // 7x in "array" SPELL_BREATH_WEST_TO_EAST = 18609, // 7x in "array" SPELL_BREATH_SE_TO_NW = 18564, // 12x in "array" SPELL_BREATH_NW_TO_SE = 18584, // 12x in "array" SPELL_BREATH_SW_TO_NE = 18596, // 12x in "array" SPELL_BREATH_NE_TO_SW = 18617, // 12x in "array" //SPELL_BREATH = 21131, // 8x in "array", different initial cast than the other arrays // Phase 3 spells SPELL_BELLOWING_ROAR = 18431, SPELL_LAIRGUARDCLEAVE = 15284, SPELL_LAIRGUARDBLASTNOVA = 68958, SPELL_LAIRGUARDIGNITE = 68960 }; struct sOnyxMove { uint32 uiLocId; uint32 uiLocIdEnd; uint32 uiSpellId; float fX, fY, fZ; }; static sOnyxMove aMoveData[]= { {0, 1, SPELL_BREATH_WEST_TO_EAST, -33.5561f, -182.682f, -56.9457f}, //west {1, 0, SPELL_BREATH_EAST_TO_WEST, -31.4963f, -250.123f, -55.1278f}, //east {2, 4, SPELL_BREATH_NW_TO_SE, 6.8951f, -180.246f, -55.896f}, //north-west {3, 5, SPELL_BREATH_NE_TO_SW, 10.2191f, -247.912f, -55.896f}, //north-east {4, 2, SPELL_BREATH_SE_TO_NW, -63.5156f, -240.096f, -55.477f}, //south-east {5, 3, SPELL_BREATH_SW_TO_NE, -58.2509f, -189.020f, -55.790f}, //south-west {6, 7, SPELL_BREATH_SOUTH_TO_NORTH, -65.8444f, -213.809f, -55.2985f}, //south {7, 6, SPELL_BREATH_NORTH_TO_SOUTH, 22.8763f, -217.152f, -55.0548f}, //north }; const Position MiddleRoomLocation = {-23.6155f, -215.357f, -55.7344f, 0.0f}; const Position Phase2Location = {-80.924f, -214.299f, -82.942f, 0.0f}; static Position aSpawnLocations[3]= { //Whelps {-30.127f, -254.463f, -89.440f, 0.0f}, {-30.817f, -177.106f, -89.258f, 0.0f}, //Lair Guard {-145.950f, -212.831f, -68.659f, 0.0f} }; class boss_onyxia : public CreatureScript { public: boss_onyxia() : CreatureScript("boss_onyxia") { } CreatureAI* GetAI(Creature* creature) const { return new boss_onyxiaAI (creature); } struct boss_onyxiaAI : public ScriptedAI { boss_onyxiaAI(Creature* creature) : ScriptedAI(creature), Summons(me) { m_instance = creature->GetInstanceScript(); Reset(); me->ApplySpellImmune(0, IMMUNITY_EFFECT, SPELL_EFFECT_KNOCK_BACK, true); me->ApplySpellImmune(0, IMMUNITY_ID, 49560, true); // Death Grip jump effect } InstanceScript* m_instance; SummonList Summons; uint32 m_uiPhase; uint32 m_uiFlameBreathTimer; uint32 m_uiCleaveTimer; uint32 m_uiTailSweepTimer; uint32 m_uiWingBuffetTimer; uint32 m_uiMovePoint; uint32 m_uiMovementTimer; sOnyxMove* m_pPointData; uint32 m_uiFireballTimer; uint32 m_uiWhelpTimer; uint32 m_uiLairGuardTimer; uint32 m_uiDeepBreathTimer; uint32 m_uiBellowingRoarTimer; uint8 m_uiSummonWhelpCount; bool m_bIsMoving; void Reset() { if (!IsCombatMovement()) SetCombatMovement(true); m_uiPhase = PHASE_START; m_uiFlameBreathTimer = urand(10000, 20000); m_uiTailSweepTimer = urand(15000, 20000); m_uiCleaveTimer = urand(2000, 5000); m_uiWingBuffetTimer = urand(10000, 20000); m_uiMovePoint = urand(0, 5); m_uiMovementTimer = 14000; m_pPointData = GetMoveData(); m_uiFireballTimer = 15000; m_uiWhelpTimer = 60000; m_uiLairGuardTimer = 60000; m_uiDeepBreathTimer = 85000; m_uiBellowingRoarTimer = 30000; Summons.DespawnAll(); m_uiSummonWhelpCount = 0; m_bIsMoving = false; if (m_instance) { m_instance->SetData(DATA_ONYXIA, NOT_STARTED); m_instance->SetData(DATA_ONYXIA_PHASE, m_uiPhase); m_instance->DoStopTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEV_TIMED_START_EVENT); } } void EnterCombat(Unit* /*who*/) { DoScriptText(SAY_AGGRO, me); me->SetInCombatWithZone(); me->ApplySpellImmune(0, IMMUNITY_MECHANIC, MECHANIC_GRIP, true); if (m_instance) { m_instance->SetData(DATA_ONYXIA, IN_PROGRESS); m_instance->DoStartTimedAchievement(ACHIEVEMENT_TIMED_TYPE_EVENT, ACHIEV_TIMED_START_EVENT); } } void JustDied(Unit* /*killer*/) { if (m_instance) m_instance->SetData(DATA_ONYXIA, DONE); Summons.DespawnAll(); } void JustSummoned(Creature* summoned) { summoned->SetInCombatWithZone(); if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) summoned->AI()->AttackStart(target); switch (summoned->GetEntry()) { case NPC_WHELP: ++m_uiSummonWhelpCount; break; case NPC_LAIRGUARD: summoned->setActive(true); break; } Summons.Summon(summoned); } void SummonedCreatureDespawn(Creature* summon) { Summons.Despawn(summon); } void KilledUnit(Unit* /*victim*/) { DoScriptText(SAY_KILL, me); } void SpellHit(Unit* /*pCaster*/, const SpellEntry* pSpell) { if (pSpell->Id == SPELL_BREATH_EAST_TO_WEST || pSpell->Id == SPELL_BREATH_WEST_TO_EAST || pSpell->Id == SPELL_BREATH_SE_TO_NW || pSpell->Id == SPELL_BREATH_NW_TO_SE || pSpell->Id == SPELL_BREATH_SW_TO_NE || pSpell->Id == SPELL_BREATH_NE_TO_SW) { m_pPointData = GetMoveData(); m_uiMovePoint = m_pPointData->uiLocIdEnd; me->SetSpeed(MOVE_FLIGHT, 1.5f); me->GetMotionMaster()->MovePoint(8, MiddleRoomLocation); } } void MovementInform(uint32 type, uint32 id) { if (type == POINT_MOTION_TYPE) { switch (id) { case 8: m_pPointData = GetMoveData(); if (m_pPointData) { me->SetSpeed(MOVE_FLIGHT, 1.0f); me->GetMotionMaster()->MovePoint(m_pPointData->uiLocId, m_pPointData->fX, m_pPointData->fY, m_pPointData->fZ); } break; case 9: me->GetMotionMaster()->MoveChase(me->getVictim()); m_uiBellowingRoarTimer = 1000; break; case 10: me->SetFlying(true); me->GetMotionMaster()->MovePoint(11, Phase2Location.GetPositionX(), Phase2Location.GetPositionY(), Phase2Location.GetPositionZ()+25); me->SetSpeed(MOVE_FLIGHT, 1.0f); DoScriptText(SAY_PHASE_2_TRANS, me); if (m_instance) m_instance->SetData(DATA_ONYXIA_PHASE, m_uiPhase); m_uiWhelpTimer = 5000; m_uiLairGuardTimer = 15000; break; case 11: if (m_pPointData) me->GetMotionMaster()->MovePoint(m_pPointData->uiLocId, m_pPointData->fX, m_pPointData->fY, m_pPointData->fZ); me->GetMotionMaster()->Clear(false); me->GetMotionMaster()->MoveIdle(); break; default: m_bIsMoving = false; break; } } } void SpellHitTarget(Unit* target, const SpellEntry* pSpell) { //Workaround - Couldn't find a way to group this spells (All Eruption) if (((pSpell->Id >= 17086 && pSpell->Id <= 17095) || (pSpell->Id == 17097) || (pSpell->Id >= 18351 && pSpell->Id <= 18361) || (pSpell->Id >= 18564 && pSpell->Id <= 18576) || (pSpell->Id >= 18578 && pSpell->Id <= 18607) || (pSpell->Id == 18609) || (pSpell->Id >= 18611 && pSpell->Id <= 18628) || (pSpell->Id >= 21132 && pSpell->Id <= 21133) || (pSpell->Id >= 21135 && pSpell->Id <= 21139) || (pSpell->Id >= 22191 && pSpell->Id <= 22202) || (pSpell->Id >= 22267 && pSpell->Id <= 22268)) && (target->GetTypeId() == TYPEID_PLAYER)) { if (m_instance) { m_instance->SetData(DATA_SHE_DEEP_BREATH_MORE, FAIL); } } } sOnyxMove* GetMoveData() { uint32 uiMaxCount = sizeof(aMoveData)/sizeof(sOnyxMove); for (uint32 i = 0; i < uiMaxCount; ++i) { if (aMoveData[i].uiLocId == m_uiMovePoint) return &aMoveData[i]; } return NULL; } void SetNextRandomPoint() { uint32 uiMaxCount = sizeof(aMoveData)/sizeof(sOnyxMove); uint32 iTemp = rand()%(uiMaxCount-1); if (iTemp >= m_uiMovePoint) ++iTemp; m_uiMovePoint = iTemp; } void UpdateAI(const uint32 uiDiff) { if (!UpdateVictim()) return; //Common to PHASE_START && PHASE_END if (m_uiPhase == PHASE_START || m_uiPhase == PHASE_END) { //Specific to PHASE_START || PHASE_END if (m_uiPhase == PHASE_START) { if (HealthBelowPct(60)) { SetCombatMovement(false); m_uiPhase = PHASE_BREATH; me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true); me->ApplySpellImmune(0, IMMUNITY_EFFECT,SPELL_EFFECT_ATTACK_ME, true); me->GetMotionMaster()->MovePoint(10, Phase2Location); return; } } else { if (m_uiBellowingRoarTimer <= uiDiff) { DoCastVictim(SPELL_BELLOWING_ROAR); // Eruption GameObject* pFloor = NULL; Trinity::GameObjectInRangeCheck check(me->GetPositionX(), me->GetPositionY(), me->GetPositionZ(), 15); Trinity::GameObjectLastSearcher<Trinity::GameObjectInRangeCheck> searcher(me, pFloor, check); me->VisitNearbyGridObject(30, searcher); if (m_instance && pFloor) m_instance->SetData64(DATA_FLOOR_ERUPTION_GUID, pFloor->GetGUID()); m_uiBellowingRoarTimer = 30000; } else m_uiBellowingRoarTimer -= uiDiff; } if (m_uiFlameBreathTimer <= uiDiff) { DoCastVictim(SPELL_FLAME_BREATH); m_uiFlameBreathTimer = urand(10000, 20000); } else m_uiFlameBreathTimer -= uiDiff; if (m_uiTailSweepTimer <= uiDiff) { DoCastAOE(SPELL_TAIL_SWEEP); m_uiTailSweepTimer = urand(15000, 20000); } else m_uiTailSweepTimer -= uiDiff; if (m_uiCleaveTimer <= uiDiff) { DoCastVictim(SPELL_CLEAVE); m_uiCleaveTimer = urand(2000, 5000); } else m_uiCleaveTimer -= uiDiff; if (m_uiWingBuffetTimer <= uiDiff) { DoCastVictim(SPELL_WING_BUFFET); m_uiWingBuffetTimer = urand(15000, 30000); } else m_uiWingBuffetTimer -= uiDiff; DoMeleeAttackIfReady(); } else { if (HealthBelowPct(40)) { m_uiPhase = PHASE_END; if (m_instance) m_instance->SetData(DATA_ONYXIA_PHASE, m_uiPhase); DoScriptText(SAY_PHASE_3_TRANS, me); SetCombatMovement(true); me->SetFlying(false); m_bIsMoving = false; me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, false); me->ApplySpellImmune(0, IMMUNITY_EFFECT,SPELL_EFFECT_ATTACK_ME, false); me->GetMotionMaster()->MovePoint(9,me->GetHomePosition()); return; } if (m_uiDeepBreathTimer <= uiDiff) { if (!m_bIsMoving) { if (me->IsNonMeleeSpellCasted(false)) me->InterruptNonMeleeSpells(false); DoScriptText(EMOTE_BREATH, me); DoCast(me, m_pPointData->uiSpellId); m_uiDeepBreathTimer = 70000; } } else m_uiDeepBreathTimer -= uiDiff; if (m_uiMovementTimer <= uiDiff) { if (!m_bIsMoving) { SetNextRandomPoint(); m_pPointData = GetMoveData(); if (!m_pPointData) return; me->GetMotionMaster()->MovePoint(m_pPointData->uiLocId, m_pPointData->fX, m_pPointData->fY, m_pPointData->fZ); m_bIsMoving = true; m_uiMovementTimer = 25000; } } else m_uiMovementTimer -= uiDiff; if (m_uiFireballTimer <= uiDiff) { if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() != POINT_MOTION_TYPE) { if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_FIREBALL); m_uiFireballTimer = 8000; } } else m_uiFireballTimer -= uiDiff; if (m_uiLairGuardTimer <= uiDiff) { me->SummonCreature(NPC_LAIRGUARD, aSpawnLocations[2].GetPositionX(), aSpawnLocations[2].GetPositionY(), aSpawnLocations[2].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); m_uiLairGuardTimer = 30000; } else m_uiLairGuardTimer -= uiDiff; if (m_uiWhelpTimer <= uiDiff) { me->SummonCreature(NPC_WHELP, aSpawnLocations[0].GetPositionX(), aSpawnLocations[0].GetPositionY(), aSpawnLocations[0].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); me->SummonCreature(NPC_WHELP, aSpawnLocations[1].GetPositionX(), aSpawnLocations[1].GetPositionY(), aSpawnLocations[1].GetPositionZ(), 0.0f, TEMPSUMMON_CORPSE_DESPAWN); if (m_uiSummonWhelpCount >= RAID_MODE(20, 40)) { m_uiSummonWhelpCount = 0; m_uiWhelpTimer = 90000; } else m_uiWhelpTimer = 500; } else m_uiWhelpTimer -= uiDiff; } } }; }; class npc_onyxia_lairguard : public CreatureScript { public: npc_onyxia_lairguard() : CreatureScript("npc_onyxia_lairguard") { } CreatureAI* GetAI(Creature* creature) const { return new npc_onyxia_lairguardAI(creature); } struct npc_onyxia_lairguardAI : public ScriptedAI { npc_onyxia_lairguardAI(Creature* creature) : ScriptedAI(creature) { m_instance = creature->GetInstanceScript(); Reset(); } InstanceScript* m_instance; uint32 m_uiLairGuardCleaveTimer; bool novadone; bool ignitedone; void Reset() { novadone = false; ignitedone = false; m_uiLairGuardCleaveTimer = urand(5000, 10000); } void UpdateAI(const uint32 uiDiff) { if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STAT_CASTING)) return; if (!ignitedone) { DoCast(me, SPELL_LAIRGUARDIGNITE); ignitedone = true; } if (!novadone && HealthBelowPct(25)) { DoCast(me, SPELL_LAIRGUARDBLASTNOVA, true); novadone = true; } if (m_uiLairGuardCleaveTimer <= uiDiff) { DoCast(me->getVictim(), SPELL_LAIRGUARDCLEAVE); m_uiLairGuardCleaveTimer = urand(5000, 10000); } else m_uiLairGuardCleaveTimer -= uiDiff; DoMeleeAttackIfReady(); } }; }; void AddSC_boss_onyxia() { new boss_onyxia(); new npc_onyxia_lairguard(); }
20,074
7,228
/* core/technology.cpp: Extracting technology information from an AST. * * Copyright 2019 Adrian "ArdiMaster" Welcker * * 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 "technology.h" #include "model_private_macros.h" #include "parser.h" using Parsing::AstNode; namespace Galaxy { Technology::Technology(QObject *parent) : QObject(parent) {} const QString &Technology::getName() const { return name; } const QStringList &Technology::getRequirements() const { return requirements; } bool Technology::getIsStartingTech() const { return isStartingTech; } bool Technology::getIsRare() const { return isRare; } bool Technology::getIsRepeatable() const { return isRepeatable; } bool Technology::getIsWeightZero() const { return isWeightZero; } const QList<WeightModifier>& Technology::getWeightModifyingTechs() const { return weightModifyingTechs; } int Technology::getTier() const { return tier; } TechArea Technology::getArea() const { return area; } Technology *Technology::createFromAst(const Parsing::AstNode *node, QObject *parent) { Technology *state = new Technology(parent); state->name = QString(node->myName); AstNode *areaNode = node->findChildWithName("area"); CHECK_PTR(areaNode); if (qstrcmp(areaNode->val.Str, "engineering") == 0) state->area = TechArea::Engineering; else if (qstrcmp(areaNode->val.Str, "society") == 0) state->area = TechArea::Society; else if (qstrcmp(areaNode->val.Str, "physics") == 0) state->area = TechArea::Physics; else { delete state; return nullptr; } AstNode *startTechNode = node->findChildWithName("start_tech"); state->isStartingTech = startTechNode ? startTechNode->val.Bool : false; AstNode *rareNode = node->findChildWithName("is_rare"); state->isRare = rareNode ? rareNode->val.Bool : false; state->isRepeatable = state->name.startsWith("tech_repeatable_"); if (!state->isRepeatable) { AstNode *tierNode = node->findChildWithName("tier"); CHECK_PTR(tierNode); state->tier = tierNode->val.Int; } else state->tier = -1; AstNode *prerequisitesNode = node->findChildWithName("prerequisites"); if (prerequisitesNode && prerequisitesNode->type == Parsing::NT_STRINGLIST) { ITERATE_CHILDREN(prerequisitesNode, aPrerequisite) { state->requirements.append(aPrerequisite->val.Str); } } AstNode *weightNode = node->findChildWithName("weight"); state->isWeightZero = !weightNode || (weightNode->type == Parsing::NT_INT && weightNode->val.Int == 0); AstNode *weightModifierNode = node->findChildWithName("weight_modifier"); if (weightModifierNode) { ITERATE_CHILDREN(weightModifierNode, modifier) { if (qstrcmp(modifier->myName, "modifier") == 0) { if (modifier->countChildren() != 2) continue; AstNode *factorNode = modifier->findChildWithName("factor"); AstNode *hasTechNode = modifier->findChildWithName("has_technology"); if (!factorNode || !hasTechNode) continue; if (hasTechNode->type != Parsing::NT_STRING) continue; switch (factorNode->type) { case Parsing::NT_INT: state->weightModifyingTechs.append({QString(hasTechNode->val.Str), (double) factorNode->val.Int}); break; case Parsing::NT_DOUBLE: state->weightModifyingTechs.append({QString(hasTechNode->val.Str), factorNode->val.Double}); break; default: continue; } } } } return state; } }
3,941
1,476
/*========================================================================= Program: MAF2 Module: mafDeviceButtonsPadMouse Authors: Marco Petrone Copyright (c) B3C All rights reserved. See Copyright.txt or http://www.scsitaly.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "mafDefines.h" //---------------------------------------------------------------------------- // NOTE: Every CPP file in the MAF must include "mafDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "mafDeviceButtonsPadMouse.h" #include "mafEventBase.h" #include "mafView.h" #include "mafSceneGraph.h" #include "mafRWIBase.h" #include "mafEventInteraction.h" #include "mmuIdFactory.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" //------------------------------------------------------------------------------ // Events //------------------------------------------------------------------------------ // MAF_ID_IMP(mafDeviceButtonsPadMouse::MOUSE_2D_MOVE) // MAF_ID_IMP(mafDeviceButtonsPadMouse::MOUSE_CHAR_EVENT) // MAF_ID_IMP(mafDeviceButtonsPadMouse::MOUSE_DCLICK) //------------------------------------------------------------------------------ mafCxxTypeMacro(mafDeviceButtonsPadMouse) //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ mafDeviceButtonsPadMouse::mafDeviceButtonsPadMouse() //------------------------------------------------------------------------------ { SetThreaded(0); m_LastPosition[0] = m_LastPosition[1] = 0; m_ButtonState[0] = m_ButtonState[1] = m_ButtonState[2] = 0; m_SelectedView = NULL; m_SelectedRWI = NULL; m_UpdateRwiInOnMoveFlag = false; m_CollaborateStatus = false; m_FromRemote = false; m_ButtonPressed = false; } //------------------------------------------------------------------------------ mafDeviceButtonsPadMouse::~mafDeviceButtonsPadMouse() //------------------------------------------------------------------------------ { } //------------------------------------------------------------------------------ void mafDeviceButtonsPadMouse::OnEvent(mafEventBase *event) //------------------------------------------------------------------------------ { assert(event); mafID id = event->GetId(); mafEventInteraction *e = mafEventInteraction::SafeDownCast(event); if (id == GetMouse2DMoveId()) { double pos[2]; e->Get2DPosition(pos); if (m_UpdateRwiInOnMoveFlag) { m_SelectedRWI = (mafRWIBase *)event->GetSender(); } SetLastPosition(pos[0],pos[1],e->GetModifiers()); } else if (id == GetButtonDownId() || id == GetMouseDClickId()) { // store the Selected RWI is needed for compounded view m_ButtonPressed = true; e->Get2DPosition(m_LastPosition); m_SelectedRWI = (mafRWIBase *)event->GetSender(); e->SetSender(this); InvokeEvent(e,MCH_INPUT); if (m_CollaborateStatus) { double disp[2]; e->Get2DPosition(disp); DisplayToNormalizedDisplay(disp); mafEventInteraction remoteEv; remoteEv.SetSender(this); remoteEv.SetId(id); remoteEv.SetButton(e->GetButton()); remoteEv.Set2DPosition(disp); remoteEv.SetModifiers(e->GetModifiers()); InvokeEvent(remoteEv,REMOTE_COMMAND_CHANNEL); } } else if (id == GetButtonUpId()) { m_ButtonPressed = false; e->Get2DPosition(m_LastPosition); e->SetSender(this); InvokeEvent(e,MCH_INPUT); if (m_CollaborateStatus) { double disp[2]; e->Get2DPosition(disp); DisplayToNormalizedDisplay(disp); mafEventInteraction remoteEv; remoteEv.SetSender(this); remoteEv.SetId(GetButtonUpId()); remoteEv.SetButton(e->GetButton()); remoteEv.Set2DPosition(disp); remoteEv.SetModifiers(e->GetModifiers()); InvokeEvent(remoteEv,REMOTE_COMMAND_CHANNEL); } } else if (id == VIEW_SELECT) { mafEvent *ev = mafEvent::SafeDownCast(event); if (ev) { m_SelectedView = ev->GetView(); } } else if (id == GetMouseCharEventId()) { mafEvent *ev = mafEvent::SafeDownCast(event); if (ev) { unsigned char key = (unsigned char)ev->GetArg(); mafEventInteraction ei(this,GetMouseCharEventId()); ei.SetKey(key); InvokeEvent(&ei,MCH_INPUT); } } } //------------------------------------------------------------------------------ void mafDeviceButtonsPadMouse::SetLastPosition(double x,double y,unsigned long modifiers) //------------------------------------------------------------------------------ { m_LastPosition[0] = x; m_LastPosition[1] = y; if (m_CollaborateStatus && m_SelectedRWI && !m_FromRemote && m_ButtonPressed) { double disp[2]; disp[0] = (double)x; disp[1] = (double)y; DisplayToNormalizedDisplay(disp); mafEventInteraction remoteEv; remoteEv.SetSender(this); remoteEv.SetId(GetMouse2DMoveId()); remoteEv.SetModifiers(modifiers); remoteEv.Set2DPosition(disp); InvokeEvent(remoteEv,REMOTE_COMMAND_CHANNEL); } m_FromRemote = false; // create a new event with last position mafEventInteraction e(this,GetMouse2DMoveId(),x,y); e.SetModifiers(modifiers); InvokeEvent(e,MCH_INPUT); } //------------------------------------------------------------------------------ void mafDeviceButtonsPadMouse::SendButtonEvent(mafEventInteraction *event) //------------------------------------------------------------------------------ { event->Set2DPosition(GetLastPosition()); Superclass::SendButtonEvent(event); } //------------------------------------------------------------------------------ vtkRenderer *mafDeviceButtonsPadMouse::GetRenderer() //------------------------------------------------------------------------------ { vtkRenderer *r = NULL; if (m_SelectedRWI) { r = m_SelectedRWI->FindPokedRenderer((int)m_LastPosition[0],(int)m_LastPosition[1]); } return r; } //------------------------------------------------------------------------------ mafView *mafDeviceButtonsPadMouse::GetView() //------------------------------------------------------------------------------ { return m_SelectedView; } //------------------------------------------------------------------------------ vtkRenderWindowInteractor *mafDeviceButtonsPadMouse::GetInteractor() //------------------------------------------------------------------------------ { if (m_SelectedRWI) return m_SelectedRWI->GetRenderWindow()->GetInteractor(); return (vtkRenderWindowInteractor *)NULL; } //------------------------------------------------------------------------------ mafRWIBase *mafDeviceButtonsPadMouse::GetRWI() //------------------------------------------------------------------------------ { return m_SelectedRWI; } //------------------------------------------------------------------------------ void mafDeviceButtonsPadMouse::DisplayToNormalizedDisplay(double display[2]) //------------------------------------------------------------------------------ { vtkRenderer *r = GetRenderer(); if (r == NULL) {return;} int *size; /* get physical window dimensions */ size = r->GetVTKWindow()->GetSize(); display[0] -= (size[0]*.5); display[1] -= (size[1]*.5); display[0] = display[0]/size[1]; display[1] = display[1]/size[1]; //r->DisplayToNormalizedDisplay(display[0],display[1]); } //------------------------------------------------------------------------------ void mafDeviceButtonsPadMouse::NormalizedDisplayToDisplay(double normalized[2]) //------------------------------------------------------------------------------ { vtkRenderer *r = GetRenderer(); if (r == NULL) {return;} int *size; /* get physical window dimensions */ size = r->GetVTKWindow()->GetSize(); normalized[0] = normalized[0]*size[1]; normalized[1] = normalized[1]*size[1]; normalized[0] += (size[0]*.5); normalized[1] += (size[1]*.5); // r->NormalizedDisplayToDisplay(normalized[0],normalized[1]); } //------------------------------------------------------------------------------ mafID mafDeviceButtonsPadMouse::GetMouse2DMoveId() //------------------------------------------------------------------------------ { static const mafID mouse2DMoveId = mmuIdFactory::GetNextId("MOUSE_2D_MOVE"); return mouse2DMoveId; } //------------------------------------------------------------------------------ mafID mafDeviceButtonsPadMouse::GetMouseCharEventId() //------------------------------------------------------------------------------ { static const mafID mouseCharEventId = mmuIdFactory::GetNextId("MOUSE_CHAR_EVENT"); return mouseCharEventId; } //------------------------------------------------------------------------------ mafID mafDeviceButtonsPadMouse::GetMouseDClickId() //------------------------------------------------------------------------------ { static const mafID mouseDClickId = mmuIdFactory::GetNextId("MOUSE_DCLICK"); return mouseDClickId; }
9,561
2,772
#include "BlockyVideoMemoryPool.h" #include <cstring> BlockyVideoMemoryPool::BlockyVideoMemoryPool(GLuint blockSize) :blockSize(blockSize) { realloc(8); } BlockyVideoMemoryPool::BlockyVideoMemoryPool(BlockyVideoMemoryPool &&rhs) { this->pbuffer.swap(rhs.pbuffer); this->usage.swap(rhs.usage); this->blockSize = rhs.blockSize; this->capacity = rhs.capacity; this->bufferSize = rhs.bufferSize; } BlockyVideoMemoryPool::~BlockyVideoMemoryPool() { } GLuint BlockyVideoMemoryPool::alloc() { int a = 2; size_t index = SIZE_MAX; while(a-- > 0) { size_t i = 0; for(auto used : usage) { //search unused block if(!used) { index = i; break; } ++i; } if(index == SIZE_MAX){ //failed realloc(this->capacity * 2); } else { //succeed usage[index] = true; break; } } return index * blockSize; } void BlockyVideoMemoryPool::free(GLuint offset) { if(offset % blockSize != 0) { throw std::runtime_error("Isn't packed"); } usage[offset / blockSize] = false; } void BlockyVideoMemoryPool::setOnRealloc(std::function<void(const VertexBuffer &)> callback) { onRealloc = callback; } void BlockyVideoMemoryPool::realloc(GLuint capacity) { std::unique_ptr<VertexBuffer> newBuffer(new VertexBuffer(GL_DYNAMIC_DRAW, capacity * blockSize)); if(pbuffer) { auto *buffer = std::malloc(bufferSize); pbuffer->map(GL_READ_ONLY, [&](void *data) { std::memcpy(buffer, data, bufferSize); }); newBuffer->map(GL_WRITE_ONLY, [&](void *data) { std::memcpy(data, buffer, bufferSize); }); std::free(buffer); } pbuffer.swap(newBuffer); this->capacity = capacity; this->bufferSize = pbuffer->size(); this->usage.resize(capacity, false); if(onRealloc) { onRealloc(getInnerBuffer()); } } const VertexBuffer &BlockyVideoMemoryPool::getInnerBuffer() const noexcept { return *pbuffer; }
2,096
697
/* $Id: CPUMAllRegs.cpp $ */ /** @file * CPUM - CPU Monitor(/Manager) - Getters and Setters. */ /* * Copyright (C) 2006-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ /******************************************************************************* * Header Files * *******************************************************************************/ #define LOG_GROUP LOG_GROUP_CPUM #include <VBox/vmm/cpum.h> #include <VBox/vmm/patm.h> #include <VBox/vmm/dbgf.h> #include <VBox/vmm/pdm.h> #include <VBox/vmm/pgm.h> #include <VBox/vmm/mm.h> #include <VBox/vmm/em.h> #if defined(VBOX_WITH_RAW_MODE) && !defined(IN_RING0) # include <VBox/vmm/selm.h> #endif #include "CPUMInternal.h" #include <VBox/vmm/vm.h> #include <VBox/err.h> #include <VBox/dis.h> #include <VBox/log.h> #include <VBox/vmm/hm.h> #include <VBox/vmm/tm.h> #include <iprt/assert.h> #include <iprt/asm.h> #include <iprt/asm-amd64-x86.h> #ifdef IN_RING3 #include <iprt/thread.h> #endif /** Disable stack frame pointer generation here. */ #if defined(_MSC_VER) && !defined(DEBUG) # pragma optimize("y", off) #endif AssertCompile2MemberOffsets(VM, cpum.s.HostFeatures, cpum.ro.HostFeatures); AssertCompile2MemberOffsets(VM, cpum.s.GuestFeatures, cpum.ro.GuestFeatures); /******************************************************************************* * Defined Constants And Macros * *******************************************************************************/ /** * Converts a CPUMCPU::Guest pointer into a VMCPU pointer. * * @returns Pointer to the Virtual CPU. * @param a_pGuestCtx Pointer to the guest context. */ #define CPUM_GUEST_CTX_TO_VMCPU(a_pGuestCtx) RT_FROM_MEMBER(a_pGuestCtx, VMCPU, cpum.s.Guest) /** * Lazily loads the hidden parts of a selector register when using raw-mode. */ #if defined(VBOX_WITH_RAW_MODE) && !defined(IN_RING0) # define CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(a_pVCpu, a_pSReg) \ do \ { \ if (!CPUMSELREG_ARE_HIDDEN_PARTS_VALID(a_pVCpu, a_pSReg)) \ cpumGuestLazyLoadHiddenSelectorReg(a_pVCpu, a_pSReg); \ } while (0) #else # define CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(a_pVCpu, a_pSReg) \ Assert(CPUMSELREG_ARE_HIDDEN_PARTS_VALID(a_pVCpu, a_pSReg)); #endif #ifdef VBOX_WITH_RAW_MODE_NOT_R0 /** * Does the lazy hidden selector register loading. * * @param pVCpu The current Virtual CPU. * @param pSReg The selector register to lazily load hidden parts of. */ static void cpumGuestLazyLoadHiddenSelectorReg(PVMCPU pVCpu, PCPUMSELREG pSReg) { Assert(!CPUMSELREG_ARE_HIDDEN_PARTS_VALID(pVCpu, pSReg)); Assert(!HMIsEnabled(pVCpu->CTX_SUFF(pVM))); Assert((uintptr_t)(pSReg - &pVCpu->cpum.s.Guest.es) < X86_SREG_COUNT); if (pVCpu->cpum.s.Guest.eflags.Bits.u1VM) { /* V8086 mode - Tightly controlled environment, no question about the limit or flags. */ pSReg->Attr.u = 0; pSReg->Attr.n.u4Type = pSReg == &pVCpu->cpum.s.Guest.cs ? X86_SEL_TYPE_ER_ACC : X86_SEL_TYPE_RW_ACC; pSReg->Attr.n.u1DescType = 1; /* code/data segment */ pSReg->Attr.n.u2Dpl = 3; pSReg->Attr.n.u1Present = 1; pSReg->u32Limit = 0x0000ffff; pSReg->u64Base = (uint32_t)pSReg->Sel << 4; pSReg->ValidSel = pSReg->Sel; pSReg->fFlags = CPUMSELREG_FLAGS_VALID; /** @todo Check what the accessed bit should be (VT-x and AMD-V). */ } else if (!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE)) { /* Real mode - leave the limit and flags alone here, at least for now. */ pSReg->u64Base = (uint32_t)pSReg->Sel << 4; pSReg->ValidSel = pSReg->Sel; pSReg->fFlags = CPUMSELREG_FLAGS_VALID; } else { /* Protected mode - get it from the selector descriptor tables. */ if (!(pSReg->Sel & X86_SEL_MASK_OFF_RPL)) { Assert(!CPUMIsGuestInLongMode(pVCpu)); pSReg->Sel = 0; pSReg->u64Base = 0; pSReg->u32Limit = 0; pSReg->Attr.u = 0; pSReg->ValidSel = 0; pSReg->fFlags = CPUMSELREG_FLAGS_VALID; /** @todo see todo in iemHlpLoadNullDataSelectorProt. */ } else SELMLoadHiddenSelectorReg(pVCpu, &pVCpu->cpum.s.Guest, pSReg); } } /** * Makes sure the hidden CS and SS selector registers are valid, loading them if * necessary. * * @param pVCpu The current virtual CPU. */ VMM_INT_DECL(void) CPUMGuestLazyLoadHiddenCsAndSs(PVMCPU pVCpu) { CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, &pVCpu->cpum.s.Guest.cs); CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, &pVCpu->cpum.s.Guest.ss); } /** * Loads a the hidden parts of a selector register. * * @param pVCpu The current virtual CPU. */ VMM_INT_DECL(void) CPUMGuestLazyLoadHiddenSelectorReg(PVMCPU pVCpu, PCPUMSELREG pSReg) { CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, pSReg); } #endif /* VBOX_WITH_RAW_MODE_NOT_R0 */ /** * Obsolete. * * We don't support nested hypervisor context interrupts or traps. Life is much * simpler when we don't. It's also slightly faster at times. * * @param pVM Handle to the virtual machine. */ VMMDECL(PCCPUMCTXCORE) CPUMGetHyperCtxCore(PVMCPU pVCpu) { return CPUMCTX2CORE(&pVCpu->cpum.s.Hyper); } /** * Gets the pointer to the hypervisor CPU context structure of a virtual CPU. * * @param pVCpu Pointer to the VMCPU. */ VMMDECL(PCPUMCTX) CPUMGetHyperCtxPtr(PVMCPU pVCpu) { return &pVCpu->cpum.s.Hyper; } VMMDECL(void) CPUMSetHyperGDTR(PVMCPU pVCpu, uint32_t addr, uint16_t limit) { pVCpu->cpum.s.Hyper.gdtr.cbGdt = limit; pVCpu->cpum.s.Hyper.gdtr.pGdt = addr; } VMMDECL(void) CPUMSetHyperIDTR(PVMCPU pVCpu, uint32_t addr, uint16_t limit) { pVCpu->cpum.s.Hyper.idtr.cbIdt = limit; pVCpu->cpum.s.Hyper.idtr.pIdt = addr; } VMMDECL(void) CPUMSetHyperCR3(PVMCPU pVCpu, uint32_t cr3) { pVCpu->cpum.s.Hyper.cr3 = cr3; #ifdef IN_RC /* Update the current CR3. */ ASMSetCR3(cr3); #endif } VMMDECL(uint32_t) CPUMGetHyperCR3(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.cr3; } VMMDECL(void) CPUMSetHyperCS(PVMCPU pVCpu, RTSEL SelCS) { pVCpu->cpum.s.Hyper.cs.Sel = SelCS; } VMMDECL(void) CPUMSetHyperDS(PVMCPU pVCpu, RTSEL SelDS) { pVCpu->cpum.s.Hyper.ds.Sel = SelDS; } VMMDECL(void) CPUMSetHyperES(PVMCPU pVCpu, RTSEL SelES) { pVCpu->cpum.s.Hyper.es.Sel = SelES; } VMMDECL(void) CPUMSetHyperFS(PVMCPU pVCpu, RTSEL SelFS) { pVCpu->cpum.s.Hyper.fs.Sel = SelFS; } VMMDECL(void) CPUMSetHyperGS(PVMCPU pVCpu, RTSEL SelGS) { pVCpu->cpum.s.Hyper.gs.Sel = SelGS; } VMMDECL(void) CPUMSetHyperSS(PVMCPU pVCpu, RTSEL SelSS) { pVCpu->cpum.s.Hyper.ss.Sel = SelSS; } VMMDECL(void) CPUMSetHyperESP(PVMCPU pVCpu, uint32_t u32ESP) { pVCpu->cpum.s.Hyper.esp = u32ESP; } VMMDECL(void) CPUMSetHyperEDX(PVMCPU pVCpu, uint32_t u32ESP) { pVCpu->cpum.s.Hyper.esp = u32ESP; } VMMDECL(int) CPUMSetHyperEFlags(PVMCPU pVCpu, uint32_t Efl) { pVCpu->cpum.s.Hyper.eflags.u32 = Efl; return VINF_SUCCESS; } VMMDECL(void) CPUMSetHyperEIP(PVMCPU pVCpu, uint32_t u32EIP) { pVCpu->cpum.s.Hyper.eip = u32EIP; } /** * Used by VMMR3RawRunGC to reinitialize the general raw-mode context registers, * EFLAGS and EIP prior to resuming guest execution. * * All general register not given as a parameter will be set to 0. The EFLAGS * register will be set to sane values for C/C++ code execution with interrupts * disabled and IOPL 0. * * @param pVCpu The current virtual CPU. * @param u32EIP The EIP value. * @param u32ESP The ESP value. * @param u32EAX The EAX value. * @param u32EDX The EDX value. */ VMM_INT_DECL(void) CPUMSetHyperState(PVMCPU pVCpu, uint32_t u32EIP, uint32_t u32ESP, uint32_t u32EAX, uint32_t u32EDX) { pVCpu->cpum.s.Hyper.eip = u32EIP; pVCpu->cpum.s.Hyper.esp = u32ESP; pVCpu->cpum.s.Hyper.eax = u32EAX; pVCpu->cpum.s.Hyper.edx = u32EDX; pVCpu->cpum.s.Hyper.ecx = 0; pVCpu->cpum.s.Hyper.ebx = 0; pVCpu->cpum.s.Hyper.ebp = 0; pVCpu->cpum.s.Hyper.esi = 0; pVCpu->cpum.s.Hyper.edi = 0; pVCpu->cpum.s.Hyper.eflags.u = X86_EFL_1; } VMMDECL(void) CPUMSetHyperTR(PVMCPU pVCpu, RTSEL SelTR) { pVCpu->cpum.s.Hyper.tr.Sel = SelTR; } VMMDECL(void) CPUMSetHyperLDTR(PVMCPU pVCpu, RTSEL SelLDTR) { pVCpu->cpum.s.Hyper.ldtr.Sel = SelLDTR; } /** @MAYBE_LOAD_DRx * Macro for updating DRx values in raw-mode and ring-0 contexts. */ #ifdef IN_RING0 # if HC_ARCH_BITS == 32 && defined(VBOX_WITH_64_BITS_GUESTS) # ifndef VBOX_WITH_HYBRID_32BIT_KERNEL # define MAYBE_LOAD_DRx(a_pVCpu, a_fnLoad, a_uValue) \ do { \ if (!CPUMIsGuestInLongModeEx(&(a_pVCpu)->cpum.s.Guest)) \ a_fnLoad(a_uValue); \ else \ (a_pVCpu)->cpum.s.fUseFlags |= CPUM_SYNC_DEBUG_REGS_HYPER; \ } while (0) # else # define MAYBE_LOAD_DRx(a_pVCpu, a_fnLoad, a_uValue) \ do { \ /** @todo we're not loading the correct guest value here! */ \ a_fnLoad(a_uValue); \ } while (0) # endif # else # define MAYBE_LOAD_DRx(a_pVCpu, a_fnLoad, a_uValue) \ do { \ a_fnLoad(a_uValue); \ } while (0) # endif #elif defined(IN_RC) # define MAYBE_LOAD_DRx(a_pVCpu, a_fnLoad, a_uValue) \ do { \ if ((a_pVCpu)->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_HYPER) \ { a_fnLoad(a_uValue); } \ } while (0) #else # define MAYBE_LOAD_DRx(a_pVCpu, a_fnLoad, a_uValue) do { } while (0) #endif VMMDECL(void) CPUMSetHyperDR0(PVMCPU pVCpu, RTGCUINTREG uDr0) { pVCpu->cpum.s.Hyper.dr[0] = uDr0; MAYBE_LOAD_DRx(pVCpu, ASMSetDR0, uDr0); } VMMDECL(void) CPUMSetHyperDR1(PVMCPU pVCpu, RTGCUINTREG uDr1) { pVCpu->cpum.s.Hyper.dr[1] = uDr1; MAYBE_LOAD_DRx(pVCpu, ASMSetDR1, uDr1); } VMMDECL(void) CPUMSetHyperDR2(PVMCPU pVCpu, RTGCUINTREG uDr2) { pVCpu->cpum.s.Hyper.dr[2] = uDr2; MAYBE_LOAD_DRx(pVCpu, ASMSetDR2, uDr2); } VMMDECL(void) CPUMSetHyperDR3(PVMCPU pVCpu, RTGCUINTREG uDr3) { pVCpu->cpum.s.Hyper.dr[3] = uDr3; MAYBE_LOAD_DRx(pVCpu, ASMSetDR3, uDr3); } VMMDECL(void) CPUMSetHyperDR6(PVMCPU pVCpu, RTGCUINTREG uDr6) { pVCpu->cpum.s.Hyper.dr[6] = uDr6; } VMMDECL(void) CPUMSetHyperDR7(PVMCPU pVCpu, RTGCUINTREG uDr7) { pVCpu->cpum.s.Hyper.dr[7] = uDr7; #ifdef IN_RC MAYBE_LOAD_DRx(pVCpu, ASMSetDR7, uDr7); #endif } VMMDECL(RTSEL) CPUMGetHyperCS(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.cs.Sel; } VMMDECL(RTSEL) CPUMGetHyperDS(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ds.Sel; } VMMDECL(RTSEL) CPUMGetHyperES(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.es.Sel; } VMMDECL(RTSEL) CPUMGetHyperFS(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.fs.Sel; } VMMDECL(RTSEL) CPUMGetHyperGS(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.gs.Sel; } VMMDECL(RTSEL) CPUMGetHyperSS(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ss.Sel; } VMMDECL(uint32_t) CPUMGetHyperEAX(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.eax; } VMMDECL(uint32_t) CPUMGetHyperEBX(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ebx; } VMMDECL(uint32_t) CPUMGetHyperECX(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ecx; } VMMDECL(uint32_t) CPUMGetHyperEDX(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.edx; } VMMDECL(uint32_t) CPUMGetHyperESI(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.esi; } VMMDECL(uint32_t) CPUMGetHyperEDI(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.edi; } VMMDECL(uint32_t) CPUMGetHyperEBP(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ebp; } VMMDECL(uint32_t) CPUMGetHyperESP(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.esp; } VMMDECL(uint32_t) CPUMGetHyperEFlags(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.eflags.u32; } VMMDECL(uint32_t) CPUMGetHyperEIP(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.eip; } VMMDECL(uint64_t) CPUMGetHyperRIP(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.rip; } VMMDECL(uint32_t) CPUMGetHyperIDTR(PVMCPU pVCpu, uint16_t *pcbLimit) { if (pcbLimit) *pcbLimit = pVCpu->cpum.s.Hyper.idtr.cbIdt; return pVCpu->cpum.s.Hyper.idtr.pIdt; } VMMDECL(uint32_t) CPUMGetHyperGDTR(PVMCPU pVCpu, uint16_t *pcbLimit) { if (pcbLimit) *pcbLimit = pVCpu->cpum.s.Hyper.gdtr.cbGdt; return pVCpu->cpum.s.Hyper.gdtr.pGdt; } VMMDECL(RTSEL) CPUMGetHyperLDTR(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.ldtr.Sel; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR0(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[0]; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR1(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[1]; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR2(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[2]; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR3(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[3]; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR6(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[6]; } VMMDECL(RTGCUINTREG) CPUMGetHyperDR7(PVMCPU pVCpu) { return pVCpu->cpum.s.Hyper.dr[7]; } /** * Gets the pointer to the internal CPUMCTXCORE structure. * This is only for reading in order to save a few calls. * * @param pVCpu Handle to the virtual cpu. */ VMMDECL(PCCPUMCTXCORE) CPUMGetGuestCtxCore(PVMCPU pVCpu) { return CPUMCTX2CORE(&pVCpu->cpum.s.Guest); } /** * Queries the pointer to the internal CPUMCTX structure. * * @returns The CPUMCTX pointer. * @param pVCpu Handle to the virtual cpu. */ VMMDECL(PCPUMCTX) CPUMQueryGuestCtxPtr(PVMCPU pVCpu) { return &pVCpu->cpum.s.Guest; } VMMDECL(int) CPUMSetGuestGDTR(PVMCPU pVCpu, uint64_t GCPtrBase, uint16_t cbLimit) { #ifdef VBOX_WITH_IEM # ifdef VBOX_WITH_RAW_MODE_NOT_R0 if (!HMIsEnabled(pVCpu->CTX_SUFF(pVM))) VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_GDT); # endif #endif pVCpu->cpum.s.Guest.gdtr.cbGdt = cbLimit; pVCpu->cpum.s.Guest.gdtr.pGdt = GCPtrBase; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_GDTR; return VINF_SUCCESS; /* formality, consider it void. */ } VMMDECL(int) CPUMSetGuestIDTR(PVMCPU pVCpu, uint64_t GCPtrBase, uint16_t cbLimit) { #ifdef VBOX_WITH_IEM # ifdef VBOX_WITH_RAW_MODE_NOT_R0 if (!HMIsEnabled(pVCpu->CTX_SUFF(pVM))) VMCPU_FF_SET(pVCpu, VMCPU_FF_TRPM_SYNC_IDT); # endif #endif pVCpu->cpum.s.Guest.idtr.cbIdt = cbLimit; pVCpu->cpum.s.Guest.idtr.pIdt = GCPtrBase; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_IDTR; return VINF_SUCCESS; /* formality, consider it void. */ } VMMDECL(int) CPUMSetGuestTR(PVMCPU pVCpu, uint16_t tr) { #ifdef VBOX_WITH_IEM # ifdef VBOX_WITH_RAW_MODE_NOT_R0 if (!HMIsEnabled(pVCpu->CTX_SUFF(pVM))) VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_TSS); # endif #endif pVCpu->cpum.s.Guest.tr.Sel = tr; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_TR; return VINF_SUCCESS; /* formality, consider it void. */ } VMMDECL(int) CPUMSetGuestLDTR(PVMCPU pVCpu, uint16_t ldtr) { #ifdef VBOX_WITH_IEM # ifdef VBOX_WITH_RAW_MODE_NOT_R0 if ( ( ldtr != 0 || pVCpu->cpum.s.Guest.ldtr.Sel != 0) && !HMIsEnabled(pVCpu->CTX_SUFF(pVM))) VMCPU_FF_SET(pVCpu, VMCPU_FF_SELM_SYNC_LDT); # endif #endif pVCpu->cpum.s.Guest.ldtr.Sel = ldtr; /* The caller will set more hidden bits if it has them. */ pVCpu->cpum.s.Guest.ldtr.ValidSel = 0; pVCpu->cpum.s.Guest.ldtr.fFlags = 0; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_LDTR; return VINF_SUCCESS; /* formality, consider it void. */ } /** * Set the guest CR0. * * When called in GC, the hyper CR0 may be updated if that is * required. The caller only has to take special action if AM, * WP, PG or PE changes. * * @returns VINF_SUCCESS (consider it void). * @param pVCpu Handle to the virtual cpu. * @param cr0 The new CR0 value. */ VMMDECL(int) CPUMSetGuestCR0(PVMCPU pVCpu, uint64_t cr0) { #ifdef IN_RC /* * Check if we need to change hypervisor CR0 because * of math stuff. */ if ( (cr0 & (X86_CR0_TS | X86_CR0_EM | X86_CR0_MP)) != (pVCpu->cpum.s.Guest.cr0 & (X86_CR0_TS | X86_CR0_EM | X86_CR0_MP))) { if (!(pVCpu->cpum.s.fUseFlags & CPUM_USED_FPU)) { /* * We haven't saved the host FPU state yet, so TS and MT are both set * and EM should be reflecting the guest EM (it always does this). */ if ((cr0 & X86_CR0_EM) != (pVCpu->cpum.s.Guest.cr0 & X86_CR0_EM)) { uint32_t HyperCR0 = ASMGetCR0(); AssertMsg((HyperCR0 & (X86_CR0_TS | X86_CR0_MP)) == (X86_CR0_TS | X86_CR0_MP), ("%#x\n", HyperCR0)); AssertMsg((HyperCR0 & X86_CR0_EM) == (pVCpu->cpum.s.Guest.cr0 & X86_CR0_EM), ("%#x\n", HyperCR0)); HyperCR0 &= ~X86_CR0_EM; HyperCR0 |= cr0 & X86_CR0_EM; Log(("CPUM: New HyperCR0=%#x\n", HyperCR0)); ASMSetCR0(HyperCR0); } # ifdef VBOX_STRICT else { uint32_t HyperCR0 = ASMGetCR0(); AssertMsg((HyperCR0 & (X86_CR0_TS | X86_CR0_MP)) == (X86_CR0_TS | X86_CR0_MP), ("%#x\n", HyperCR0)); AssertMsg((HyperCR0 & X86_CR0_EM) == (pVCpu->cpum.s.Guest.cr0 & X86_CR0_EM), ("%#x\n", HyperCR0)); } # endif } else { /* * Already saved the state, so we're just mirroring * the guest flags. */ uint32_t HyperCR0 = ASMGetCR0(); AssertMsg( (HyperCR0 & (X86_CR0_TS | X86_CR0_EM | X86_CR0_MP)) == (pVCpu->cpum.s.Guest.cr0 & (X86_CR0_TS | X86_CR0_EM | X86_CR0_MP)), ("%#x %#x\n", HyperCR0, pVCpu->cpum.s.Guest.cr0)); HyperCR0 &= ~(X86_CR0_TS | X86_CR0_EM | X86_CR0_MP); HyperCR0 |= cr0 & (X86_CR0_TS | X86_CR0_EM | X86_CR0_MP); Log(("CPUM: New HyperCR0=%#x\n", HyperCR0)); ASMSetCR0(HyperCR0); } } #endif /* IN_RC */ /* * Check for changes causing TLB flushes (for REM). * The caller is responsible for calling PGM when appropriate. */ if ( (cr0 & (X86_CR0_PG | X86_CR0_WP | X86_CR0_PE)) != (pVCpu->cpum.s.Guest.cr0 & (X86_CR0_PG | X86_CR0_WP | X86_CR0_PE))) pVCpu->cpum.s.fChanged |= CPUM_CHANGED_GLOBAL_TLB_FLUSH; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_CR0; /* * Let PGM know if the WP goes from 0 to 1 (netware WP0+RO+US hack) */ if (((cr0 ^ pVCpu->cpum.s.Guest.cr0) & X86_CR0_WP) && (cr0 & X86_CR0_WP)) PGMCr0WpEnabled(pVCpu); pVCpu->cpum.s.Guest.cr0 = cr0 | X86_CR0_ET; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestCR2(PVMCPU pVCpu, uint64_t cr2) { pVCpu->cpum.s.Guest.cr2 = cr2; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestCR3(PVMCPU pVCpu, uint64_t cr3) { pVCpu->cpum.s.Guest.cr3 = cr3; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_CR3; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestCR4(PVMCPU pVCpu, uint64_t cr4) { /* * The CR4.OSXSAVE bit is reflected in CPUID(1).ECX[27]. */ if ( (cr4 & X86_CR4_OSXSAVE) != (pVCpu->cpum.s.Guest.cr4 & X86_CR4_OSXSAVE) ) { PVM pVM = pVCpu->CTX_SUFF(pVM); if (cr4 & X86_CR4_OSXSAVE) CPUMSetGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_OSXSAVE); else CPUMClearGuestCpuIdFeature(pVM, CPUMCPUIDFEATURE_OSXSAVE); } if ( (cr4 & (X86_CR4_PGE | X86_CR4_PAE | X86_CR4_PSE)) != (pVCpu->cpum.s.Guest.cr4 & (X86_CR4_PGE | X86_CR4_PAE | X86_CR4_PSE))) pVCpu->cpum.s.fChanged |= CPUM_CHANGED_GLOBAL_TLB_FLUSH; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_CR4; pVCpu->cpum.s.Guest.cr4 = cr4; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEFlags(PVMCPU pVCpu, uint32_t eflags) { pVCpu->cpum.s.Guest.eflags.u32 = eflags; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEIP(PVMCPU pVCpu, uint32_t eip) { pVCpu->cpum.s.Guest.eip = eip; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEAX(PVMCPU pVCpu, uint32_t eax) { pVCpu->cpum.s.Guest.eax = eax; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEBX(PVMCPU pVCpu, uint32_t ebx) { pVCpu->cpum.s.Guest.ebx = ebx; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestECX(PVMCPU pVCpu, uint32_t ecx) { pVCpu->cpum.s.Guest.ecx = ecx; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEDX(PVMCPU pVCpu, uint32_t edx) { pVCpu->cpum.s.Guest.edx = edx; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestESP(PVMCPU pVCpu, uint32_t esp) { pVCpu->cpum.s.Guest.esp = esp; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEBP(PVMCPU pVCpu, uint32_t ebp) { pVCpu->cpum.s.Guest.ebp = ebp; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestESI(PVMCPU pVCpu, uint32_t esi) { pVCpu->cpum.s.Guest.esi = esi; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestEDI(PVMCPU pVCpu, uint32_t edi) { pVCpu->cpum.s.Guest.edi = edi; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestSS(PVMCPU pVCpu, uint16_t ss) { pVCpu->cpum.s.Guest.ss.Sel = ss; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestCS(PVMCPU pVCpu, uint16_t cs) { pVCpu->cpum.s.Guest.cs.Sel = cs; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestDS(PVMCPU pVCpu, uint16_t ds) { pVCpu->cpum.s.Guest.ds.Sel = ds; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestES(PVMCPU pVCpu, uint16_t es) { pVCpu->cpum.s.Guest.es.Sel = es; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestFS(PVMCPU pVCpu, uint16_t fs) { pVCpu->cpum.s.Guest.fs.Sel = fs; return VINF_SUCCESS; } VMMDECL(int) CPUMSetGuestGS(PVMCPU pVCpu, uint16_t gs) { pVCpu->cpum.s.Guest.gs.Sel = gs; return VINF_SUCCESS; } VMMDECL(void) CPUMSetGuestEFER(PVMCPU pVCpu, uint64_t val) { pVCpu->cpum.s.Guest.msrEFER = val; } VMMDECL(RTGCPTR) CPUMGetGuestIDTR(PVMCPU pVCpu, uint16_t *pcbLimit) { if (pcbLimit) *pcbLimit = pVCpu->cpum.s.Guest.idtr.cbIdt; return pVCpu->cpum.s.Guest.idtr.pIdt; } VMMDECL(RTSEL) CPUMGetGuestTR(PVMCPU pVCpu, PCPUMSELREGHID pHidden) { if (pHidden) *pHidden = pVCpu->cpum.s.Guest.tr; return pVCpu->cpum.s.Guest.tr.Sel; } VMMDECL(RTSEL) CPUMGetGuestCS(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.cs.Sel; } VMMDECL(RTSEL) CPUMGetGuestDS(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ds.Sel; } VMMDECL(RTSEL) CPUMGetGuestES(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.es.Sel; } VMMDECL(RTSEL) CPUMGetGuestFS(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.fs.Sel; } VMMDECL(RTSEL) CPUMGetGuestGS(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.gs.Sel; } VMMDECL(RTSEL) CPUMGetGuestSS(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ss.Sel; } VMMDECL(RTSEL) CPUMGetGuestLDTR(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ldtr.Sel; } VMMDECL(RTSEL) CPUMGetGuestLdtrEx(PVMCPU pVCpu, uint64_t *pGCPtrBase, uint32_t *pcbLimit) { *pGCPtrBase = pVCpu->cpum.s.Guest.ldtr.u64Base; *pcbLimit = pVCpu->cpum.s.Guest.ldtr.u32Limit; return pVCpu->cpum.s.Guest.ldtr.Sel; } VMMDECL(uint64_t) CPUMGetGuestCR0(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.cr0; } VMMDECL(uint64_t) CPUMGetGuestCR2(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.cr2; } VMMDECL(uint64_t) CPUMGetGuestCR3(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.cr3; } VMMDECL(uint64_t) CPUMGetGuestCR4(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.cr4; } VMMDECL(uint64_t) CPUMGetGuestCR8(PVMCPU pVCpu) { uint64_t u64; int rc = CPUMGetGuestCRx(pVCpu, DISCREG_CR8, &u64); if (RT_FAILURE(rc)) u64 = 0; return u64; } VMMDECL(void) CPUMGetGuestGDTR(PVMCPU pVCpu, PVBOXGDTR pGDTR) { *pGDTR = pVCpu->cpum.s.Guest.gdtr; } VMMDECL(uint32_t) CPUMGetGuestEIP(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.eip; } VMMDECL(uint64_t) CPUMGetGuestRIP(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.rip; } VMMDECL(uint32_t) CPUMGetGuestEAX(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.eax; } VMMDECL(uint32_t) CPUMGetGuestEBX(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ebx; } VMMDECL(uint32_t) CPUMGetGuestECX(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ecx; } VMMDECL(uint32_t) CPUMGetGuestEDX(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.edx; } VMMDECL(uint32_t) CPUMGetGuestESI(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.esi; } VMMDECL(uint32_t) CPUMGetGuestEDI(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.edi; } VMMDECL(uint32_t) CPUMGetGuestESP(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.esp; } VMMDECL(uint32_t) CPUMGetGuestEBP(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.ebp; } VMMDECL(uint32_t) CPUMGetGuestEFlags(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.eflags.u32; } VMMDECL(int) CPUMGetGuestCRx(PVMCPU pVCpu, unsigned iReg, uint64_t *pValue) { switch (iReg) { case DISCREG_CR0: *pValue = pVCpu->cpum.s.Guest.cr0; break; case DISCREG_CR2: *pValue = pVCpu->cpum.s.Guest.cr2; break; case DISCREG_CR3: *pValue = pVCpu->cpum.s.Guest.cr3; break; case DISCREG_CR4: *pValue = pVCpu->cpum.s.Guest.cr4; break; case DISCREG_CR8: { uint8_t u8Tpr; int rc = PDMApicGetTPR(pVCpu, &u8Tpr, NULL /* pfPending */, NULL /* pu8PendingIrq */); if (RT_FAILURE(rc)) { AssertMsg(rc == VERR_PDM_NO_APIC_INSTANCE, ("%Rrc\n", rc)); *pValue = 0; return rc; } *pValue = u8Tpr >> 4; /* bits 7-4 contain the task priority that go in cr8, bits 3-0*/ break; } default: return VERR_INVALID_PARAMETER; } return VINF_SUCCESS; } VMMDECL(uint64_t) CPUMGetGuestDR0(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[0]; } VMMDECL(uint64_t) CPUMGetGuestDR1(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[1]; } VMMDECL(uint64_t) CPUMGetGuestDR2(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[2]; } VMMDECL(uint64_t) CPUMGetGuestDR3(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[3]; } VMMDECL(uint64_t) CPUMGetGuestDR6(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[6]; } VMMDECL(uint64_t) CPUMGetGuestDR7(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.dr[7]; } VMMDECL(int) CPUMGetGuestDRx(PVMCPU pVCpu, uint32_t iReg, uint64_t *pValue) { AssertReturn(iReg <= DISDREG_DR7, VERR_INVALID_PARAMETER); /* DR4 is an alias for DR6, and DR5 is an alias for DR7. */ if (iReg == 4 || iReg == 5) iReg += 2; *pValue = pVCpu->cpum.s.Guest.dr[iReg]; return VINF_SUCCESS; } VMMDECL(uint64_t) CPUMGetGuestEFER(PVMCPU pVCpu) { return pVCpu->cpum.s.Guest.msrEFER; } /** * Looks up a CPUID leaf in the CPUID leaf array, no subleaf. * * @returns Pointer to the leaf if found, NULL if not. * * @param pVM Pointer to the cross context VM structure. * @param uLeaf The leaf to get. */ PCPUMCPUIDLEAF cpumCpuIdGetLeaf(PVM pVM, uint32_t uLeaf) { unsigned iEnd = pVM->cpum.s.GuestInfo.cCpuIdLeaves; if (iEnd) { unsigned iStart = 0; PCPUMCPUIDLEAF paLeaves = pVM->cpum.s.GuestInfo.CTX_SUFF(paCpuIdLeaves); for (;;) { unsigned i = iStart + (iEnd - iStart) / 2U; if (uLeaf < paLeaves[i].uLeaf) { if (i <= iStart) return NULL; iEnd = i; } else if (uLeaf > paLeaves[i].uLeaf) { i += 1; if (i >= iEnd) return NULL; iStart = i; } else { if (RT_LIKELY(paLeaves[i].fSubLeafMask == 0 && paLeaves[i].uSubLeaf == 0)) return &paLeaves[i]; /* This shouldn't normally happen. But in case the it does due to user configuration overrids or something, just return the first sub-leaf. */ AssertMsgFailed(("uLeaf=%#x fSubLeafMask=%#x uSubLeaf=%#x\n", uLeaf, paLeaves[i].fSubLeafMask, paLeaves[i].uSubLeaf)); while ( paLeaves[i].uSubLeaf != 0 && i > 0 && uLeaf == paLeaves[i - 1].uLeaf) i--; return &paLeaves[i]; } } } return NULL; } /** * Looks up a CPUID leaf in the CPUID leaf array. * * @returns Pointer to the leaf if found, NULL if not. * * @param pVM Pointer to the cross context VM structure. * @param uLeaf The leaf to get. * @param uSubLeaf The subleaf, if applicable. Just pass 0 if it * isn't. * @param pfExactSubLeafHit Whether we've got an exact subleaf hit or not. */ PCPUMCPUIDLEAF cpumCpuIdGetLeafEx(PVM pVM, uint32_t uLeaf, uint32_t uSubLeaf, bool *pfExactSubLeafHit) { unsigned iEnd = pVM->cpum.s.GuestInfo.cCpuIdLeaves; if (iEnd) { unsigned iStart = 0; PCPUMCPUIDLEAF paLeaves = pVM->cpum.s.GuestInfo.CTX_SUFF(paCpuIdLeaves); for (;;) { unsigned i = iStart + (iEnd - iStart) / 2U; if (uLeaf < paLeaves[i].uLeaf) { if (i <= iStart) return NULL; iEnd = i; } else if (uLeaf > paLeaves[i].uLeaf) { i += 1; if (i >= iEnd) return NULL; iStart = i; } else { uSubLeaf &= paLeaves[i].fSubLeafMask; if (uSubLeaf == paLeaves[i].uSubLeaf) *pfExactSubLeafHit = true; else { /* Find the right subleaf. We return the last one before uSubLeaf if we don't find an exact match. */ if (uSubLeaf < paLeaves[i].uSubLeaf) while ( i > 0 && uLeaf == paLeaves[i - 1].uLeaf && uSubLeaf <= paLeaves[i - 1].uSubLeaf) i--; else while ( i + 1 < pVM->cpum.s.GuestInfo.cCpuIdLeaves && uLeaf == paLeaves[i + 1].uLeaf && uSubLeaf >= paLeaves[i + 1].uSubLeaf) i++; *pfExactSubLeafHit = uSubLeaf == paLeaves[i].uSubLeaf; } return &paLeaves[i]; } } } *pfExactSubLeafHit = false; return NULL; } /** * Gets a CPUID leaf. * * @param pVCpu Pointer to the VMCPU. * @param uLeaf The CPUID leaf to get. * @param uSubLeaf The CPUID sub-leaf to get, if applicable. * @param pEax Where to store the EAX value. * @param pEbx Where to store the EBX value. * @param pEcx Where to store the ECX value. * @param pEdx Where to store the EDX value. */ VMMDECL(void) CPUMGetGuestCpuId(PVMCPU pVCpu, uint32_t uLeaf, uint32_t uSubLeaf, uint32_t *pEax, uint32_t *pEbx, uint32_t *pEcx, uint32_t *pEdx) { bool fExactSubLeafHit; PVM pVM = pVCpu->CTX_SUFF(pVM); PCCPUMCPUIDLEAF pLeaf = cpumCpuIdGetLeafEx(pVM, uLeaf, uSubLeaf, &fExactSubLeafHit); if (pLeaf) { AssertMsg(pLeaf->uLeaf == uLeaf, ("%#x\n", pLeaf->uLeaf, uLeaf)); if (fExactSubLeafHit) { *pEax = pLeaf->uEax; *pEbx = pLeaf->uEbx; *pEcx = pLeaf->uEcx; *pEdx = pLeaf->uEdx; /* * Deal with CPU specific information (currently only APIC ID). */ if (pLeaf->fFlags & (CPUMCPUIDLEAF_F_CONTAINS_APIC_ID | CPUMCPUIDLEAF_F_CONTAINS_OSXSAVE)) { if (uLeaf == 1) { /* EBX: Bits 31-24: Initial APIC ID. */ Assert(pVCpu->idCpu <= 255); AssertMsg((pLeaf->uEbx >> 24) == 0, ("%#x\n", pLeaf->uEbx)); /* raw-mode assumption */ *pEbx = (pLeaf->uEbx & UINT32_C(0x00ffffff)) | (pVCpu->idCpu << 24); /* ECX: Bit 27: CR4.OSXSAVE mirror. */ *pEcx = (pLeaf->uEcx & ~X86_CPUID_FEATURE_ECX_OSXSAVE) | (pVCpu->cpum.s.Guest.cr4 & X86_CR4_OSXSAVE ? X86_CPUID_FEATURE_ECX_OSXSAVE : 0); } else if (uLeaf == 0xb) { /* EDX: Initial extended APIC ID. */ AssertMsg(pLeaf->uEdx == 0, ("%#x\n", pLeaf->uEdx)); /* raw-mode assumption */ *pEdx = pVCpu->idCpu; } else if (uLeaf == UINT32_C(0x8000001e)) { /* EAX: Initial extended APIC ID. */ AssertMsg(pLeaf->uEax == 0, ("%#x\n", pLeaf->uEax)); /* raw-mode assumption */ *pEax = pVCpu->idCpu; } else AssertMsgFailed(("uLeaf=%#x\n", uLeaf)); } } /* * Out of range sub-leaves aren't quite as easy and pretty as we emulate * them here, but we do the best we can here... */ else { *pEax = *pEbx = *pEcx = *pEdx = 0; if (pLeaf->fFlags & CPUMCPUIDLEAF_F_INTEL_TOPOLOGY_SUBLEAVES) { *pEcx = uSubLeaf & 0xff; *pEdx = pVCpu->idCpu; } } } else { /* * Different CPUs have different ways of dealing with unknown CPUID leaves. */ switch (pVM->cpum.s.GuestInfo.enmUnknownCpuIdMethod) { default: AssertFailed(); case CPUMUNKNOWNCPUID_DEFAULTS: case CPUMUNKNOWNCPUID_LAST_STD_LEAF: /* ASSUME this is executed */ case CPUMUNKNOWNCPUID_LAST_STD_LEAF_WITH_ECX: /** @todo Implement CPUMUNKNOWNCPUID_LAST_STD_LEAF_WITH_ECX */ *pEax = pVM->cpum.s.GuestInfo.DefCpuId.uEax; *pEbx = pVM->cpum.s.GuestInfo.DefCpuId.uEbx; *pEcx = pVM->cpum.s.GuestInfo.DefCpuId.uEcx; *pEdx = pVM->cpum.s.GuestInfo.DefCpuId.uEdx; break; case CPUMUNKNOWNCPUID_PASSTHRU: *pEax = uLeaf; *pEbx = 0; *pEcx = uSubLeaf; *pEdx = 0; break; } } Log2(("CPUMGetGuestCpuId: uLeaf=%#010x/%#010x %RX32 %RX32 %RX32 %RX32\n", uLeaf, uSubLeaf, *pEax, *pEbx, *pEcx, *pEdx)); } /** * Sets a CPUID feature bit. * * @param pVM Pointer to the VM. * @param enmFeature The feature to set. */ VMMDECL(void) CPUMSetGuestCpuIdFeature(PVM pVM, CPUMCPUIDFEATURE enmFeature) { PCPUMCPUIDLEAF pLeaf; switch (enmFeature) { /* * Set the APIC bit in both feature masks. */ case CPUMCPUIDFEATURE_APIC: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx |= X86_CPUID_FEATURE_EDX_APIC; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_AMD_FEATURE_EDX_APIC; pVM->cpum.s.GuestFeatures.fApic = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled APIC\n")); break; /* * Set the x2APIC bit in the standard feature mask. */ case CPUMCPUIDFEATURE_X2APIC: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx |= X86_CPUID_FEATURE_ECX_X2APIC; pVM->cpum.s.GuestFeatures.fX2Apic = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled x2APIC\n")); break; /* * Set the sysenter/sysexit bit in the standard feature mask. * Assumes the caller knows what it's doing! (host must support these) */ case CPUMCPUIDFEATURE_SEP: if (!pVM->cpum.s.HostFeatures.fSysEnter) { AssertMsgFailed(("ERROR: Can't turn on SEP when the host doesn't support it!!\n")); return; } pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx |= X86_CPUID_FEATURE_EDX_SEP; pVM->cpum.s.GuestFeatures.fSysEnter = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled SYSENTER/EXIT\n")); break; /* * Set the syscall/sysret bit in the extended feature mask. * Assumes the caller knows what it's doing! (host must support these) */ case CPUMCPUIDFEATURE_SYSCALL: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fSysCall) { #if HC_ARCH_BITS == 32 /* X86_CPUID_EXT_FEATURE_EDX_SYSCALL not set it seems in 32-bit mode by Intel, even when the cpu is capable of doing so in 64-bit mode. Long mode requires syscall support. */ if (!pVM->cpum.s.HostFeatures.fLongMode) #endif { LogRel(("CPUM: WARNING! Can't turn on SYSCALL/SYSRET when the host doesn't support it!\n")); return; } } /* Valid for both Intel and AMD CPUs, although only in 64 bits mode for Intel. */ pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_EXT_FEATURE_EDX_SYSCALL; pVM->cpum.s.GuestFeatures.fSysCall = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled SYSCALL/RET\n")); break; /* * Set the PAE bit in both feature masks. * Assumes the caller knows what it's doing! (host must support these) */ case CPUMCPUIDFEATURE_PAE: if (!pVM->cpum.s.HostFeatures.fPae) { LogRel(("CPUM: WARNING! Can't turn on PAE when the host doesn't support it!\n")); return; } pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx |= X86_CPUID_FEATURE_EDX_PAE; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_AMD_FEATURE_EDX_PAE; pVM->cpum.s.GuestFeatures.fPae = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled PAE\n")); break; /* * Set the LONG MODE bit in the extended feature mask. * Assumes the caller knows what it's doing! (host must support these) */ case CPUMCPUIDFEATURE_LONG_MODE: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fLongMode) { LogRel(("CPUM: WARNING! Can't turn on LONG MODE when the host doesn't support it!\n")); return; } /* Valid for both Intel and AMD. */ pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_EXT_FEATURE_EDX_LONG_MODE; pVM->cpum.s.GuestFeatures.fLongMode = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled LONG MODE\n")); break; /* * Set the NX/XD bit in the extended feature mask. * Assumes the caller knows what it's doing! (host must support these) */ case CPUMCPUIDFEATURE_NX: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fNoExecute) { LogRel(("CPUM: WARNING! Can't turn on NX/XD when the host doesn't support it!\n")); return; } /* Valid for both Intel and AMD. */ pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_EXT_FEATURE_EDX_NX; pVM->cpum.s.GuestFeatures.fNoExecute = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled NX\n")); break; /* * Set the LAHF/SAHF support in 64-bit mode. * Assumes the caller knows what it's doing! (host must support this) */ case CPUMCPUIDFEATURE_LAHF: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fLahfSahf) { LogRel(("CPUM: WARNING! Can't turn on LAHF/SAHF when the host doesn't support it!\n")); return; } /* Valid for both Intel and AMD. */ pVM->cpum.s.aGuestCpuIdPatmExt[1].uEcx = pLeaf->uEcx |= X86_CPUID_EXT_FEATURE_ECX_LAHF_SAHF; pVM->cpum.s.GuestFeatures.fLahfSahf = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled LAHF/SAHF\n")); break; /* * Set the page attribute table bit. This is alternative page level * cache control that doesn't much matter when everything is * virtualized, though it may when passing thru device memory. */ case CPUMCPUIDFEATURE_PAT: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx |= X86_CPUID_FEATURE_EDX_PAT; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_AMD_FEATURE_EDX_PAT; pVM->cpum.s.GuestFeatures.fPat = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled PAT\n")); break; /* * Set the RDTSCP support bit. * Assumes the caller knows what it's doing! (host must support this) */ case CPUMCPUIDFEATURE_RDTSCP: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fRdTscP || pVM->cpum.s.u8PortableCpuIdLevel > 0) { if (!pVM->cpum.s.u8PortableCpuIdLevel) LogRel(("CPUM: WARNING! Can't turn on RDTSCP when the host doesn't support it!\n")); return; } /* Valid for both Intel and AMD. */ pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx |= X86_CPUID_EXT_FEATURE_EDX_RDTSCP; pVM->cpum.s.HostFeatures.fRdTscP = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled RDTSCP.\n")); break; /* * Set the Hypervisor Present bit in the standard feature mask. */ case CPUMCPUIDFEATURE_HVP: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx |= X86_CPUID_FEATURE_ECX_HVP; pVM->cpum.s.GuestFeatures.fHypervisorPresent = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled Hypervisor Present bit\n")); break; /* * Set the MWAIT Extensions Present bit in the MWAIT/MONITOR leaf. * This currently includes the Present bit and MWAITBREAK bit as well. */ case CPUMCPUIDFEATURE_MWAIT_EXTS: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000005)); if ( !pLeaf || !pVM->cpum.s.HostFeatures.fMWaitExtensions) { LogRel(("CPUM: WARNING! Can't turn on MWAIT Extensions when the host doesn't support it!\n")); return; } /* Valid for both Intel and AMD. */ pVM->cpum.s.aGuestCpuIdPatmStd[5].uEcx = pLeaf->uEcx |= X86_CPUID_MWAIT_ECX_EXT | X86_CPUID_MWAIT_ECX_BREAKIRQIF0; pVM->cpum.s.GuestFeatures.fMWaitExtensions = 1; LogRel(("CPUM: SetGuestCpuIdFeature: Enabled MWAIT Extensions.\n")); break; /* * OSXSAVE - only used from CPUMSetGuestCR4. */ case CPUMCPUIDFEATURE_OSXSAVE: AssertLogRelReturnVoid(pVM->cpum.s.HostFeatures.fXSaveRstor && pVM->cpum.s.HostFeatures.fOpSysXSaveRstor); pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); AssertLogRelReturnVoid(pLeaf); /* UNI: Special case for single CPU to make life simple for CPUMPatchHlpCpuId. */ if (pVM->cCpus == 1) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx |= X86_CPUID_FEATURE_ECX_OSXSAVE; /* SMP: Set flag indicating OSXSAVE updating (superfluous because of the APIC ID, but that's fine). */ else ASMAtomicOrU32(&pLeaf->fFlags, CPUMCPUIDLEAF_F_CONTAINS_OSXSAVE); break; default: AssertMsgFailed(("enmFeature=%d\n", enmFeature)); break; } for (VMCPUID i = 0; i < pVM->cCpus; i++) { PVMCPU pVCpu = &pVM->aCpus[i]; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_CPUID; } } /** * Queries a CPUID feature bit. * * @returns boolean for feature presence * @param pVM Pointer to the VM. * @param enmFeature The feature to query. */ VMMDECL(bool) CPUMGetGuestCpuIdFeature(PVM pVM, CPUMCPUIDFEATURE enmFeature) { switch (enmFeature) { case CPUMCPUIDFEATURE_APIC: return pVM->cpum.s.GuestFeatures.fApic; case CPUMCPUIDFEATURE_X2APIC: return pVM->cpum.s.GuestFeatures.fX2Apic; case CPUMCPUIDFEATURE_SYSCALL: return pVM->cpum.s.GuestFeatures.fSysCall; case CPUMCPUIDFEATURE_SEP: return pVM->cpum.s.GuestFeatures.fSysEnter; case CPUMCPUIDFEATURE_PAE: return pVM->cpum.s.GuestFeatures.fPae; case CPUMCPUIDFEATURE_NX: return pVM->cpum.s.GuestFeatures.fNoExecute; case CPUMCPUIDFEATURE_LAHF: return pVM->cpum.s.GuestFeatures.fLahfSahf; case CPUMCPUIDFEATURE_LONG_MODE: return pVM->cpum.s.GuestFeatures.fLongMode; case CPUMCPUIDFEATURE_PAT: return pVM->cpum.s.GuestFeatures.fPat; case CPUMCPUIDFEATURE_RDTSCP: return pVM->cpum.s.GuestFeatures.fRdTscP; case CPUMCPUIDFEATURE_HVP: return pVM->cpum.s.GuestFeatures.fHypervisorPresent; case CPUMCPUIDFEATURE_MWAIT_EXTS: return pVM->cpum.s.GuestFeatures.fMWaitExtensions; case CPUMCPUIDFEATURE_OSXSAVE: case CPUMCPUIDFEATURE_INVALID: case CPUMCPUIDFEATURE_32BIT_HACK: break; } AssertFailed(); return false; } /** * Clears a CPUID feature bit. * * @param pVM Pointer to the VM. * @param enmFeature The feature to clear. */ VMMDECL(void) CPUMClearGuestCpuIdFeature(PVM pVM, CPUMCPUIDFEATURE enmFeature) { PCPUMCPUIDLEAF pLeaf; switch (enmFeature) { case CPUMCPUIDFEATURE_APIC: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_FEATURE_EDX_APIC; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_AMD_FEATURE_EDX_APIC; pVM->cpum.s.GuestFeatures.fApic = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled APIC\n")); break; case CPUMCPUIDFEATURE_X2APIC: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx &= ~X86_CPUID_FEATURE_ECX_X2APIC; pVM->cpum.s.GuestFeatures.fX2Apic = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled x2APIC\n")); break; case CPUMCPUIDFEATURE_PAE: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_FEATURE_EDX_PAE; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_AMD_FEATURE_EDX_PAE; pVM->cpum.s.GuestFeatures.fPae = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled PAE!\n")); break; case CPUMCPUIDFEATURE_PAT: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_FEATURE_EDX_PAT; pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if ( pLeaf && pVM->cpum.s.GuestFeatures.enmCpuVendor == CPUMCPUVENDOR_AMD) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_AMD_FEATURE_EDX_PAT; pVM->cpum.s.GuestFeatures.fPat = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled PAT!\n")); break; case CPUMCPUIDFEATURE_LONG_MODE: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_EXT_FEATURE_EDX_LONG_MODE; pVM->cpum.s.GuestFeatures.fLongMode = 0; break; case CPUMCPUIDFEATURE_LAHF: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEcx = pLeaf->uEcx &= ~X86_CPUID_EXT_FEATURE_ECX_LAHF_SAHF; pVM->cpum.s.GuestFeatures.fLahfSahf = 0; break; case CPUMCPUIDFEATURE_RDTSCP: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x80000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmExt[1].uEdx = pLeaf->uEdx &= ~X86_CPUID_EXT_FEATURE_EDX_RDTSCP; pVM->cpum.s.GuestFeatures.fRdTscP = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled RDTSCP!\n")); break; case CPUMCPUIDFEATURE_HVP: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx &= ~X86_CPUID_FEATURE_ECX_HVP; pVM->cpum.s.GuestFeatures.fHypervisorPresent = 0; break; case CPUMCPUIDFEATURE_MWAIT_EXTS: pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000005)); if (pLeaf) pVM->cpum.s.aGuestCpuIdPatmStd[5].uEcx = pLeaf->uEcx &= ~(X86_CPUID_MWAIT_ECX_EXT | X86_CPUID_MWAIT_ECX_BREAKIRQIF0); pVM->cpum.s.GuestFeatures.fMWaitExtensions = 0; Log(("CPUM: ClearGuestCpuIdFeature: Disabled MWAIT Extensions!\n")); break; /* * OSXSAVE - only used from CPUMSetGuestCR4. */ case CPUMCPUIDFEATURE_OSXSAVE: AssertLogRelReturnVoid(pVM->cpum.s.HostFeatures.fXSaveRstor && pVM->cpum.s.HostFeatures.fOpSysXSaveRstor); pLeaf = cpumCpuIdGetLeaf(pVM, UINT32_C(0x00000001)); AssertLogRelReturnVoid(pLeaf); /* UNI: Special case for single CPU to make life easy for CPUMPatchHlpCpuId. */ if (pVM->cCpus == 1) pVM->cpum.s.aGuestCpuIdPatmStd[1].uEcx = pLeaf->uEcx &= ~X86_CPUID_FEATURE_ECX_OSXSAVE; /* else: SMP: We never set the OSXSAVE bit and leaving the CONTAINS_OSXSAVE flag is fine. */ break; default: AssertMsgFailed(("enmFeature=%d\n", enmFeature)); break; } for (VMCPUID i = 0; i < pVM->cCpus; i++) { PVMCPU pVCpu = &pVM->aCpus[i]; pVCpu->cpum.s.fChanged |= CPUM_CHANGED_CPUID; } } /** * Gets the host CPU vendor. * * @returns CPU vendor. * @param pVM Pointer to the VM. */ VMMDECL(CPUMCPUVENDOR) CPUMGetHostCpuVendor(PVM pVM) { return (CPUMCPUVENDOR)pVM->cpum.s.HostFeatures.enmCpuVendor; } /** * Gets the CPU vendor. * * @returns CPU vendor. * @param pVM Pointer to the VM. */ VMMDECL(CPUMCPUVENDOR) CPUMGetGuestCpuVendor(PVM pVM) { return (CPUMCPUVENDOR)pVM->cpum.s.GuestFeatures.enmCpuVendor; } VMMDECL(int) CPUMSetGuestDR0(PVMCPU pVCpu, uint64_t uDr0) { pVCpu->cpum.s.Guest.dr[0] = uDr0; return CPUMRecalcHyperDRx(pVCpu, 0, false); } VMMDECL(int) CPUMSetGuestDR1(PVMCPU pVCpu, uint64_t uDr1) { pVCpu->cpum.s.Guest.dr[1] = uDr1; return CPUMRecalcHyperDRx(pVCpu, 1, false); } VMMDECL(int) CPUMSetGuestDR2(PVMCPU pVCpu, uint64_t uDr2) { pVCpu->cpum.s.Guest.dr[2] = uDr2; return CPUMRecalcHyperDRx(pVCpu, 2, false); } VMMDECL(int) CPUMSetGuestDR3(PVMCPU pVCpu, uint64_t uDr3) { pVCpu->cpum.s.Guest.dr[3] = uDr3; return CPUMRecalcHyperDRx(pVCpu, 3, false); } VMMDECL(int) CPUMSetGuestDR6(PVMCPU pVCpu, uint64_t uDr6) { pVCpu->cpum.s.Guest.dr[6] = uDr6; return VINF_SUCCESS; /* No need to recalc. */ } VMMDECL(int) CPUMSetGuestDR7(PVMCPU pVCpu, uint64_t uDr7) { pVCpu->cpum.s.Guest.dr[7] = uDr7; return CPUMRecalcHyperDRx(pVCpu, 7, false); } VMMDECL(int) CPUMSetGuestDRx(PVMCPU pVCpu, uint32_t iReg, uint64_t Value) { AssertReturn(iReg <= DISDREG_DR7, VERR_INVALID_PARAMETER); /* DR4 is an alias for DR6, and DR5 is an alias for DR7. */ if (iReg == 4 || iReg == 5) iReg += 2; pVCpu->cpum.s.Guest.dr[iReg] = Value; return CPUMRecalcHyperDRx(pVCpu, iReg, false); } /** * Recalculates the hypervisor DRx register values based on current guest * registers and DBGF breakpoints, updating changed registers depending on the * context. * * This is called whenever a guest DRx register is modified (any context) and * when DBGF sets a hardware breakpoint (ring-3 only, rendezvous). * * In raw-mode context this function will reload any (hyper) DRx registers which * comes out with a different value. It may also have to save the host debug * registers if that haven't been done already. In this context though, we'll * be intercepting and emulating all DRx accesses, so the hypervisor DRx values * are only important when breakpoints are actually enabled. * * In ring-0 (HM) context DR0-3 will be relocated by us, while DR7 will be * reloaded by the HM code if it changes. Further more, we will only use the * combined register set when the VBox debugger is actually using hardware BPs, * when it isn't we'll keep the guest DR0-3 + (maybe) DR6 loaded (DR6 doesn't * concern us here). * * In ring-3 we won't be loading anything, so well calculate hypervisor values * all the time. * * @returns VINF_SUCCESS. * @param pVCpu Pointer to the VMCPU. * @param iGstReg The guest debug register number that was modified. * UINT8_MAX if not guest register. * @param fForceHyper Used in HM to force hyper registers because of single * stepping. */ VMMDECL(int) CPUMRecalcHyperDRx(PVMCPU pVCpu, uint8_t iGstReg, bool fForceHyper) { PVM pVM = pVCpu->CTX_SUFF(pVM); /* * Compare the DR7s first. * * We only care about the enabled flags. GD is virtualized when we * dispatch the #DB, we never enable it. The DBGF DR7 value is will * always have the LE and GE bits set, so no need to check and disable * stuff if they're cleared like we have to for the guest DR7. */ RTGCUINTREG uGstDr7 = CPUMGetGuestDR7(pVCpu); if (!(uGstDr7 & (X86_DR7_LE | X86_DR7_GE))) uGstDr7 = 0; else if (!(uGstDr7 & X86_DR7_LE)) uGstDr7 &= ~X86_DR7_LE_ALL; else if (!(uGstDr7 & X86_DR7_GE)) uGstDr7 &= ~X86_DR7_GE_ALL; const RTGCUINTREG uDbgfDr7 = DBGFBpGetDR7(pVM); #ifdef IN_RING0 if (!fForceHyper && (pVCpu->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_HYPER)) fForceHyper = true; #endif if (( HMIsEnabled(pVCpu->CTX_SUFF(pVM)) && !fForceHyper ? uDbgfDr7 : (uGstDr7 | uDbgfDr7)) & X86_DR7_ENABLED_MASK) { Assert(!CPUMIsGuestDebugStateActive(pVCpu)); #ifdef IN_RC bool const fHmEnabled = false; #elif defined(IN_RING3) bool const fHmEnabled = HMIsEnabled(pVM); #endif /* * Ok, something is enabled. Recalc each of the breakpoints, taking * the VM debugger ones of the guest ones. In raw-mode context we will * not allow breakpoints with values inside the hypervisor area. */ RTGCUINTREG uNewDr7 = X86_DR7_GE | X86_DR7_LE | X86_DR7_RA1_MASK; /* bp 0 */ RTGCUINTREG uNewDr0; if (uDbgfDr7 & (X86_DR7_L0 | X86_DR7_G0)) { uNewDr7 |= uDbgfDr7 & (X86_DR7_L0 | X86_DR7_G0 | X86_DR7_RW0_MASK | X86_DR7_LEN0_MASK); uNewDr0 = DBGFBpGetDR0(pVM); } else if (uGstDr7 & (X86_DR7_L0 | X86_DR7_G0)) { uNewDr0 = CPUMGetGuestDR0(pVCpu); #ifndef IN_RING0 if (fHmEnabled && MMHyperIsInsideArea(pVM, uNewDr0)) uNewDr0 = 0; else #endif uNewDr7 |= uGstDr7 & (X86_DR7_L0 | X86_DR7_G0 | X86_DR7_RW0_MASK | X86_DR7_LEN0_MASK); } else uNewDr0 = 0; /* bp 1 */ RTGCUINTREG uNewDr1; if (uDbgfDr7 & (X86_DR7_L1 | X86_DR7_G1)) { uNewDr7 |= uDbgfDr7 & (X86_DR7_L1 | X86_DR7_G1 | X86_DR7_RW1_MASK | X86_DR7_LEN1_MASK); uNewDr1 = DBGFBpGetDR1(pVM); } else if (uGstDr7 & (X86_DR7_L1 | X86_DR7_G1)) { uNewDr1 = CPUMGetGuestDR1(pVCpu); #ifndef IN_RING0 if (fHmEnabled && MMHyperIsInsideArea(pVM, uNewDr1)) uNewDr1 = 0; else #endif uNewDr7 |= uGstDr7 & (X86_DR7_L1 | X86_DR7_G1 | X86_DR7_RW1_MASK | X86_DR7_LEN1_MASK); } else uNewDr1 = 0; /* bp 2 */ RTGCUINTREG uNewDr2; if (uDbgfDr7 & (X86_DR7_L2 | X86_DR7_G2)) { uNewDr7 |= uDbgfDr7 & (X86_DR7_L2 | X86_DR7_G2 | X86_DR7_RW2_MASK | X86_DR7_LEN2_MASK); uNewDr2 = DBGFBpGetDR2(pVM); } else if (uGstDr7 & (X86_DR7_L2 | X86_DR7_G2)) { uNewDr2 = CPUMGetGuestDR2(pVCpu); #ifndef IN_RING0 if (fHmEnabled && MMHyperIsInsideArea(pVM, uNewDr2)) uNewDr2 = 0; else #endif uNewDr7 |= uGstDr7 & (X86_DR7_L2 | X86_DR7_G2 | X86_DR7_RW2_MASK | X86_DR7_LEN2_MASK); } else uNewDr2 = 0; /* bp 3 */ RTGCUINTREG uNewDr3; if (uDbgfDr7 & (X86_DR7_L3 | X86_DR7_G3)) { uNewDr7 |= uDbgfDr7 & (X86_DR7_L3 | X86_DR7_G3 | X86_DR7_RW3_MASK | X86_DR7_LEN3_MASK); uNewDr3 = DBGFBpGetDR3(pVM); } else if (uGstDr7 & (X86_DR7_L3 | X86_DR7_G3)) { uNewDr3 = CPUMGetGuestDR3(pVCpu); #ifndef IN_RING0 if (fHmEnabled && MMHyperIsInsideArea(pVM, uNewDr3)) uNewDr3 = 0; else #endif uNewDr7 |= uGstDr7 & (X86_DR7_L3 | X86_DR7_G3 | X86_DR7_RW3_MASK | X86_DR7_LEN3_MASK); } else uNewDr3 = 0; /* * Apply the updates. */ #ifdef IN_RC /* Make sure to save host registers first. */ if (!(pVCpu->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_HOST)) { if (!(pVCpu->cpum.s.fUseFlags & CPUM_USE_DEBUG_REGS_HOST)) { pVCpu->cpum.s.Host.dr6 = ASMGetDR6(); pVCpu->cpum.s.Host.dr7 = ASMGetDR7(); } pVCpu->cpum.s.Host.dr0 = ASMGetDR0(); pVCpu->cpum.s.Host.dr1 = ASMGetDR1(); pVCpu->cpum.s.Host.dr2 = ASMGetDR2(); pVCpu->cpum.s.Host.dr3 = ASMGetDR3(); pVCpu->cpum.s.fUseFlags |= CPUM_USED_DEBUG_REGS_HOST | CPUM_USE_DEBUG_REGS_HYPER | CPUM_USED_DEBUG_REGS_HYPER; /* We haven't loaded any hyper DRxes yet, so we'll have to load them all now. */ pVCpu->cpum.s.Hyper.dr[0] = uNewDr0; ASMSetDR0(uNewDr0); pVCpu->cpum.s.Hyper.dr[1] = uNewDr1; ASMSetDR1(uNewDr1); pVCpu->cpum.s.Hyper.dr[2] = uNewDr2; ASMSetDR2(uNewDr2); pVCpu->cpum.s.Hyper.dr[3] = uNewDr3; ASMSetDR3(uNewDr3); ASMSetDR6(X86_DR6_INIT_VAL); pVCpu->cpum.s.Hyper.dr[7] = uNewDr7; ASMSetDR7(uNewDr7); } else #endif { pVCpu->cpum.s.fUseFlags |= CPUM_USE_DEBUG_REGS_HYPER; if (uNewDr3 != pVCpu->cpum.s.Hyper.dr[3]) CPUMSetHyperDR3(pVCpu, uNewDr3); if (uNewDr2 != pVCpu->cpum.s.Hyper.dr[2]) CPUMSetHyperDR2(pVCpu, uNewDr2); if (uNewDr1 != pVCpu->cpum.s.Hyper.dr[1]) CPUMSetHyperDR1(pVCpu, uNewDr1); if (uNewDr0 != pVCpu->cpum.s.Hyper.dr[0]) CPUMSetHyperDR0(pVCpu, uNewDr0); if (uNewDr7 != pVCpu->cpum.s.Hyper.dr[7]) CPUMSetHyperDR7(pVCpu, uNewDr7); } } #ifdef IN_RING0 else if (CPUMIsGuestDebugStateActive(pVCpu)) { /* * Reload the register that was modified. Normally this won't happen * as we won't intercept DRx writes when not having the hyper debug * state loaded, but in case we do for some reason we'll simply deal * with it. */ switch (iGstReg) { case 0: ASMSetDR0(CPUMGetGuestDR0(pVCpu)); break; case 1: ASMSetDR1(CPUMGetGuestDR1(pVCpu)); break; case 2: ASMSetDR2(CPUMGetGuestDR2(pVCpu)); break; case 3: ASMSetDR3(CPUMGetGuestDR3(pVCpu)); break; default: AssertReturn(iGstReg != UINT8_MAX, VERR_INTERNAL_ERROR_3); } } #endif else { /* * No active debug state any more. In raw-mode this means we have to * make sure DR7 has everything disabled now, if we armed it already. * In ring-0 we might end up here when just single stepping. */ #if defined(IN_RC) || defined(IN_RING0) if (pVCpu->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_HYPER) { # ifdef IN_RC ASMSetDR7(X86_DR7_INIT_VAL); # endif if (pVCpu->cpum.s.Hyper.dr[0]) ASMSetDR0(0); if (pVCpu->cpum.s.Hyper.dr[1]) ASMSetDR1(0); if (pVCpu->cpum.s.Hyper.dr[2]) ASMSetDR2(0); if (pVCpu->cpum.s.Hyper.dr[3]) ASMSetDR3(0); pVCpu->cpum.s.fUseFlags &= ~CPUM_USED_DEBUG_REGS_HYPER; } #endif pVCpu->cpum.s.fUseFlags &= ~CPUM_USE_DEBUG_REGS_HYPER; /* Clear all the registers. */ pVCpu->cpum.s.Hyper.dr[7] = X86_DR7_RA1_MASK; pVCpu->cpum.s.Hyper.dr[3] = 0; pVCpu->cpum.s.Hyper.dr[2] = 0; pVCpu->cpum.s.Hyper.dr[1] = 0; pVCpu->cpum.s.Hyper.dr[0] = 0; } Log2(("CPUMRecalcHyperDRx: fUseFlags=%#x %RGr %RGr %RGr %RGr %RGr %RGr\n", pVCpu->cpum.s.fUseFlags, pVCpu->cpum.s.Hyper.dr[0], pVCpu->cpum.s.Hyper.dr[1], pVCpu->cpum.s.Hyper.dr[2], pVCpu->cpum.s.Hyper.dr[3], pVCpu->cpum.s.Hyper.dr[6], pVCpu->cpum.s.Hyper.dr[7])); return VINF_SUCCESS; } /** * Set the guest XCR0 register. * * Will load additional state if the FPU state is already loaded (in ring-0 & * raw-mode context). * * @returns VINF_SUCCESS on success, VERR_CPUM_RAISE_GP_0 on invalid input * value. * @param pVCpu Pointer to the cross context VMCPU structure for the * calling EMT. * @param uNewValue The new value. * @thread EMT(pVCpu) */ VMM_INT_DECL(int) CPUMSetGuestXcr0(PVMCPU pVCpu, uint64_t uNewValue) { if ( (uNewValue & ~pVCpu->CTX_SUFF(pVM)->cpum.s.fXStateGuestMask) == 0 /* The X87 bit cannot be cleared. */ && (uNewValue & XSAVE_C_X87) /* AVX requires SSE. */ && (uNewValue & (XSAVE_C_SSE | XSAVE_C_YMM)) != XSAVE_C_YMM /* AVX-512 requires YMM, SSE and all of its three components to be enabled. */ && ( (uNewValue & (XSAVE_C_OPMASK | XSAVE_C_ZMM_HI256 | XSAVE_C_ZMM_16HI)) == 0 || (uNewValue & (XSAVE_C_SSE | XSAVE_C_YMM | XSAVE_C_OPMASK | XSAVE_C_ZMM_HI256 | XSAVE_C_ZMM_16HI)) == (XSAVE_C_SSE | XSAVE_C_YMM | XSAVE_C_OPMASK | XSAVE_C_ZMM_HI256 | XSAVE_C_ZMM_16HI) ) ) { pVCpu->cpum.s.Guest.aXcr[0] = uNewValue; /* If more state components are enabled, we need to take care to load them if the FPU/SSE state is already loaded. May otherwise leak host state to the guest. */ uint64_t fNewComponents = ~pVCpu->cpum.s.Guest.fXStateMask & uNewValue; if (fNewComponents) { #if defined(IN_RING0) || defined(IN_RC) if (pVCpu->cpum.s.fUseFlags & CPUM_USED_FPU) { if (pVCpu->cpum.s.Guest.fXStateMask != 0) /* Adding more components. */ ASMXRstor(pVCpu->cpum.s.Guest.CTX_SUFF(pXState), fNewComponents); else { /* We're switching from FXSAVE/FXRSTOR to XSAVE/XRSTOR. */ pVCpu->cpum.s.Guest.fXStateMask |= XSAVE_C_X87 | XSAVE_C_SSE; if (uNewValue & ~(XSAVE_C_X87 | XSAVE_C_SSE)) ASMXRstor(pVCpu->cpum.s.Guest.CTX_SUFF(pXState), uNewValue & ~(XSAVE_C_X87 | XSAVE_C_SSE)); } } #endif pVCpu->cpum.s.Guest.fXStateMask |= uNewValue; } return VINF_SUCCESS; } return VERR_CPUM_RAISE_GP_0; } /** * Tests if the guest has No-Execute Page Protection Enabled (NXE). * * @returns true if in real mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestNXEnabled(PVMCPU pVCpu) { return !!(pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_NXE); } /** * Tests if the guest has the Page Size Extension enabled (PSE). * * @returns true if in real mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestPageSizeExtEnabled(PVMCPU pVCpu) { /* PAE or AMD64 implies support for big pages regardless of CR4.PSE */ return !!(pVCpu->cpum.s.Guest.cr4 & (X86_CR4_PSE | X86_CR4_PAE)); } /** * Tests if the guest has the paging enabled (PG). * * @returns true if in real mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestPagingEnabled(PVMCPU pVCpu) { return !!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PG); } /** * Tests if the guest has the paging enabled (PG). * * @returns true if in real mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestR0WriteProtEnabled(PVMCPU pVCpu) { return !!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_WP); } /** * Tests if the guest is running in real mode or not. * * @returns true if in real mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInRealMode(PVMCPU pVCpu) { return !(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE); } /** * Tests if the guest is running in real or virtual 8086 mode. * * @returns @c true if it is, @c false if not. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInRealOrV86Mode(PVMCPU pVCpu) { return !(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE) || pVCpu->cpum.s.Guest.eflags.Bits.u1VM; /** @todo verify that this cannot be set in long mode. */ } /** * Tests if the guest is running in protected or not. * * @returns true if in protected mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInProtectedMode(PVMCPU pVCpu) { return !!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE); } /** * Tests if the guest is running in paged protected or not. * * @returns true if in paged protected mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInPagedProtectedMode(PVMCPU pVCpu) { return (pVCpu->cpum.s.Guest.cr0 & (X86_CR0_PE | X86_CR0_PG)) == (X86_CR0_PE | X86_CR0_PG); } /** * Tests if the guest is running in long mode or not. * * @returns true if in long mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInLongMode(PVMCPU pVCpu) { return (pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA) == MSR_K6_EFER_LMA; } /** * Tests if the guest is running in PAE mode or not. * * @returns true if in PAE mode, otherwise false. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestInPAEMode(PVMCPU pVCpu) { /* Intel mentions EFER.LMA and EFER.LME in different parts of their spec. We shall use EFER.LMA rather than EFER.LME as it reflects if the CPU has entered paging with EFER.LME set. */ return (pVCpu->cpum.s.Guest.cr4 & X86_CR4_PAE) && (pVCpu->cpum.s.Guest.cr0 & X86_CR0_PG) && !(pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA); } /** * Tests if the guest is running in 64 bits mode or not. * * @returns true if in 64 bits protected mode, otherwise false. * @param pVCpu The current virtual CPU. */ VMMDECL(bool) CPUMIsGuestIn64BitCode(PVMCPU pVCpu) { if (!CPUMIsGuestInLongMode(pVCpu)) return false; CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, &pVCpu->cpum.s.Guest.cs); return pVCpu->cpum.s.Guest.cs.Attr.n.u1Long; } /** * Helper for CPUMIsGuestIn64BitCodeEx that handles lazy resolving of hidden CS * registers. * * @returns true if in 64 bits protected mode, otherwise false. * @param pCtx Pointer to the current guest CPU context. */ VMM_INT_DECL(bool) CPUMIsGuestIn64BitCodeSlow(PCPUMCTX pCtx) { return CPUMIsGuestIn64BitCode(CPUM_GUEST_CTX_TO_VMCPU(pCtx)); } #ifdef VBOX_WITH_RAW_MODE_NOT_R0 /** * * @returns @c true if we've entered raw-mode and selectors with RPL=1 are * really RPL=0, @c false if we've not (RPL=1 really is RPL=1). * @param pVCpu The current virtual CPU. */ VMM_INT_DECL(bool) CPUMIsGuestInRawMode(PVMCPU pVCpu) { return pVCpu->cpum.s.fRawEntered; } /** * Transforms the guest CPU state to raw-ring mode. * * This function will change the any of the cs and ss register with DPL=0 to DPL=1. * * @returns VBox status. (recompiler failure) * @param pVCpu Pointer to the VMCPU. * @see @ref pg_raw */ VMM_INT_DECL(int) CPUMRawEnter(PVMCPU pVCpu) { PVM pVM = pVCpu->CTX_SUFF(pVM); Assert(!pVCpu->cpum.s.fRawEntered); Assert(!pVCpu->cpum.s.fRemEntered); PCPUMCTX pCtx = &pVCpu->cpum.s.Guest; /* * Are we in Ring-0? */ if ( pCtx->ss.Sel && (pCtx->ss.Sel & X86_SEL_RPL) == 0 && !pCtx->eflags.Bits.u1VM) { /* * Enter execution mode. */ PATMRawEnter(pVM, pCtx); /* * Set CPL to Ring-1. */ pCtx->ss.Sel |= 1; if ( pCtx->cs.Sel && (pCtx->cs.Sel & X86_SEL_RPL) == 0) pCtx->cs.Sel |= 1; } else { # ifdef VBOX_WITH_RAW_RING1 if ( EMIsRawRing1Enabled(pVM) && !pCtx->eflags.Bits.u1VM && (pCtx->ss.Sel & X86_SEL_RPL) == 1) { /* Set CPL to Ring-2. */ pCtx->ss.Sel = (pCtx->ss.Sel & ~X86_SEL_RPL) | 2; if (pCtx->cs.Sel && (pCtx->cs.Sel & X86_SEL_RPL) == 1) pCtx->cs.Sel = (pCtx->cs.Sel & ~X86_SEL_RPL) | 2; } # else AssertMsg((pCtx->ss.Sel & X86_SEL_RPL) >= 2 || pCtx->eflags.Bits.u1VM, ("ring-1 code not supported\n")); # endif /* * PATM takes care of IOPL and IF flags for Ring-3 and Ring-2 code as well. */ PATMRawEnter(pVM, pCtx); } /* * Assert sanity. */ AssertMsg((pCtx->eflags.u32 & X86_EFL_IF), ("X86_EFL_IF is clear\n")); AssertReleaseMsg(pCtx->eflags.Bits.u2IOPL == 0, ("X86_EFL_IOPL=%d CPL=%d\n", pCtx->eflags.Bits.u2IOPL, pCtx->ss.Sel & X86_SEL_RPL)); Assert((pVCpu->cpum.s.Guest.cr0 & (X86_CR0_PG | X86_CR0_WP | X86_CR0_PE)) == (X86_CR0_PG | X86_CR0_PE | X86_CR0_WP)); pCtx->eflags.u32 |= X86_EFL_IF; /* paranoia */ pVCpu->cpum.s.fRawEntered = true; return VINF_SUCCESS; } /** * Transforms the guest CPU state from raw-ring mode to correct values. * * This function will change any selector registers with DPL=1 to DPL=0. * * @returns Adjusted rc. * @param pVCpu Pointer to the VMCPU. * @param rc Raw mode return code * @see @ref pg_raw */ VMM_INT_DECL(int) CPUMRawLeave(PVMCPU pVCpu, int rc) { PVM pVM = pVCpu->CTX_SUFF(pVM); /* * Don't leave if we've already left (in RC). */ Assert(!pVCpu->cpum.s.fRemEntered); if (!pVCpu->cpum.s.fRawEntered) return rc; pVCpu->cpum.s.fRawEntered = false; PCPUMCTX pCtx = &pVCpu->cpum.s.Guest; Assert(pCtx->eflags.Bits.u1VM || (pCtx->ss.Sel & X86_SEL_RPL)); AssertMsg(pCtx->eflags.Bits.u1VM || pCtx->eflags.Bits.u2IOPL < (unsigned)(pCtx->ss.Sel & X86_SEL_RPL), ("X86_EFL_IOPL=%d CPL=%d\n", pCtx->eflags.Bits.u2IOPL, pCtx->ss.Sel & X86_SEL_RPL)); /* * Are we executing in raw ring-1? */ if ( (pCtx->ss.Sel & X86_SEL_RPL) == 1 && !pCtx->eflags.Bits.u1VM) { /* * Leave execution mode. */ PATMRawLeave(pVM, pCtx, rc); /* Not quite sure if this is really required, but shouldn't harm (too much anyways). */ /** @todo See what happens if we remove this. */ if ((pCtx->ds.Sel & X86_SEL_RPL) == 1) pCtx->ds.Sel &= ~X86_SEL_RPL; if ((pCtx->es.Sel & X86_SEL_RPL) == 1) pCtx->es.Sel &= ~X86_SEL_RPL; if ((pCtx->fs.Sel & X86_SEL_RPL) == 1) pCtx->fs.Sel &= ~X86_SEL_RPL; if ((pCtx->gs.Sel & X86_SEL_RPL) == 1) pCtx->gs.Sel &= ~X86_SEL_RPL; /* * Ring-1 selector => Ring-0. */ pCtx->ss.Sel &= ~X86_SEL_RPL; if ((pCtx->cs.Sel & X86_SEL_RPL) == 1) pCtx->cs.Sel &= ~X86_SEL_RPL; } else { /* * PATM is taking care of the IOPL and IF flags for us. */ PATMRawLeave(pVM, pCtx, rc); if (!pCtx->eflags.Bits.u1VM) { # ifdef VBOX_WITH_RAW_RING1 if ( EMIsRawRing1Enabled(pVM) && (pCtx->ss.Sel & X86_SEL_RPL) == 2) { /* Not quite sure if this is really required, but shouldn't harm (too much anyways). */ /** @todo See what happens if we remove this. */ if ((pCtx->ds.Sel & X86_SEL_RPL) == 2) pCtx->ds.Sel = (pCtx->ds.Sel & ~X86_SEL_RPL) | 1; if ((pCtx->es.Sel & X86_SEL_RPL) == 2) pCtx->es.Sel = (pCtx->es.Sel & ~X86_SEL_RPL) | 1; if ((pCtx->fs.Sel & X86_SEL_RPL) == 2) pCtx->fs.Sel = (pCtx->fs.Sel & ~X86_SEL_RPL) | 1; if ((pCtx->gs.Sel & X86_SEL_RPL) == 2) pCtx->gs.Sel = (pCtx->gs.Sel & ~X86_SEL_RPL) | 1; /* * Ring-2 selector => Ring-1. */ pCtx->ss.Sel = (pCtx->ss.Sel & ~X86_SEL_RPL) | 1; if ((pCtx->cs.Sel & X86_SEL_RPL) == 2) pCtx->cs.Sel = (pCtx->cs.Sel & ~X86_SEL_RPL) | 1; } else { # endif /** @todo See what happens if we remove this. */ if ((pCtx->ds.Sel & X86_SEL_RPL) == 1) pCtx->ds.Sel &= ~X86_SEL_RPL; if ((pCtx->es.Sel & X86_SEL_RPL) == 1) pCtx->es.Sel &= ~X86_SEL_RPL; if ((pCtx->fs.Sel & X86_SEL_RPL) == 1) pCtx->fs.Sel &= ~X86_SEL_RPL; if ((pCtx->gs.Sel & X86_SEL_RPL) == 1) pCtx->gs.Sel &= ~X86_SEL_RPL; # ifdef VBOX_WITH_RAW_RING1 } # endif } } return rc; } #endif /* VBOX_WITH_RAW_MODE_NOT_R0 */ /** * Updates the EFLAGS while we're in raw-mode. * * @param pVCpu Pointer to the VMCPU. * @param fEfl The new EFLAGS value. */ VMMDECL(void) CPUMRawSetEFlags(PVMCPU pVCpu, uint32_t fEfl) { #ifdef VBOX_WITH_RAW_MODE_NOT_R0 if (pVCpu->cpum.s.fRawEntered) PATMRawSetEFlags(pVCpu->CTX_SUFF(pVM), &pVCpu->cpum.s.Guest, fEfl); else #endif pVCpu->cpum.s.Guest.eflags.u32 = fEfl; } /** * Gets the EFLAGS while we're in raw-mode. * * @returns The eflags. * @param pVCpu Pointer to the current virtual CPU. */ VMMDECL(uint32_t) CPUMRawGetEFlags(PVMCPU pVCpu) { #ifdef VBOX_WITH_RAW_MODE_NOT_R0 if (pVCpu->cpum.s.fRawEntered) return PATMRawGetEFlags(pVCpu->CTX_SUFF(pVM), &pVCpu->cpum.s.Guest); #endif return pVCpu->cpum.s.Guest.eflags.u32; } /** * Sets the specified changed flags (CPUM_CHANGED_*). * * @param pVCpu Pointer to the current virtual CPU. */ VMMDECL(void) CPUMSetChangedFlags(PVMCPU pVCpu, uint32_t fChangedFlags) { pVCpu->cpum.s.fChanged |= fChangedFlags; } /** * Checks if the CPU supports the XSAVE and XRSTOR instruction. * * @returns true if supported. * @returns false if not supported. * @param pVM Pointer to the VM. */ VMMDECL(bool) CPUMSupportsXSave(PVM pVM) { return pVM->cpum.s.HostFeatures.fXSaveRstor != 0; } /** * Checks if the host OS uses the SYSENTER / SYSEXIT instructions. * @returns true if used. * @returns false if not used. * @param pVM Pointer to the VM. */ VMMDECL(bool) CPUMIsHostUsingSysEnter(PVM pVM) { return RT_BOOL(pVM->cpum.s.fHostUseFlags & CPUM_USE_SYSENTER); } /** * Checks if the host OS uses the SYSCALL / SYSRET instructions. * @returns true if used. * @returns false if not used. * @param pVM Pointer to the VM. */ VMMDECL(bool) CPUMIsHostUsingSysCall(PVM pVM) { return RT_BOOL(pVM->cpum.s.fHostUseFlags & CPUM_USE_SYSCALL); } #ifdef IN_RC /** * Lazily sync in the FPU/XMM state. * * @returns VBox status code. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(int) CPUMHandleLazyFPU(PVMCPU pVCpu) { return cpumHandleLazyFPUAsm(&pVCpu->cpum.s); } #endif /* !IN_RC */ /** * Checks if we activated the FPU/XMM state of the guest OS. * @returns true if we did. * @returns false if not. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestFPUStateActive(PVMCPU pVCpu) { return RT_BOOL(pVCpu->cpum.s.fUseFlags & CPUM_USED_FPU); } /** * Checks if the guest debug state is active. * * @returns boolean * @param pVM Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestDebugStateActive(PVMCPU pVCpu) { return RT_BOOL(pVCpu->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_GUEST); } /** * Checks if the guest debug state is to be made active during the world-switch * (currently only used for the 32->64 switcher case). * * @returns boolean * @param pVM Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsGuestDebugStateActivePending(PVMCPU pVCpu) { return RT_BOOL(pVCpu->cpum.s.fUseFlags & CPUM_SYNC_DEBUG_REGS_GUEST); } /** * Checks if the hyper debug state is active. * * @returns boolean * @param pVM Pointer to the VM. */ VMMDECL(bool) CPUMIsHyperDebugStateActive(PVMCPU pVCpu) { return RT_BOOL(pVCpu->cpum.s.fUseFlags & CPUM_USED_DEBUG_REGS_HYPER); } /** * Checks if the hyper debug state is to be made active during the world-switch * (currently only used for the 32->64 switcher case). * * @returns boolean * @param pVM Pointer to the VMCPU. */ VMMDECL(bool) CPUMIsHyperDebugStateActivePending(PVMCPU pVCpu) { return RT_BOOL(pVCpu->cpum.s.fUseFlags & CPUM_SYNC_DEBUG_REGS_HYPER); } /** * Mark the guest's debug state as inactive. * * @returns boolean * @param pVM Pointer to the VM. * @todo This API doesn't make sense any more. */ VMMDECL(void) CPUMDeactivateGuestDebugState(PVMCPU pVCpu) { Assert(!(pVCpu->cpum.s.fUseFlags & (CPUM_USED_DEBUG_REGS_GUEST | CPUM_USED_DEBUG_REGS_HYPER | CPUM_USED_DEBUG_REGS_HOST))); } /** * Get the current privilege level of the guest. * * @returns CPL * @param pVCpu Pointer to the current virtual CPU. */ VMMDECL(uint32_t) CPUMGetGuestCPL(PVMCPU pVCpu) { /* * CPL can reliably be found in SS.DPL (hidden regs valid) or SS if not. * * Note! We used to check CS.DPL here, assuming it was always equal to * CPL even if a conforming segment was loaded. But this truned out to * only apply to older AMD-V. With VT-x we had an ACP2 regression * during install after a far call to ring 2 with VT-x. Then on newer * AMD-V CPUs we have to move the VMCB.guest.u8CPL into cs.Attr.n.u2Dpl * as well as ss.Attr.n.u2Dpl to make this (and other) code work right. * * So, forget CS.DPL, always use SS.DPL. * * Note! The SS RPL is always equal to the CPL, while the CS RPL * isn't necessarily equal if the segment is conforming. * See section 4.11.1 in the AMD manual. * * Update: Where the heck does it say CS.RPL can differ from CPL other than * right after real->prot mode switch and when in V8086 mode? That * section says the RPL specified in a direct transfere (call, jmp, * ret) is not the one loaded into CS. Besides, if CS.RPL != CPL * it would be impossible for an exception handle or the iret * instruction to figure out whether SS:ESP are part of the frame * or not. VBox or qemu bug must've lead to this misconception. * * Update2: On an AMD bulldozer system here, I've no trouble loading a null * selector into SS with an RPL other than the CPL when CPL != 3 and * we're in 64-bit mode. The intel dev box doesn't allow this, on * RPL = CPL. Weird. */ uint32_t uCpl; if (pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE) { if (!pVCpu->cpum.s.Guest.eflags.Bits.u1VM) { if (CPUMSELREG_ARE_HIDDEN_PARTS_VALID(pVCpu, &pVCpu->cpum.s.Guest.ss)) uCpl = pVCpu->cpum.s.Guest.ss.Attr.n.u2Dpl; else { uCpl = (pVCpu->cpum.s.Guest.ss.Sel & X86_SEL_RPL); #ifdef VBOX_WITH_RAW_MODE_NOT_R0 # ifdef VBOX_WITH_RAW_RING1 if (pVCpu->cpum.s.fRawEntered) { if ( uCpl == 2 && EMIsRawRing1Enabled(pVCpu->CTX_SUFF(pVM))) uCpl = 1; else if (uCpl == 1) uCpl = 0; } Assert(uCpl != 2); /* ring 2 support not allowed anymore. */ # else if (uCpl == 1) uCpl = 0; # endif #endif } } else uCpl = 3; /* V86 has CPL=3; REM doesn't set DPL=3 in V8086 mode. See @bugref{5130}. */ } else uCpl = 0; /* Real mode is zero; CPL set to 3 for VT-x real-mode emulation. */ return uCpl; } /** * Gets the current guest CPU mode. * * If paging mode is what you need, check out PGMGetGuestMode(). * * @returns The CPU mode. * @param pVCpu Pointer to the VMCPU. */ VMMDECL(CPUMMODE) CPUMGetGuestMode(PVMCPU pVCpu) { CPUMMODE enmMode; if (!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE)) enmMode = CPUMMODE_REAL; else if (!(pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA)) enmMode = CPUMMODE_PROTECTED; else enmMode = CPUMMODE_LONG; return enmMode; } /** * Figure whether the CPU is currently executing 16, 32 or 64 bit code. * * @returns 16, 32 or 64. * @param pVCpu The current virtual CPU. */ VMMDECL(uint32_t) CPUMGetGuestCodeBits(PVMCPU pVCpu) { if (!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE)) return 16; if (pVCpu->cpum.s.Guest.eflags.Bits.u1VM) { Assert(!(pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA)); return 16; } CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, &pVCpu->cpum.s.Guest.cs); if ( pVCpu->cpum.s.Guest.cs.Attr.n.u1Long && (pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA)) return 64; if (pVCpu->cpum.s.Guest.cs.Attr.n.u1DefBig) return 32; return 16; } VMMDECL(DISCPUMODE) CPUMGetGuestDisMode(PVMCPU pVCpu) { if (!(pVCpu->cpum.s.Guest.cr0 & X86_CR0_PE)) return DISCPUMODE_16BIT; if (pVCpu->cpum.s.Guest.eflags.Bits.u1VM) { Assert(!(pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA)); return DISCPUMODE_16BIT; } CPUMSELREG_LAZY_LOAD_HIDDEN_PARTS(pVCpu, &pVCpu->cpum.s.Guest.cs); if ( pVCpu->cpum.s.Guest.cs.Attr.n.u1Long && (pVCpu->cpum.s.Guest.msrEFER & MSR_K6_EFER_LMA)) return DISCPUMODE_64BIT; if (pVCpu->cpum.s.Guest.cs.Attr.n.u1DefBig) return DISCPUMODE_32BIT; return DISCPUMODE_16BIT; }
86,599
37,337
#include "ann.h" bool training = true; //======================Set Network Size============================= std::ofstream config; //store network size for testing purpose std::string config_file = "config.dat"; DataSet dataset = MNIST; int numOfLayers; std::vector<int> numOfNeurons; //User Interface for network setting void networkConstruction(){ std::string defaultSetting; int userInput; std::cout << "**************************************************" << std::endl; std::cout << "**************** Default Setting *****************" << std::endl; std::cout << "**************************************************" << std::endl; std::cout<< "Number of Layers: " << numOfLayers << std::endl; for (int i = 0; i < numOfLayers; i++) std::cout<< "Number of Neurons in Layer " << i+1 << ": " << numOfNeurons[i] << std::endl; std::cout<< "Use the default setting? (Y/N):"; std::cin >> defaultSetting; if (defaultSetting == "Y" || defaultSetting == "y"){ std::cout << "Default setting chose. Press any key to continue.\n" << std::endl; getchar(); } else{ numOfNeurons.clear(); std::cout<< "Please enter number of layers (input layer included): "; std::cin >> numOfLayers; for (int i = 1; i <= numOfLayers; i++){ std::cout<< "Please enter number of neurons for layer " << i << ": "; std::cin >> userInput; numOfNeurons.push_back(userInput); } } //write setting to config file config.open(config_file.c_str(), std::ios::out); config << numOfLayers << std::endl; for (int i = 0; i < numOfNeurons.size(); i++) config << numOfNeurons[i] << std::endl; config.close(); } int main(){ //default setting //single hidden layer and 128 neurons numOfLayers = 3; numOfNeurons.resize(numOfLayers); numOfNeurons[0] = IN_SIZE; numOfNeurons[1] = HL_SIZE; numOfNeurons[2] = OUT_SIZE; networkConstruction(); //============Create Network==================== Ann training_nn(sigmoidFunct, numOfLayers, numOfNeurons, training); //Ann training_nn (reluFunct, numOfLayers, numOfNeurons, training); training_nn.chooseDataset(dataset); training_nn.initAnn(); training_nn.summary(); //print basic network information training_nn.readHeader(); //get rid of header from image file (for MNIST) int SampleSize = training_nn.getTrainSize(); //================Traing======================== for (int sample = 0; sample < SampleSize; sample++) { std::cout << "Sample " << sample+1 << ": "; int nIterations = 0; double error = 0; training_nn.loadInput(); nIterations = training_nn.learning(); // Write down the squared error std::cout << "No. iterations: " << nIterations << ". "; error = training_nn.squareError(); printf("Error: %0.6lf\n", error); training_nn.trainReport(sample, nIterations, error); // Save the current weight matrix every 100 samples if (sample != 0 && sample % 100 == 0) { std::cout << "Saving weight matrix.\n"; training_nn.writeWeight(); } } training_nn.writeWeight(); std::cout << "Training Completed.\n"; return 0; }
3,349
1,032
// Copyright 2018 The Chromium OS 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 "crosdns/hosts_modifier.h" #include <string> #include <base/files/scoped_temp_dir.h> #include <base/files/file_path.h> #include <base/files/file_util.h> #include <gtest/gtest.h> namespace crosdns { namespace { constexpr char kBaseFileContents[] = "# Example /etc/hosts file\n" "127.0.0.1 localhost\n"; constexpr char kFileModificationDelimeter[] = "\n#####DYNAMIC-CROSDNS-ENTRIES#####\n"; class HostsModifierTest : public ::testing::Test { public: HostsModifierTest() { CHECK(temp_dir_.CreateUniqueTempDir()); hosts_file_ = temp_dir_.GetPath().Append("hosts"); WriteHostsContents(kBaseFileContents); } HostsModifierTest(const HostsModifierTest&) = delete; HostsModifierTest& operator=(const HostsModifierTest&) = delete; ~HostsModifierTest() override = default; void WriteHostsContents(const std::string& file_contents) { EXPECT_EQ(file_contents.size(), base::WriteFile(hosts_file_, file_contents.c_str(), file_contents.size())); } std::string ReadHostsContents() const { std::string ret; EXPECT_TRUE(base::ReadFileToString(hosts_file_, &ret)); return ret; } HostsModifier* hosts_modifier() { return &hosts_modifier_; } base::FilePath hosts_file() const { return hosts_file_; } private: base::ScopedTempDir temp_dir_; base::FilePath hosts_file_; HostsModifier hosts_modifier_; }; } // namespace TEST_F(HostsModifierTest, InitSucceeds) { EXPECT_TRUE(hosts_modifier()->Init(hosts_file())); // The hosts file contents should be unchanged now. EXPECT_EQ(kBaseFileContents, ReadHostsContents()); } TEST_F(HostsModifierTest, InitFailsNonExistentFile) { EXPECT_TRUE(base::DeleteFile(hosts_file())); EXPECT_FALSE(hosts_modifier()->Init(hosts_file())); } TEST_F(HostsModifierTest, InitRemovesOldEntries) { std::string extra_contents = kBaseFileContents; extra_contents += kFileModificationDelimeter; extra_contents += "1.2.3.4 example.com\n"; WriteHostsContents(extra_contents); EXPECT_TRUE(hosts_modifier()->Init(hosts_file())); // The hosts file contents should be the original contents up to our // delimeter. EXPECT_EQ(kBaseFileContents, ReadHostsContents()); } TEST_F(HostsModifierTest, SettingRemovingHostnames) { std::string err; EXPECT_TRUE(hosts_modifier()->Init(hosts_file())); // Valid hostname for default container. EXPECT_TRUE(hosts_modifier()->SetHostnameIpMapping( "penguin.linux.test", "100.115.92.24", "", &err)); // Valid hostnames for vm/container. EXPECT_TRUE(hosts_modifier()->SetHostnameIpMapping( "foo12.linux.test", "100.115.92.22", "", &err)); EXPECT_TRUE(hosts_modifier()->SetHostnameIpMapping( "penguin.termina.linux.test", "100.115.92.253", "", &err)); // Invalid hostnames. EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "google.com", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "localhost", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "-foo-local", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "foo..linux.test", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( ".linux.test", "100.115.92.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "linux.test", "100.115.92.24", "", &err)); EXPECT_FALSE( hosts_modifier()->SetHostnameIpMapping("", "100.115.92.24", "", &err)); // Invalid IPs. EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "penguin.linux.test", "100.115.91.24", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping("penguin.linux.test", "8.8.8.8", "", &err)); EXPECT_FALSE(hosts_modifier()->SetHostnameIpMapping( "penguin.linux.test", "101.115.92.24", "", &err)); // Verify the contents of the hosts file. We are assuming an ordered map is // used here (which it is in the code) to make analyzing the results easier. std::string extra_contents = kBaseFileContents; extra_contents += kFileModificationDelimeter; extra_contents += "100.115.92.22 foo12.linux.test\n"; extra_contents += "100.115.92.24 penguin.linux.test\n"; extra_contents += "100.115.92.253 penguin.termina.linux.test\n"; EXPECT_EQ(extra_contents, ReadHostsContents()); // Removing an invalid hostname should fail. EXPECT_FALSE(hosts_modifier()->RemoveHostnameIpMapping("bar-local", &err)); EXPECT_FALSE(hosts_modifier()->RemoveHostnameIpMapping("google.com", &err)); // Removing a valid hostname should succeed. EXPECT_TRUE( hosts_modifier()->RemoveHostnameIpMapping("penguin.linux.test", &err)); EXPECT_TRUE( hosts_modifier()->RemoveHostnameIpMapping("foo12.linux.test", &err)); // Verify the contents of the hosts file again, there should be one entry // left. extra_contents = kBaseFileContents; extra_contents += kFileModificationDelimeter; extra_contents += "100.115.92.253 penguin.termina.linux.test\n"; EXPECT_EQ(extra_contents, ReadHostsContents()); } } // namespace crosdns
5,322
1,925
/* * binary_search_tree.cpp * Copyright (C) 2020 sylveryte <sylveryte@archred> * * Distributed under terms of the MIT license. */ #include "binary_search_tree.h" #include "../sylvtools.cpp" int main(){ binary_search_tree b(21); b.insert(21); b.insert(1); b.insert(23); b.insert(233); b.insert(4); b.print_tree(); //to sort //yeah!! i'm amazing int a[13]={12,24,54,2,452,36,23,6,325732,45,2346234,23,1}; printa("before",a,13); binary_search_tree sor(12); for(int i=1;i<13;i++)sor.insert(a[i]); sor.print_tree(); sor.get_sorted_array(a); printa("after",a,13); return 0; } //implementations binary_search_tree::binary_search_tree(int value){ this -> head = new node(value); this -> size = 1; } void binary_search_tree::insert(int value){ node* node_ptr = this -> head; while(true) if(node_ptr -> value >= value){ //cout << "arg " << node_ptr-> value << " <= " << value << endl; //cout << "adding " << value << " to left" << endl; if( node_ptr -> leftchild == nullptr) { node_ptr -> leftchild = new node(value); node_ptr -> leftchild -> parent = node_ptr; this -> size++; break; } node_ptr = node_ptr -> leftchild; } else{ //cout << "arg " << node_ptr-> value << " > " << value << endl; //cout << "adding " << value << " to rigth" << endl; if( node_ptr -> rightchild == nullptr) { node_ptr -> rightchild = new node(value); node_ptr -> rightchild -> parent = node_ptr; this -> size++; break; } node_ptr = node_ptr -> rightchild; } } void binary_search_tree::inorder_traverse(int* a, node* n){ /* takes an empty array a and node from where sorted array needed. * fills array with ascending order node vallues (sorted array) using inorder_traverssal * */ if(n-> leftchild != nullptr)inorder_traverse(a,n->leftchild); a[this -> inorder_index++]=n->value; if(n-> rightchild != nullptr)inorder_traverse(a,n->rightchild); } void binary_search_tree::get_sorted_array(int* a){ this -> inorder_index = 0; inorder_traverse(a,this->head); } /* printing purpose */ void binary_search_tree::print_node(node* ptr){ if(ptr -> leftchild == nullptr && ptr -> rightchild == nullptr)return; cout << "|| " << ptr -> value << " : "; if(ptr->leftchild != nullptr){ cout << ptr-> leftchild-> value ; } cout<< " _ "; if(ptr->rightchild != nullptr){ cout << ptr-> rightchild-> value ; } cout << " ||" << endl; if(ptr->leftchild != nullptr)print_node(ptr->leftchild); if(ptr->rightchild != nullptr)print_node(ptr->rightchild); } void binary_search_tree::print_tree(){ cout << "Tree of size : " << this->size << endl; print_node(this->head); cout <<endl; }
2,662
1,090
#include "Asteroid.h" #define REFINEMENT_LEVEL 2 #define BASE_RADIUS 1.9021f #define MAX_VELOCITY 0.05 #define MAX_ROTATION 5.0 float Asteroid::nextID = 1.0; Asteroid::Asteroid(){ Asteroid(glm::vec3(0), 0, 1.9021); } Asteroid::Asteroid(glm::vec3 startingPosition, int elementOffset, GLfloat radius) { this->radius = radius; setStartingPoint(startingPosition); this->elementOffset = elementOffset; alive = true; asteroidID = nextID; nextID += 1.0; generateAsteroidBase(); deformAndTransformBase(); calculateDeformedResultantRadius(); GLfloat xPos = -MAX_VELOCITY + (float)rand()/((float)RAND_MAX/(MAX_VELOCITY-(-MAX_VELOCITY))); GLfloat yPos = -MAX_VELOCITY + (float)rand()/((float)RAND_MAX/(MAX_VELOCITY-(-MAX_VELOCITY))); GLfloat zPos = -MAX_VELOCITY + (float)rand()/((float)RAND_MAX/(MAX_VELOCITY-(-MAX_VELOCITY))); velocityVector = glm::vec3(xPos, yPos, zPos); GLfloat xRot = -MAX_ROTATION + (float)rand()/((float)RAND_MAX/(MAX_ROTATION-(-MAX_ROTATION))); GLfloat yRot = -MAX_ROTATION + (float)rand()/((float)RAND_MAX/(MAX_ROTATION-(-MAX_ROTATION))); GLfloat zRot = -MAX_ROTATION + (float)rand()/((float)RAND_MAX/(MAX_ROTATION-(-MAX_ROTATION))); this->rotationRates = glm::vec3(xRot, yRot, zRot); this->rotation = glm::mat4(1); } Asteroid::~Asteroid(void) { } vector<GLfloat> Asteroid::getNormals(){ return this->asteroidGLNormals; } vector<GLfloat> Asteroid::getVertices(){ return this->asteroidGLVertices; } vector<GLuint> Asteroid::getElementArray(){ return elements; } vector<GLfloat> Asteroid::getColors(){ return colors; } glm::vec3 Asteroid::getPosition(){ return this->position; } GLfloat Asteroid::getRadius(){ return this->radius; } bool Asteroid::isAlive(){ return alive; } void Asteroid::kill(){ this->alive = false; } float Asteroid::getID(){ return this->asteroidID; } void Asteroid::setStartingPoint(glm::vec3 startingPosition){ this->position = startingPosition; glm::vec3 translateVector = this->position; this->translation = glm::translate(glm::mat4(1), translateVector); } glm::mat4 Asteroid::getTransformMatrix(float bounds, bool pickingPass){ glm::mat4 S = glm::scale(glm::mat4(1), glm::vec3(radius / deformedResultantRadius, radius / deformedResultantRadius, radius / deformedResultantRadius)); if(!pickingPass){ this->position += velocityVector; glm::mat4 T = glm::translate(this->translation, velocityVector); this->translation = T; if(this->position.x + radius >= bounds || this->position.x - radius <= -bounds){ velocityVector = glm::vec3(-velocityVector.x, velocityVector.y, velocityVector.z); rotationRates = glm::vec3(rotationRates.x, -rotationRates.y, -rotationRates.z); } if(this->position.y + radius >= bounds || this->position.y - radius <= -bounds){ velocityVector = glm::vec3(velocityVector.x, -velocityVector.y, velocityVector.z); rotationRates = glm::vec3(-rotationRates.x, rotationRates.y, -rotationRates.z); } if(this->position.z + radius>= bounds || this->position.z - radius<= -bounds){ velocityVector = glm::vec3(velocityVector.x, velocityVector.y, -velocityVector.z); rotationRates = glm::vec3(-rotationRates.x, -rotationRates.y, rotationRates.z); } glm::mat4 R = glm::rotate(this->rotation, rotationRates.x, glm::vec3(1,0,0)); R = glm::rotate(R, rotationRates.y, glm::vec3(0,1,0)); R = glm::rotate(R, rotationRates.z, glm::vec3(0,0,1)); this->rotation = R; return T*R*S; } else { return this->translation * this->rotation * S; } } void Asteroid::generateAsteroidBase(){ if(this->asteroidPoints.size() == 0){ //We haven't made the base of the asteroid, so we need to createIcosahedronPoints(); createIcosahedronTriangles(); //Now we have the icosahedron, we should make it a bit better though for(int i = 0; i < REFINEMENT_LEVEL; i++){ deformAsteroid(&this->asteroidPoints); refineIcoSphere(); } } } void Asteroid::deformAndTransformBase(){ transformToGL(); vector<GLuint> elements = vector<GLuint>(); for(int i = 0; i < this->asteroidTriangles.size()*3; i++){ elements.push_back(i+this->elementOffset); } this->elements = elements; for(int i = 0; i < this->asteroidGLVertices.size(); i++){ this->colors.push_back(1.0f); this->colors.push_back(1.0f); this->colors.push_back(1.0f); } } void Asteroid::transformToGL(){ for(int i = 0; i < this->asteroidTriangles.size(); i++){ Triangle* tri = &this->asteroidTriangles[i]; tri->recalculateNormal(this->asteroidPoints[tri->p1Index], this->asteroidPoints[tri->p2Index], this->asteroidPoints[tri->p3Index]); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p1Index].coords.r); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p1Index].coords.g); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p1Index].coords.b); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p2Index].coords.r); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p2Index].coords.g); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p2Index].coords.b); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p3Index].coords.r); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p3Index].coords.g); this->asteroidGLVertices.push_back(this->asteroidPoints[tri->p3Index].coords.b); for(int k = 0; k < 3; k++){ this->asteroidGLNormals.push_back(tri->normal.r); this->asteroidGLNormals.push_back(tri->normal.g); this->asteroidGLNormals.push_back(tri->normal.b); } } } void Asteroid::deformAsteroid(vector<Point>* points){ //srand(time(NULL)); for(int i = 0; i < points->size(); i++){ points->data()[i].moveInRandomDirection(1.0f); } } void Asteroid::createIcosahedronPoints(){ GLfloat reductionFactor = 1; GLfloat baseSize = 1; GLfloat t = (1.0 + sqrt(5.0)) / 2.0; t = reductionFactor * t; baseSize = baseSize * reductionFactor; this->asteroidPoints.push_back(Point(-baseSize, t, 0)); this->asteroidPoints.push_back(Point( baseSize, t, 0)); this->asteroidPoints.push_back(Point(-baseSize, -t, 0)); this->asteroidPoints.push_back(Point( baseSize, -t, 0)); this->asteroidPoints.push_back(Point( 0, -baseSize, t)); this->asteroidPoints.push_back(Point( 0, baseSize, t)); this->asteroidPoints.push_back(Point( 0, -baseSize, -t)); this->asteroidPoints.push_back(Point( 0, baseSize, -t)); this->asteroidPoints.push_back(Point( t, 0, -baseSize)); this->asteroidPoints.push_back(Point( t, 0, baseSize)); this->asteroidPoints.push_back(Point(-t, 0, -baseSize)); this->asteroidPoints.push_back(Point(-t, 0, baseSize)); } void Asteroid::createIcosahedronTriangles(){ this->asteroidTriangles.push_back(Triangle( 0, 11, 5)); this->asteroidTriangles.push_back(Triangle( 0, 5, 1)); this->asteroidTriangles.push_back(Triangle( 0, 1, 7)); this->asteroidTriangles.push_back(Triangle( 0, 7, 10)); this->asteroidTriangles.push_back(Triangle( 0, 10, 11)); this->asteroidTriangles.push_back(Triangle( 1, 5, 9)); this->asteroidTriangles.push_back(Triangle( 5, 11, 4)); this->asteroidTriangles.push_back(Triangle(11, 10, 2)); this->asteroidTriangles.push_back(Triangle(10, 7, 6)); this->asteroidTriangles.push_back(Triangle( 7, 1, 8)); this->asteroidTriangles.push_back(Triangle( 3, 9, 4)); this->asteroidTriangles.push_back(Triangle( 3, 4, 2)); this->asteroidTriangles.push_back(Triangle( 3, 2, 6)); this->asteroidTriangles.push_back(Triangle( 3, 6, 8)); this->asteroidTriangles.push_back(Triangle( 3, 8, 9)); this->asteroidTriangles.push_back(Triangle( 4, 9, 5)); this->asteroidTriangles.push_back(Triangle( 2, 4, 11)); this->asteroidTriangles.push_back(Triangle( 6, 2, 10)); this->asteroidTriangles.push_back(Triangle( 8, 6, 7)); this->asteroidTriangles.push_back(Triangle( 9, 8, 1)); } int Asteroid::calculateMiddlePoint(int p1, int p2, vector<Point>* points){ bool firstSmaller = p1 < p2; int64_t smallerIndex = firstSmaller ? p1 : p2; int64_t greaterIndex = firstSmaller ? p2 : p1; int64_t key = (smallerIndex << 32) + greaterIndex; map<int64_t, int>::iterator iter = middlePointCache.find(key); if(iter != middlePointCache.end()){ //We found the element return iter->second; } Point* first = &((*points)[p1]); Point* second = &((*points)[p2]); Point middlePoint = Point((first->coords.r + second->coords.r)/2.0, (first->coords.g + second->coords.g)/2.0, (first->coords.b + second->coords.b)/2.0); int index = affixVertex(middlePoint, *first, points); middlePointCache.insert(make_pair(key, index)); return index; } int Asteroid::affixVertex(Point middlePoint, Point derpPoint, vector<Point>* pointsVector){ double derpLength = sqrt(derpPoint.coords.r*derpPoint.coords.r + derpPoint.coords.g*derpPoint.coords.g + derpPoint.coords.b*derpPoint.coords.b); double length = sqrt(middlePoint.coords.r*middlePoint.coords.r + middlePoint.coords.g*middlePoint.coords.g + middlePoint.coords.b*middlePoint.coords.b); double ration = derpLength / length; //ration = 1 / length; //length = length/2; (*pointsVector).push_back(Point(middlePoint.coords.r * ration, middlePoint.coords.g * ration, middlePoint.coords.b * ration)); return (*pointsVector).size()-1; } void Asteroid::refineIcoSphere(){ vector<Triangle> refined = vector<Triangle>(); for(int i = 0; i < this->asteroidTriangles.size(); i++){ Triangle tri = this->asteroidTriangles[i]; int a = calculateMiddlePoint(tri.p1Index, tri.p2Index, &this->asteroidPoints); int b = calculateMiddlePoint(tri.p2Index, tri.p3Index, &this->asteroidPoints); int c = calculateMiddlePoint(tri.p3Index, tri.p1Index, &this->asteroidPoints); refined.push_back(Triangle(tri.p1Index, a, c)); refined.push_back(Triangle(tri.p2Index, b, a)); refined.push_back(Triangle(tri.p3Index, c, b)); refined.push_back(Triangle(a, b, c)); } this->asteroidTriangles = refined; } void Asteroid::calculateDeformedResultantRadius(){ GLfloat maxRadius = BASE_RADIUS; for(int i = 0; i < this->asteroidPoints.size(); i++){ Point p = this->asteroidPoints.data()[i]; GLfloat currentRadius = sqrt(p.coords.r*p.coords.r + p.coords.g*p.coords.g + p.coords.b*p.coords.g); if(currentRadius > maxRadius){ maxRadius = currentRadius; } } this->deformedResultantRadius = maxRadius; }
10,369
4,258
#include <assert.h> #include <memory.h> #include <stdio.h> #include <algorithm> #include <vector> #include <string> using namespace std; struct Node; typedef Node Column; struct Node { Node* left; Node* right; Node* up; Node* down; Column* col; int col_idx; const char* name; int size; }; const int kMaxNodes = 25 * 2 * 5 * 2; const int kMaxColumns = 5 * 2 * 5; struct Dance { Column* root_; int* inout_; Column* columns_[100]; vector<Node*> stack_; Node nodes_[kMaxNodes]; int cur_node_; int cnt_; Column* new_column(int n = 0) { assert(cur_node_ < kMaxNodes); Column* c = &nodes_[cur_node_++]; memset(c, 0, sizeof(Column)); c->left = c; c->right = c; c->up = c; c->down = c; c->col = c; c->col_idx = n; return c; } void append_column(int n) { assert(columns_[n] == NULL); Column* c = new_column(n); put_left(root_, c); columns_[n] = c; } Node* new_row(int col) { assert(columns_[col] != NULL); assert(cur_node_ < kMaxNodes); Node* r = &nodes_[cur_node_++]; memset(r, 0, sizeof(Node)); r->left = r; r->right = r; r->up = r; r->down = r; r->col_idx = col; r->col = columns_[col]; put_up(r->col, r); return r; } Dance() : inout_(NULL), cur_node_(0), cnt_(0) { stack_.reserve(100); root_ = new_column(); root_->left = root_->right = root_; memset(columns_, 0, sizeof(columns_)); setup(); } Column* get_min_column() { Column* c = root_->right; int min_size = c->size; if (min_size > 1) { for (Column* cc = c->right; cc != root_; cc = cc->right) { if (min_size > cc->size) { c = cc; min_size = cc->size; if (min_size <= 1) break; } } } return c; } void cover(Column* c) { c->right->left = c->left; c->left->right = c->right; for (Node* row = c->down; row != c; row = row->down) { for (Node* j = row->right; j != row; j = j->right) { j->down->up = j->up; j->up->down = j->down; j->col->size--; } } } void uncover(Column* c) { for (Node* row = c->up; row != c; row = row->up) { for (Node* j = row->left; j != row; j = j->left) { j->col->size++; j->down->up = j; j->up->down = j; } } c->right->left = c; c->left->right = c; } void put_left(Column* old, Column* nnew) { nnew->left = old->left; nnew->right = old; old->left->right = nnew; old->left = nnew; } void put_up(Column* old, Node* nnew) { nnew->up = old->up; nnew->down = old; old->up->down = nnew; old->up = nnew; old->size++; nnew->col = old; } bool solve() { if (root_->left == root_) { printf("found %d '0123456789|0123456789|0123456789|0123456789|0123456789|'\n", ++cnt_); for (size_t i = 0; i < stack_.size(); ++i) { Node* n = stack_[i]; printf(" node = '%s'\n", n->name); } return true; } Column* const col = get_min_column(); cover(col); for (Node* row = col->down; row != col; row = row->down) { stack_.push_back(row); for (Node* j = row->right; j != row; j = j->right) { cover(j->col); } if (solve()) { // return true; } stack_.pop_back(); for (Node* j = row->left; j != row; j = j->left) { uncover(j->col); } } uncover(col); return false; } void setup() { for (int i = 0; i < 5 * 2 * 5; ++i) { append_column(i); } const char* image[] = { // Nation | Color | Drink | Pet | Cigar // 5 - Eng 5 - Red 5 - Tea 5 - Dog 5 - Pall Mall // 6 - Swe 6 - Green 6 - Cof 6 - Bird 6 - Dunhill // 7 - Dan 7 - Yellow 7 - Milk 7 - Horse 7 - Blends // 8 - Nor 8 - Blue 8 - Beer 8 - Cat 8 - Blue Master // 9 - Gem 9 - White 9 - Water 9 - 9 - Prince // 0123456789|0123456789|0123456789|0123456789|0123456789|0123456789| // "1 1 | | | | |", // "1 1 | | | | |", // "1 1 | | | | |", "1 1 | 1 1 | | | |", // "1 1| | | | |", " 1 1 | 1 1 | | | |", " 1 1 | | | 1 1 | |", " 1 1 | | 1 1 | | |", " 1 1 | | | | |", " 1 1| | | | 1 1|", " 1 1 | 1 1 | | | |", " 1 1 | | | 1 1 | |", " 1 1 | | 1 1 | | |", " 1 1 | | | | |", " 1 1| | | | 1 1|", " 1 1 | 1 1 | | | |", " 1 1 | | | 1 1 | |", " 1 1 | | 1 1 | | |", " 1 1 | | | | |", " 1 1| | | | 1 1|", " 11 | 11 | | | |", " 1 1 | | | 11 | |", " 1 1 | | 11 | | |", " 1 1 | | | | |", " 1 1| | | | 1 1|", " |1 1 | | | |", " |11 1 1|1 1 | | |", " |1 1 | | 1 1 |1 1 |", " |1 1 | | | |", " |1 1| | | |", " | 1 1 | | | |", " | 11 1 1| 1 1 | | |", " | 1 1 | |1 | 1 1 |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | | |", " | 1 1| | | |", " | 1 1 | | | |", " | 11 1 1| 1 1 | | |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | | |", " | 1 1| | | |", " | 1 1 | | | |", " | 11 1 1| 1 1 | | |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | | |", " | 1 1| | | |", " | 11 | | | |", // " | 1 1 | 1 1 | | |", " | 1 1 | | 1 1 | 1 1 |", " | 1 1 | | | |", " | 1 1| | | |", " | |1 1 | | |", " | |1 1 | | |", // " | |1 1 | | |", " | |1 1 | |1 1 |", " | |1 1| | |", " | | 1 1 | | |", " | | 1 1 | | |", // " | | 1 1 | | |", " | | 1 1 | | 1 1 |", " | | 1 1| | |", " | | 1 1 | | |", " | | 1 1 | | |", " | | 1 1 | | |", " | | 1 1 | | |", " | | 1 1| | |", " | | 1 1 | | |", " | | 1 1 | | |", // " | | 1 1 | | |", " | | 1 1 | | 1 1 |", " | | 1 1| | |", " | | 11 | | |", " | | 1 1 | | |", // " | | 1 1 | | |", " | | 1 1 | | 1 1 |", " | | 1 1| | |", " | | |1 1 | |", " | | |1 1 |1 1 |", " | | |1 1 | |", " | | |1 1 | 1 1 |", " | | |1 1| |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1 | |", " | | | 1 1 |1 1 |", " | | | 1 1 | 1 1 |", " | | | 1 1| |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1 | 1 1 |", " | | | 1 1| |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1 | 1 1 |", " | | | 1 1| |", " | | | 11 | |", " | | | 1 1 | 11 |", " | | | 1 1 | |", " | | | 1 1 | 1 1 |", " | | | 1 1| |", " | | | |1 1 |", " | | | |1 1 |", " | | | |1 1 |", " | | | |1 1 |", " | | | |1 1|", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1|", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1|", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1|", " | | | | 11 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1 |", " | | | | 1 1|", NULL }; for (int line = 0; image[line] != NULL; ++line) { std::string thisLine(image[line]); std::string::iterator it = std::remove(thisLine.begin(), thisLine.end(), '|'); thisLine.erase(it, thisLine.end()); const char* row = thisLine.c_str(); const char* first = strchr(row, '1'); assert(first != NULL); Node* n0 = new_row(first - row); n0->name = image[line]; printf("\n%d: %d", line, first - row); const char* next = strchr(first+1, '1'); while (next) { Node* n = new_row(next - row); n->name = image[line]; printf(", %d", next - row); put_left(n0, n); next = strchr(next+1, '1'); } } printf("\n"); } }; int main() { Dance d; d.solve(); }
13,440
4,514
#include <iostream> #include <stdexcept> #include <string> using namespace std; class OwnException: public exception{ //class derived from exception private: string a; //declaring string public: OwnException(){ a = "Default case exception"; //when default thsi is printed } OwnException(const string& s){ this->a = a; } virtual const char* what() const throw(){ //overwriting what() return "OwnException"; } }; void types(int n){ switch(n){ case 1: //when parameter is 1 a is thrown throw 'a'; break; case 2: //when parameter is 2, 12 is thrown throw 12; break; case 3: //when parameter is 3, bool is true throw true; break; default: //default throw new OwnException; } return; } int main(){ try{ types(1); //try with parameter 1 } catch(char ch){ cerr<<"Exception caught in main: "<<ch<<endl; } try{ types(2); //try with parameter 2 } catch(int i){ cerr<<"Exception caught in main: "<<i<<endl; } try{ types(3); //try with parameter 3 } catch(bool t){ cerr<<"Exception caught in main: "<<t<<endl; } try{ types(4); //try with parameter 4 } catch(OwnException* m){ cerr<<"Exception caught in main: "<<m->what()<<endl; } return 1; }
1,411
461
/* * adds pose information given by pose_000x.txt into cloud_000x.pcd files (old dataset structure) * now we can use pcl_viewer *.pcd to show all point clouds in common coordinate system * * Created on: Dec 04, 2014 * Author: Thomas Faeulhammer * */ #include <v4r/io/filesystem.h> #include <v4r/io/eigen.h> #include <v4r/common/faat_3d_rec_framework_defines.h> #include <v4r/common/pcl_utils.h> #include <pcl/common/transforms.h> #include <pcl/console/parse.h> #include <pcl/io/pcd_io.h> #include <iostream> #include <sstream> #include <boost/program_options.hpp> #include <glog/logging.h> namespace po = boost::program_options; typedef pcl::PointXYZRGB PointT; int main (int argc, char ** argv) { std::string input_dir, out_dir = "/tmp/clouds_with_pose/"; std::string cloud_prefix = "cloud_", pose_prefix = "pose_", indices_prefix = "object_indices_"; bool invert_pose = false; bool use_indices = false; po::options_description desc("Save camera pose given by seperate pose file directly into header of .pcd file\n======================================\n**Allowed options"); desc.add_options() ("help,h", "produce help message") ("input_dir,i", po::value<std::string>(&input_dir)->required(), "directory containing both .pcd and pose files") ("output_dir,o", po::value<std::string>(&out_dir)->default_value(out_dir), "output directory") ("use_indices,u", po::bool_switch(&use_indices), "if true, uses indices") ("invert_pose,t", po::bool_switch(&invert_pose), "if true, takes the inverse of the pose file (e.g. required for Willow Dataset)") ("cloud_prefix,c", po::value<std::string>(&cloud_prefix)->default_value(cloud_prefix)->implicit_value(""), "prefix of cloud names") ("pose_prefix,p", po::value<std::string>(&pose_prefix)->default_value(pose_prefix), "prefix of camera pose names (e.g. transformation_)") ("indices_prefix,d", po::value<std::string>(&indices_prefix)->default_value(indices_prefix), "prefix of object indices names") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); if (vm.count("help")) { std::cout << desc << std::endl; return false; } try { po::notify(vm); } catch(std::exception& e) { std::cerr << "Error: " << e.what() << std::endl << std::endl << desc << std::endl; return false; } std::vector< std::string> sub_folder_names = v4r::io::getFoldersInDirectory( input_dir ); if( sub_folder_names.empty() ) sub_folder_names.push_back(""); for (const std::string &sub_folder : sub_folder_names) { const std::string path_extended = input_dir + "/" + sub_folder; std::cout << "Processing all point clouds in folder " << path_extended; // const std::string search_pattern = ".*." + cloud_prefix + ".*.pcd"; const std::string search_pattern = ".*.pcd"; std::vector < std::string > cloud_files = v4r::io::getFilesInDirectory (path_extended, search_pattern, true); for (const std::string &cloud_file : cloud_files) { const std::string full_path = path_extended + "/" + cloud_file; const std::string out_fn = out_dir + "/" + sub_folder + "/" + cloud_file; // Loading file and corresponding indices file (if it exists) pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>); pcl::io::loadPCDFile (full_path, *cloud); if(use_indices) { // Check if indices file exist std::string indices_filename( cloud_file ); boost::replace_first (indices_filename, cloud_prefix, indices_prefix); if( v4r::io::existsFile( path_extended+"/"+indices_filename ) ) { pcl::PointCloud<IndexPoint> obj_indices_cloud; pcl::io::loadPCDFile(path_extended+"/"+indices_filename, obj_indices_cloud); pcl::PointIndices indices; indices.indices.resize(obj_indices_cloud.points.size()); for(size_t kk=0; kk < obj_indices_cloud.points.size(); kk++) indices.indices[kk] = obj_indices_cloud.points[kk].idx; pcl::copyPointCloud(*cloud, indices, *cloud); } else { boost::replace_last( indices_filename, ".pcd", ".txt"); if( v4r::io::existsFile( path_extended+"/"+indices_filename ) ) { std::vector<int> indices; int idx_tmp; std::ifstream mask_f( path_extended+"/"+indices_filename ); while (mask_f >> idx_tmp) indices.push_back(idx_tmp); mask_f.close(); pcl::copyPointCloud(*cloud, indices, *cloud); } else { std::cerr << "Indices file " << path_extended << "/" << indices_filename << " does not exist." << std::endl; } } } // Check if pose file exist std::string pose_fn( cloud_file ); boost::replace_first (pose_fn, cloud_prefix, pose_prefix); boost::replace_last (pose_fn, ".pcd", ".txt"); const std::string full_pose_path = input_dir + pose_fn; if( v4r::io::existsFile( full_pose_path ) ) { Eigen::Matrix4f global_trans = v4r::io::readMatrixFromFile(full_pose_path); if(invert_pose) global_trans = global_trans.inverse(); v4r::setCloudPose(global_trans, *cloud); v4r::io::createDirForFileIfNotExist(out_fn); pcl::io::savePCDFileBinary(out_fn, *cloud); } else std::cerr << "Pose file " << full_pose_path << " does not exist." << std::endl; } } }
6,137
1,875
#include <iostream> #include <stdlib.h> #include <fstream> #include <string> #include <sstream> #include <vector> #include <queue> using namespace std; struct Node { int key; // Key int h; // Height attribute. EVERY function must leave h correct for all nodes. Node* left; // Left child Node* right; // Right child Node* p; // Parent Node(int k) // Constructor to create a new node with key k { key = k; clear(); } void clear() // Reset attributes, detach from any tree { left = right = p = NULL; h = -1; } }; struct Tree { Node* root; // Root node. Has NIL parent Node* NIL; // NIL is the sentinel Tree() // Constructor to create an empty tree, with a newly allocated NIL node { NIL = new Node(0); // Create a fresh node and designate it to be the NIL sentinel. root = NIL; root->p = root->left = root->right = NIL; } // Helper functions (you may wish to add more) void LEFT_ROTATE(Node*); // Rotate left void RIGHT_ROTATE(Node*); // Rotate right void HEIGHT_UP(Node*); // Helper function for ROTATE. We assume some leaf has been adjusted, and the heights have been recalculated up to x. We must correct the height of x and all its ancestors. void BALANCE_UP(Node*); // Given a node with correct height and balance, walk up to the root, correcting the height and performing BALANCE at each level. Node* GET_MIN(Node*); // Find minimum (left most) vertex in non-empty subtree void REPLACE(Node*, Node*, bool); // Assignment functions void BALANCE(Node*); // Balance subtree after insert or delete void AVL_INSERT(Node*, Node*); // Insert node into subtree. If tree is empty, give NIL as first parameter. void AVL_DELETE(Node*, Node*); // Delete node from tree Node* SEARCH(Node*, int); // Search for a key in subtree, return node if found, else NIL // IO functions string toString(); // Produces a string, representing your tree in the array format described in (d) void write(ofstream&, Node*); // Writes tree in special DOT format required for use of GraphViz void display(string); // Produce image of tree, using Graphviz (need to install it first) // Overloaded public functions Node* SEARCH(int k) { return SEARCH(root, k); } void AVL_INSERT(int k) { Node* z = new Node(k); AVL_INSERT(root, z); } void AVL_DELETE(int k) { Node* z = SEARCH(root, k); if(z != NIL) AVL_DELETE(root, z); } }; Node* Tree::SEARCH(Node* x, int k) { if(x == NIL) return NIL; // k not in tree if(x->key == k) return x; else if(k < x->key) return SEARCH(x->left, k); else return SEARCH(x->right, k); } void Tree::HEIGHT_UP(Node* x) // corrects height upwards { if(x != NIL) // haven't gone past the root yet { if(x->h == max(x->left->h, x->right->h)+1) return; // x is already correct. Given the context of this function, we can safely assume then that all ancestors are correct. So don't waste extra time. x->h = max(x->left->h, x->right->h)+1; HEIGHT_UP(x->p); } } void Tree::BALANCE_UP(Node* x) // performs balance on each ancestor, upwards { if(x != NIL) // haven't gone past the root yet { Node* parent = x->p; BALANCE(x); // rebalance subtree rooted at x BALANCE_UP(parent); // continue up the ladder } } void Tree::LEFT_ROTATE(Node* x) { Node* y = x->right; x->right = y->left; if(y->left != NIL) y->left->p = x; y->p = x->p; if(x->p == NIL) root = y; else if(x == x->p->left) x->p->left = y; else x->p->right = y; y->left = x; x->p = y; // But because we moved x and y, the h attribute for x and y might now be wrong! Let's recalculate them to make sure HEIGHT_UP(x); } void Tree::RIGHT_ROTATE(Node* x) { Node* y = x->left; x->left = y->right; if(y->right != NIL) y->right->p = x; y->p = x->p; if(x->p == NIL) root = y; else if(x == x->p->left) x->p->left = y; else x->p->right = y; y->right = x; x->p = y; // But because we moved x and y, the h attribute for x, y and ancestors might now be wrong! Let's recalculate them to make sure HEIGHT_UP(x); } Node* Tree::GET_MIN(Node* x) { if(x->left == NIL) return x; else return GET_MIN(x->left); // recurse down to the left until there is no left child } void Tree::REPLACE(Node* x, Node* z, bool keepkids) // set keepkids to true to let z keep its children { if(z != NIL) z->p = x->p; if(!keepkids) { // copy attributes from x to z z->left = x->left; z->right = x->right; z->h = x->h; // give x's children to z if(x->left != NIL) x->left->p = z; if(x->right != NIL) x->right->p = z; } // direct x's parent to z if(x->p == NIL) // x is root root = z; else // x has a parent { if(x->p->right == x) // x is a right child x->p->right = z; else // x is a left child x->p->left = z; if(keepkids) HEIGHT_UP(x->p); // recalculate heights above z } // clear x's attributes x->clear(); } void Tree::BALANCE(Node* x) { if(x->left->h > x->right->h + 1) { if(x->left->right->h > x->left->left->h) LEFT_ROTATE(x->left); RIGHT_ROTATE(x); } if(x->right->h > x->left->h + 1) { if(x->right->left->h > x->right->right->h) RIGHT_ROTATE(x->right); LEFT_ROTATE(x); } HEIGHT_UP(x); } void Tree::AVL_INSERT(Node* x, Node* z) { if(root == NIL) { root = z; z->p = NIL; z->left = NIL; z->right = NIL; z->h = 0; return; } if(z->key < x->key) // insert on the left branch { if(x->left == NIL) // found an empty space { x->left = z; z->left = NIL; z->right = NIL; z->h = 0; z->p = x; } else AVL_INSERT(x->left, z); // recurse on left branch } else // insert on the right branch { if(x->right == NIL) // found an empty space { x->right = z; z->left = NIL; z->right = NIL; z->h = 0; z->p = x; } else AVL_INSERT(x->right, z); // recurse on right branch } x->h = max(x->left->h, x->right->h) + 1; // correct height BALANCE(x); // balance at this ancestor } void Tree::AVL_DELETE(Node* x, Node* z) { if(z->left == NIL && z->right == NIL) // z is a leaf { Node* parent = z->p; REPLACE(z, NIL, true); // replace z with NIL BALANCE_UP(parent); } else if(z->left == NIL) // z has no left child { Node* parent = z->p; REPLACE(z, z->right, true); // replace z with its child subtree BALANCE_UP(parent); } else if(z->right == NIL) // z has no right child { Node* parent = z->p; REPLACE(z, z->left, true); // replace z with its child subtree BALANCE_UP(parent); } else { Node* successor = GET_MIN(z->right); // find successor in right branch Node* dummy = new Node(successor->key); // make a clone of the successor //dummy->data = successor->data; // copy data to clone (only if you are using data) REPLACE(successor, dummy, false); // replace successor with clone REPLACE(z, successor, false); // replace z with successor AVL_DELETE(x, dummy); // finally delete the clone } } string Tree::toString() { // Your code here // An empty tree should just return the string "NIL" if (root == NIL) return "NIL"; int size = (1 << (root->h + 1))-1; string result; queue<Node*> q; q.push(root); // Expand nodes in tree, row by row, including NIL nodes for(int i = 0; i < size; i++) { Node* node = q.front(); q.pop(); if(node == NIL) result += "NIL "; else result += (to_string(node->key) + " "); q.push(node->left); q.push(node->right); } // Delete extra whitespace char at end of string return result.substr(0, result.length()-1); }; void Tree::write(ofstream &filestream, Node* x) { // Write the tree in DOT language to filestream, required for Graphviz if(x != NIL) { if(x->left != NIL) filestream << x->key << " -> " << x->left->key << '\n'; else filestream << "null" << x->key << "l [shape=point];\n" << x->key << " -> " << "null" << x->key << "l\n"; if(x->right != NIL) filestream << x->key << " -> " << x->right->key << '\n'; else filestream << "null" << x->key << "r [shape=point];\n" << x->key << " -> " << "null" << x->key << "r\n"; write(filestream, x->left); write(filestream, x->right); } } void Tree::display(string filename = "tree") { // Creates a PNG diagram of the tree return; // install Graphviz on your machine from http://www.graphviz.org/, then comment out this line ofstream myfile(filename + ".txt"); if (myfile.is_open()) { myfile << "digraph G {\n"; myfile << "graph [ordering=\"out\"]\n"; write(myfile, root); myfile << "}\n"; myfile.close(); } else cout << "Unable to open file"; string s1("\"\"C:\\Program Files (x86)\\Graphviz2.38\\bin\\dot.exe\" -Tpng -o \"C:\\Users\\Mencella\\Documents\\DS Assignment 2\\AVL_tree\\AVL_tree\\"); // change these filepaths to match your graphviz installation location, and your C++ project location string s2(".png\" "); string s3(".txt\""); string args = s1 + filename + s2 + filename + s3; system(args.c_str()); } bool IS_AVL(Node* x) { if(x->h == -1) // i.e. x is NIL return true; if(abs(x->left->h - x->right->h) <= 1 && IS_AVL(x->left) && IS_AVL(x->right)) return true; return false; } int main() { Tree* T = new Tree(); ifstream input("input.txt", ios::in); ofstream output("output.txt", ios::out); string line; while(getline(input, line)) { // Extract the pair (command, key) from the line. E.g. "I 7" istringstream iss(line); string command; iss >> command; int key; iss >> key; // Carry out Insert or Delete command if(command == "I") T->AVL_INSERT(key); else if(command == "D") T->AVL_DELETE(key); // Verify AVL property if(!IS_AVL(T->root)) { cout << "Error. Tree is not AVL!\n"; cout << "Program terminated due to error. Press enter to exit..."; cin.get(); return 0; } // Convert tree to array format, and write to output output << T->toString() << endl; } // Close files input.close(); output.close(); // Display tree as png file (only if GraphViz is installed) T->display(); cout << "Program terminated. Press enter to exit..."; cin.get(); return 0; }
9,982
4,164
#include "precomp.h" //TODO: Compute post processing effects on GPU void PostProcessing::Vignette(Color renderBuffer[SCRWIDTH][SCRHEIGHT], float2 uv[SCRWIDTH][SCRHEIGHT], float outerRadius, float smoothness, float intensity) { outerRadius = clamp(outerRadius, 0.0f, 1.0f); intensity = clamp(intensity, 0.0f, 1.0f); smoothness = max(0.0001f, smoothness); float innerRadius = outerRadius - smoothness; for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { float2 p = uv[i][j] - .5f; float len = dot(p, p); float vignette = smoothstep(outerRadius, innerRadius, len) * intensity; renderBuffer[i][j] = renderBuffer[i][j] * vignette; } } void PostProcessing::GammaCorrection(Color renderBuffer[SCRWIDTH][SCRHEIGHT], float gamma) { float invGamma = 1 / gamma; for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { float x = pow(renderBuffer[i][j].value.x, invGamma); float y = pow(renderBuffer[i][j].value.y, invGamma); float z = pow(renderBuffer[i][j].value.z, invGamma); renderBuffer[i][j] = float3(x, y, z); } } Color tempBuffer[SCRWIDTH][SCRHEIGHT]; void PostProcessing::ChromaticAberration(Color renderBuffer[SCRWIDTH][SCRHEIGHT], int2 redOffset, int2 greenOffset, int2 blueOffset) { for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { float r = renderBuffer[i - redOffset.x][j - redOffset.y].value.x; float g = renderBuffer[i - greenOffset.x][j - greenOffset.y].value.y; float b = renderBuffer[i - blueOffset.x][j - blueOffset.y].value.z; tempBuffer[i][j] = float3(r, g, b); } for (int i = 0; i < SCRWIDTH; i++) for (int j = 0; j < SCRHEIGHT; j++) { renderBuffer[i][j] = tempBuffer[i][j]; } }
1,704
712
#include "init.h" #include <iostream> #include "../../core/project.h" namespace cli { const char* command_init_string = R"(Usage: repaintbrush init [-f] <directory> Create a new Repaintbrush project. Options: -f, --force Force the creation of a project)"; void command_init_func(ArgChain& args) { ArgBlock block = args.parse(1, false, { {"force", false, 'f'} }); args.assert_finished(); // block.assert_all_args(); fs::path path_base = "."; if (block.size() >= 1) { path_base = block[0]; } auto path_project = path_base / core::rbrush_folder_name; // Create project folder if (fs::exists(path_project)) { std::cout << "Could not create project; project already exists." << std::endl; return; } fs::create_directories(path_project); // Create version file fs::ofstream file_version(path_project / core::rbrush_version_name); file_version << core::version; file_version.close(); // Create project bool do_force = block.has_option("force"); auto project = core::Project::create(path_base, do_force); std::cout << "Successfully created project." << std::endl; } }
1,321
387
/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab: * * Gearmand client and server library. * * Copyright (C) 2011-2012 Data Differential, http://datadifferential.com/ * Copyright (C) 2009 Cory Bennett * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * * The names of its contributors may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ /** * @file * @brief libsqlite3 Queue Storage Definitions */ #include <gear_config.h> #include <libgearman-server/common.h> #include <libgearman-server/plugins/queue/sqlite/queue.h> #include <libgearman-server/plugins/queue/base.h> #include "libgearman-server/plugins/queue/sqlite/instance.hpp" /** Default values. */ #define GEARMAND_QUEUE_SQLITE_DEFAULT_TABLE "gearman_queue" namespace gearmand { namespace plugins { namespace queue { class Sqlite : public gearmand::plugins::Queue { public: Sqlite(); ~Sqlite(); gearmand_error_t initialize(); std::string schema; std::string table; private: bool _store_on_shutdown; }; Sqlite::Sqlite() : Queue("libsqlite3") { command_line_options().add_options() ("libsqlite3-db", boost::program_options::value(&schema), "Database file to use.") ("store-queue-on-shutdown", boost::program_options::bool_switch(&_store_on_shutdown)->default_value(false), "Store queue on shutdown.") ("libsqlite3-table", boost::program_options::value(&table)->default_value(GEARMAND_QUEUE_SQLITE_DEFAULT_TABLE), "Table to use.") ; } Sqlite::~Sqlite() { } gearmand_error_t Sqlite::initialize() { gearmand::queue::Instance* exec_queue= new gearmand::queue::Instance(schema, table); if (exec_queue == NULL) { return GEARMAND_MEMORY_ALLOCATION_FAILURE; } exec_queue->store_on_shutdown(_store_on_shutdown); gearmand_error_t rc; if ((rc= exec_queue->init()) != GEARMAND_SUCCESS) { delete exec_queue; return rc; } gearman_server_set_queue(Gearmand()->server, exec_queue); return rc; } void initialize_sqlite() { static Sqlite local_instance; } } // namespace queue } // namespace plugins } // namespace gearmand
3,455
1,253
/*! * @section LICENSE * * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * @section DESCRIPTION * * */ #include "agent-framework/module/model/endpoint.hpp" #include "agent-framework/module/constants/pnc.hpp" using namespace agent_framework::model; using namespace agent_framework::model::utils; const enums::Component Endpoint::component = enums::Component::Endpoint; const enums::CollectionName Endpoint::collection_name = enums::CollectionName::Endpoints; Endpoint::Endpoint(const std::string& parent_uuid, enums::Component parent_type) : Resource{parent_uuid, parent_type} {} Endpoint::~Endpoint() {} Json::Value Endpoint::to_json() const { Json::Value result; result[literals::Endpoint::PROTOCOL] = get_protocol(); result[literals::Endpoint::IDENTIFIERS] = get_identifiers().to_json(); result[literals::Endpoint::ENTITIES] = get_connected_entities().to_json(); result[literals::Endpoint::COLLECTIONS] = get_collections().to_json(); result[literals::Endpoint::STATUS] = get_status().to_json(); result[literals::Endpoint::OEM] = get_oem().to_json(); return result; } Endpoint Endpoint::from_json(const Json::Value& json) { Endpoint endpoint; endpoint.set_protocol(json[literals::Endpoint::PROTOCOL]); endpoint.set_connected_entities( ConnectedEntities::from_json(json[literals::Endpoint::ENTITIES])); endpoint.set_identifiers( Identifiers::from_json(json[literals::Endpoint::IDENTIFIERS])); endpoint.set_collections( Collections::from_json(json[literals::Endpoint::COLLECTIONS])); endpoint.set_status(attribute::Status::from_json(json[literals::Endpoint::STATUS])); endpoint.set_oem(attribute::Oem::from_json(json[literals::Endpoint::OEM])); return endpoint; } bool Endpoint::has_drive_entity(const std::string& drive_uuid) const { for (const auto& entity : m_connected_entities){ if (drive_uuid == entity.get_entity()) { return true; } } return false; }
2,623
800
//correct solution #include <iostream> #include <cmath> #include <algorithm> using namespace std; int main() { int n, nt; long s = 0, m; cin >> n; int *a = new int[n];// dynamic array allocation long *b = new long[n]; for (int i = 0; i < n; i++) cin >> a[i]; b[0] = a[0]; for (int i = 1; i < n; i++) b[i] = a[i]+b[i-1];// store cumulative values of a for (int i = 0; i < n; i++) { nt = 2 * (n - i); nt = ((int)sqrt(1 + 4 * nt) - 1) / 2; nt = (nt * (nt + 1)) / 2;//find number of terms by ap series sum formula if(i == 0) { m = b[nt-1]; s = m; } else s = b[nt+i-1]-b[i-1];// find sum of the series with the help of cumulative values m = max(m, s);//store maximum sum in m s = 0;//reinitialize sum } cout << m; return 0; }
773
371
/** * Copyright Soramitsu Co., Ltd. 2018 All Rights Reserved. * http://soramitsu.co.jp * * 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 <boost/format.hpp> #include "endpoint.grpc.pb.h" // any gRPC service is required for test #include "main/server_runner.hpp" boost::format address{"0.0.0.0:%d"}; auto port_visitor = iroha::make_visitor( [](iroha::expected::Value<int> x) { return x.value; }, [](iroha::expected::Error<std::string> x) { return 0; }); /** * @given a running ServerRunner * @when another ServerRunner tries to run on the same port without port reuse * @then Result with error is returned */ TEST(ServerRunnerTest, SamePortNoReuse) { ServerRunner first_runner((address % 0).str()); auto first_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); auto result = first_runner.append(first_query_service).run(); auto port = boost::apply_visitor(port_visitor, result); ASSERT_NE(0, port); ServerRunner second_runner((address % port).str(), false); auto second_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); result = second_runner.append(second_query_service).run(); port = boost::apply_visitor(port_visitor, result); ASSERT_EQ(0, port); } /** * @given a running ServerRunner * @when another ServerRunner tries to run on the same port with port reuse * @then Result with port number is returned */ TEST(ServerRunnerTest, SamePortWithReuse) { ServerRunner first_runner((address % 0).str()); auto first_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); auto result = first_runner.append(first_query_service).run(); auto port = boost::apply_visitor(port_visitor, result); ASSERT_NE(0, port); ServerRunner second_runner((address % port).str(), true); auto second_query_service = std::make_shared<iroha::protocol::QueryService_v1::Service>(); result = second_runner.append(second_query_service).run(); port = boost::apply_visitor(port_visitor, result); ASSERT_NE(0, port); }
2,605
827
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "sysdeps.h" #include "adb_trace.h" #include <string> #include <unordered_map> #include <vector> #include <android-base/logging.h> #include <android-base/strings.h> #include "adb.h" #if !ADB_HOST #include <cutils/properties.h> #endif #if !defined(ADB_HOST) && defined(__ANDROID__) const char* adb_device_banner = "device"; static android::base::LogdLogger gLogdLogger; #else const char* adb_device_banner = "host"; #endif void AdbLogger(android::base::LogId id, android::base::LogSeverity severity, const char* tag, const char* file, unsigned int line, const char* message) { android::base::StderrLogger(id, severity, tag, file, line, message); #if !defined(ADB_HOST) && defined(__ANDROID__) gLogdLogger(id, severity, tag, file, line, message); #endif } #if !defined(ADB_HOST) && defined(__ANDROID__) static std::string get_log_file_name() { struct tm now; time_t t; tzset(); time(&t); localtime_r(&t, &now); char timestamp[PATH_MAX]; strftime(timestamp, sizeof(timestamp), "%Y-%m-%d-%H-%M-%S", &now); return android::base::StringPrintf("/data/adb/adb-%s-%d", timestamp, getpid()); } void start_device_log(void) { int fd = unix_open(get_log_file_name().c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0640); if (fd == -1) { return; } // Redirect stdout and stderr to the log file. dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); fprintf(stderr, "--- adb starting (pid %d) ---\n", getpid()); unix_close(fd); } #endif int adb_trace_mask; std::string get_trace_setting_from_env() { const char* setting = getenv("ADB_TRACE"); if (setting == nullptr) { setting = ""; } return std::string(setting); } #if !defined(ADB_HOST) && defined(__ANDROID__) std::string get_trace_setting_from_prop() { char buf[PROPERTY_VALUE_MAX]; property_get("persist.adb.trace_mask", buf, ""); return std::string(buf); } #endif std::string get_trace_setting() { #if !defined(ADB_HOST) && defined(__ANDROID__) return get_trace_setting_from_prop(); #else return get_trace_setting_from_env(); #endif } // Split the space separated list of tags from the trace setting and build the // trace mask from it. note that '1' and 'all' are special cases to enable all // tracing. // // adb's trace setting comes from the ADB_TRACE environment variable, whereas // adbd's comes from the system property persist.adb.trace_mask. static void setup_trace_mask() { const std::string trace_setting = get_trace_setting(); if (trace_setting.empty()) { return; } std::unordered_map<std::string, int> trace_flags = { {"1", 0}, {"all", 0}, {"adb", ADB}, {"sockets", SOCKETS}, {"packets", PACKETS}, {"rwx", RWX}, {"usb", USB}, {"sync", SYNC}, {"sysdeps", SYSDEPS}, {"transport", TRANSPORT}, {"jdwp", JDWP}, {"services", SERVICES}, {"auth", AUTH}, {"fdevent", FDEVENT}, {"shell", SHELL}}; std::vector<std::string> elements = android::base::Split(trace_setting, " "); for (const auto& elem : elements) { const auto& flag = trace_flags.find(elem); if (flag == trace_flags.end()) { LOG(ERROR) << "Unknown trace flag: " << elem; continue; } if (flag->second == 0) { // 0 is used for the special values "1" and "all" that enable all // tracing. adb_trace_mask = ~0; return; } else { adb_trace_mask |= 1 << flag->second; } } } void adb_trace_init(char** argv) { #if !defined(ADB_HOST) && defined(__ANDROID__) // Don't open log file if no tracing, since this will block // the crypto unmount of /data if (!get_trace_setting().empty()) { if (unix_isatty(STDOUT_FILENO) == 0) { start_device_log(); } } #endif android::base::InitLogging(argv, &AdbLogger); setup_trace_mask(); VLOG(ADB) << adb_version(); } void adb_trace_enable(AdbTrace trace_tag) { adb_trace_mask |= (1 << trace_tag); }
4,847
1,659
#include "load_library.hpp" #include <fmt/printf.h> #include <zeus/platform.hpp> #if defined(ZEUS_PLATFORM_WINDOWS) # define WIN32_LEAN_AND_MEAN # include <windows.h> #else # include <dlfcn.h> #endif namespace atlas::hlr { #if defined(ZEUS_PLATFORM_WINDOWS) void* load_library_handle(std::string const& library_name) { void* handle = LoadLibrary(library_name.c_str()); if (handle == nullptr) { auto error_code = GetLastError(); fmt::print(stderr, "error: LoadLibrary returned error code {}\n", error_code); } return handle; } void* load_raw_function_ptr(void* handle, std::string const& function_name) { if (handle == nullptr) { fmt::print(stderr, "error: null library handle\n"); return nullptr; } auto hmodule = reinterpret_cast<HMODULE>(handle); FARPROC prog_address = GetProcAddress(hmodule, function_name.c_str()); if (prog_address == nullptr) { auto error_code = GetLastError(); fmt::print(stderr, "error: GetProcAddress returned error code {}\n", error_code); } return prog_address; } void unload_library_handle(void* handle) { auto h = reinterpret_cast<HMODULE>(handle); FreeLibrary(h); } #else void* load_library_handle(std::string const& library_name) { void* handle = dlopen(library_name.c_str(), RTLD_LAZY); if (handle == nullptr) { auto error_message = dlerror(); fmt::print(stderr, "error: in dlopen: {}\n", error_message); } return handle; } void* load_raw_function_ptr(void* handle, std::string const& function_name) { if (handle == nullptr) { fmt::print(stderr, "error: null library handle\n"); return nullptr; } void* prog_address = dlsym(handle, function_name.c_str()); if (prog_address == nullptr) { auto error_message = dlerror(); fmt::print(stderr, "error: in dlsym: {}\n", error_message); } return prog_address; } void unload_library_handle(void* handle) { dlclose(handle); } #endif } // namespace atlas::hlr
2,402
764
/*========================================================================= * * Copyright SINAPSE: Scalable Informatics for Neuroscience, Processing and Software Engineering * The University of Iowa * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkMeshFunction_hxx #define __itkMeshFunction_hxx #include "itkMeshFunction.h" namespace itk { /** * Constructor */ template <typename TInputMesh, typename TOutput> MeshFunction<TInputMesh, TOutput>::MeshFunction() { m_Mesh = nullptr; } /** * Standard "PrintSelf" method */ template <typename TInputMesh, typename TOutput> void MeshFunction<TInputMesh, TOutput>::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "InputMesh: " << m_Mesh.GetPointer() << std::endl; } /** * Initialize by setting the input mesh */ template <typename TInputMesh, typename TOutput> void MeshFunction<TInputMesh, TOutput>::SetInputMesh(const InputMeshType * ptr) { this->m_Mesh = ptr; if (ptr) { // FIXME Add here the point locator... } } /** * Return the input mesh */ template <typename TInputMesh, typename TOutput> const typename MeshFunction<TInputMesh, TOutput>::InputMeshType * MeshFunction<TInputMesh, TOutput>::GetInputMesh() const { return m_Mesh; } } // end namespace itk #endif
1,936
602
#ifndef _CONFIG_CONFIGURATION_H_ #define _CONFIG_CONFIGURATION_H_ #include <tinyxml2.h> #include <chrono> #include <functional> #include <map> #include <memory> #include <mutex> #include <string> #include <vector> namespace gramConfig { class Configurable; class Configuration { public: /** A list of configurations and values type * The first element in the pair is the name of the configuration, with the second element being it's string value */ typedef std::map<std::string, std::string> ValueList; /** A list of configuration names type */ typedef std::vector<std::string> NameList; /** Configuration callback function type */ typedef std::function<void(ValueList)> Callback; /** Constructor * \param xml_filename The name of the XML configuration file */ Configuration(const std::string &xml_filename); /** Destructor */ ~Configuration(); /** Add a new configuration listener * This adds a number of configurations that need to be provided to the supplied callback function when the * configuration is updated * \param configurations NameList of configuration names * \param callback Callback to be called when the configuration changes * \return A shared pointer that can be used as a token. UpdateListeners ensures the token is still in existence * before calling the callback. */ std::shared_ptr<void> AddListener(const NameList &configurations, Callback callback); /** Add a new configuration listener * This adds a number of configurations that need to be provided to the supplied callback function when the * configuration is updated * \param configurations NameList of configuration names * \param callback Reference to a class that implements Configurable * \return A shared pointer that can be used as a token. UpdateListeners ensures the token is still in existence * before calling the callback. */ std::shared_ptr<void> AddListener(const NameList &configurations, Configurable &callback); /** Update all listeners with configuration */ void UpdateListeners(void); /** Get a specific configuration * Request a specific list of configuration values without having to register any listeners * \param required_config NameList of configuration names * \return A ValueList of the requested configuration and their values */ ValueList GetConfiguration(NameList &required_config); /** Continously monitor the configuration file for changes * Sits in a forever loop checking the configuration file for changes and notifying any registered listeners upon * change. This should be called in a separate thread to the main application * \param period_ms Number of milliseconds to wait between file polls */ void MonitorForChanges(unsigned int period_ms); /** Disables the monitoring loop to exit the thread */ void DisableMonitor(void); private: /** List of callbacks containing a weak pointer to the callback function and the relevant NameList of configurations */ std::vector<std::pair<NameList, std::weak_ptr<Callback>>> callbacks_; /** Configuration XML filename */ const std::string config_filename_; /** TinyXML document */ tinyxml2::XMLDocument config_document_; /** File monitor running flag * This flag must be true to keep the file monitor runnign */ bool file_monitor_running_; /** Mutex for locking access to the callbacks_ vector in multithreaded applications */ std::mutex callbacks_mutex_; }; } // namespace gramConfig #endif // _CONFIG_CONFIGURATION_H_
3,574
920
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018 Vladimír Vondruš <mosra@centrum.cz> 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 <numeric> #include <vector> #include <Corrade/Containers/ArrayView.h> #include "Magnum/Magnum.h" #include "Magnum/Math/Algorithms/KahanSum.h" #include "Magnum/Math/Algorithms/Svd.h" #include "Magnum/Math/Packing.h" using namespace Magnum; using namespace Magnum::Math::Literals; int main() { { /* [kahanSum] */ std::vector<Float> data(100000000, 1.0f); Float a = std::accumulate(data.begin(), data.end(), 0.0f); // 1.667e7f Float b = Math::Algorithms::kahanSum(data.begin(), data.end()); // 1.000e8f /* [kahanSum] */ static_cast<void>(a); static_cast<void>(b); } { /* [kahanSum-iterative] */ Containers::ArrayView<UnsignedByte> pixels; Float sum = 0.0f, c = 0.0f; for(UnsignedByte pixel: pixels) { Float value = Math::unpack<Float>(pixel); sum = Math::Algorithms::kahanSum(&value, &value + 1, sum, &c); } /* [kahanSum-iterative] */ } { enum: std::size_t { cols = 3, rows = 4 }; /* [svd] */ Math::RectangularMatrix<cols, rows, Double> m; Math::RectangularMatrix<cols, rows, Double> uPart; Math::Vector<cols, Double> wDiagonal; Math::Matrix<cols, Double> v; std::tie(uPart, wDiagonal, v) = Math::Algorithms::svd(m); // Extend U Math::Matrix<rows, Double> u{Math::ZeroInit}; for(std::size_t i = 0; i != rows; ++i) u[i] = uPart[i]; // Diagonal W Math::RectangularMatrix<cols, rows, Double> w = Math::RectangularMatrix<cols, rows, Double>::fromDiagonal(wDiagonal); // u*w*v.transposed() == m /* [svd] */ static_cast<void>(w); } }
2,710
1,043
/* Copyright (c) 2011 Kevin Wells */ /* OpenGL Pong may be freely redistributed. See license for details. */ #include "input.h" #include "variables.h" #include "quit.h" #include "sdl.h" #include "screen_draw.h" using namespace std; void input_game(){ while(SDL_PollEvent(&event)){ switch(event.type){ case SDL_QUIT: quit_game(); break; } } Uint8 *keystates=SDL_GetKeyState(NULL);/**Get keystates.*/ /**Handle input.*/ if(keystates[SDLK_PAUSE]){ keystates[SDLK_PAUSE]=NULL; //pause(); } if(keystates[SDLK_f]){ keystates[SDLK_f]=NULL; option_frame_rate=!option_frame_rate; } if(keystates[SDLK_m]){ keystates[SDLK_m]=NULL; option_gamemode++; if(option_gamemode>2){ option_gamemode=0; } } if(keystates[SDLK_KP_PLUS]){ keystates[SDLK_KP_PLUS]=NULL; for(int i=0;i<1;i++){ balls.push_back(Ball()); } //if(balls.size()<1000000){ // balls.push_back(Ball()); //} } if(keystates[SDLK_KP_MINUS]){ keystates[SDLK_KP_MINUS]=NULL; if(balls.size()>1){ balls.pop_back(); } } if(option_gamemode==0){/**If we are in demo mode.*/ for(int i=0;i<paddles.size();i++){ paddles.at(i).human=false; } } if(option_gamemode==1){/**If we are in singleplayer mode.*/ paddles.at(0).human=true; paddles.at(1).human=false; } if(option_gamemode==2){/**If we are in humans only mode.*/ for(int i=0;i<paddles.size();i++){ paddles.at(i).human=true; } } for(int i=0;i<paddles.size();i++){ paddles.at(i).handle_input(); } }
1,783
709
#include <seastar/http/httpd.hh> #include <seastar/http/handlers.hh> #include <seastar/http/function_handlers.hh> #include <seastar/http/file_handler.hh> #include <seastar/core/seastar.hh> #include <seastar/core/reactor.hh> // #include "demo.json.hh" #include <seastar/http/api_docs.hh> #include <seastar/core/thread.hh> #include <seastar/core/prometheus.hh> #include <seastar/core/print.hh> #include <seastar/net/inet_address.hh> #include "./stop_signal.hh" namespace bpo = boost::program_options; using namespace seastar; using namespace httpd; class handl : public httpd::handler_base { public: virtual future<std::unique_ptr<reply> > handle(const sstring& path, std::unique_ptr<request> req, std::unique_ptr<reply> rep) { rep->_content = "hello"; rep->done("html"); return make_ready_future<std::unique_ptr<reply>>(std::move(rep)); } }; void set_routes(routes& r) { function_handler* h1 = new function_handler([](const_req req) { return ""; }); // function_handler* h2 = new function_handler([](std::unique_ptr<request> req) { // return make_ready_future<json::json_return_type>("json-future"); // }); r.add(operation_type::GET, url("/healthcheck"), h1); // r.add(operation_type::GET, url("/jf"), h2); // r.add(operation_type::GET, url("/file").remainder("path"), // new directory_handler("/")); // demo_json::hello_world.set(r, [] (const_req req) { // demo_json::my_object obj; // obj.var1 = req.param.at("var1"); // obj.var2 = req.param.at("var2"); // demo_json::ns_hello_world::query_enum v = demo_json::ns_hello_world::str2query_enum(req.query_parameters.at("query_enum")); // // This demonstrate enum conversion // obj.enum_var = v; // return obj; // }); } int main(int ac, char** av) { httpd::http_server_control prometheus_server; prometheus::config pctx; app_template app; app.add_options()("port", bpo::value<uint16_t>()->default_value(8080), "HTTP Server port"); app.add_options()("prometheus_port", bpo::value<uint16_t>()->default_value(9180), "Prometheus port. Set to zero in order to disable."); app.add_options()("prometheus_address", bpo::value<sstring>()->default_value("0.0.0.0"), "Prometheus address"); app.add_options()("prometheus_prefix", bpo::value<sstring>()->default_value("seastar_httpd"), "Prometheus metrics prefix"); return app.run_deprecated(ac, av, [&] { return seastar::async([&] { seastar_apps_lib::stop_signal stop_signal; auto&& config = app.configuration(); httpd::http_server_control prometheus_server; uint16_t pport = config["prometheus_port"].as<uint16_t>(); if (pport) { prometheus::config pctx; net::inet_address prom_addr(config["prometheus_address"].as<sstring>()); pctx.metric_help = "seastar::httpd server statistics"; pctx.prefix = config["prometheus_prefix"].as<sstring>(); std::cout << "starting prometheus API server" << std::endl; prometheus_server.start("prometheus").get(); prometheus::start(prometheus_server, pctx).get(); prometheus_server.listen(socket_address{prom_addr, pport}).handle_exception([prom_addr, pport] (auto ep) { std::cerr << seastar::format("Could not start Prometheus API server on {}:{}: {}\n", prom_addr, pport, ep); return make_exception_future<>(ep); }).get(); } uint16_t port = config["port"].as<uint16_t>(); auto server = new http_server_control(); auto rb = make_shared<api_registry_builder>("apps/httpd/"); server->start().get(); server->set_routes(set_routes).get(); server->set_routes([rb](routes& r){rb->set_api_doc(r);}).get(); server->set_routes([rb](routes& r) {rb->register_function(r, "demo", "hello world application");}).get(); server->listen(port).get(); std::cout << "Seastar HTTP server listening on port " << port << " ...\n"; engine().at_exit([&prometheus_server, server, pport] { return [pport, &prometheus_server] { if (pport) { std::cout << "Stoppping Prometheus server" << std::endl; return prometheus_server.stop(); } return make_ready_future<>(); }().finally([server] { std::cout << "Stoppping HTTP server" << std::endl; return server->stop(); }); }); stop_signal.wait().get(); }); }); }
4,819
1,543
#include "Generated/AB.rfks.h"
30
13
///////////////////////////////////////////////////////////////////////////////////////// // distribution::survival::models::common::importance_sampling::proposals_manager.hpp // // // // Copyright 2009 Erwann Rogard. Distributed under the Boost // // Software License, Version 1.0. (See accompanying file // // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // ///////////////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_IMPORTANCE_SAMPLING_PROPOSALS_MANAGER_HPP_ER_2009 #define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_IMPORTANCE_SAMPLING_PROPOSALS_MANAGER_HPP_ER_2009 #include <boost/typeof/typeof.hpp> #include <boost/fusion/include/make_map.hpp> #include <boost/fusion/include/pair.hpp> #include <boost/statistics/detail/traits/remove_cvref.hpp> #include <boost/statistics/detail/distribution_common/meta/value.hpp> #include <boost/statistics/detail/distribution_common/meta/random/distribution.hpp> #include <boost/statistics/detail/distribution_common/meta/random/generator.hpp> namespace boost { namespace statistics{ namespace detail{ namespace distribution{ namespace survival { namespace importance_sampling{ template<typename D> class proposals_manager{ typedef typename distribution::meta::value<D>::type val_; typedef distribution::meta::random_distribution<D> meta_random_; typedef typename meta_random_::type random_; typedef typename random_::result_type par_value1_; typedef typename statistics::detail::traits::remove_cvref< par_value1_ >::type par_value_; public: proposals_manager(const D& dist):dist_(dist){} proposals_manager(const proposals_manager& that):dist_(that.dist_){} // Tags struct tag{ struct parameter{}; struct log_pdf{}; }; typedef typename tag::parameter tag_par_; typedef typename tag::log_pdf tag_lpdf_; typedef typename boost::fusion::map< boost::fusion::pair<tag_par_,par_value_>, boost::fusion::pair<tag_lpdf_,val_> > proposal_; typedef std::vector<proposal_> proposals_type; // Generate posterior sample const D& distribution()const{ return this->dist_; } template<typename U,typename N> void refresh(U& urng,N n){ BOOST_AUTO( gen, distribution::make_random_generator(urng,this->dist_) ); this->proposals_.clear(); this->proposals_.reserve(n); for(unsigned i = 0; i<n; i++) { par_value_ p = gen(); val_ lpdf = log_unnormalized_pdf(this->dist_,p); this->proposals_.push_back( boost::fusion::make_map<tag_par_,tag_lpdf_>(p,lpdf) ); } } const proposals_type& operator()()const{ return this->proposals_; } private: proposals_type proposals_; D dist_; }; }// importance_sampling }// survival }// distribution }// detail }// statistics }// boost #endif
3,252
1,033
// Copyright (c) 2018 Hongzheng Chen // E-mail: chenhzh37@mail2.sysu.edu.cn // This is the implementation of Entropy-directed scheduling (EDS) algorithm for FPGA high-level synthesis. // This file is the main function of EDS. #include <iostream> #include <fstream> #include <string> #include <cstdlib> #include <chrono> // timing using Clock = std::chrono::high_resolution_clock; #include "graph.h" #include "graph.hpp" using namespace std; // Benchmarks for our experiments can be downloaded at // https://www.ece.ucsb.edu/EXPRESS/benchmark/ const vector<string> dot_file = { "", "hal", "horner_bezier_surf_dfg__12"/*c*/, "arf", "motion_vectors_dfg__7"/*c*/, "ewf", "fir2", "fir1", "h2v2_smooth_downsample_dfg__6", "feedback_points_dfg__7"/*c*/, "collapse_pyr_dfg__113"/*c*/, "cosine1", "cosine2", "write_bmp_header_dfg__7"/*c*/, "interpolate_aux_dfg__12"/*c*/, "matmul_dfg__3"/*c*/, "idctcol_dfg__3"/*c*/, "jpeg_idct_ifast_dfg__5"/*c*/, "jpeg_fdct_islow_dfg__6"/*c*/, "smooth_color_z_triangle_dfg__31"/*c*/, "invert_matrix_general_dfg__3"/*c*/, "dag_500", "dag_1000", "dag_1500" }; // if you need to load from other path, please modify here string path = "./Benchmarks/"; // default constraints for resource-constrained scheduling // these fine-tuned constraints are first presented in the paper below // ----------------------------------------------------------------- // @Article{ // Author = {G. Wang and W. Gong and B. DeRenzi and R. Kastner}, // title = {Ant Colony Optimizations for Resource- and Timing-Constrained Operation Scheduling}, // journal = {IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems (TCAD)}, // year = {2007} // } // ----------------------------------------------------------------- // const vector<map<string,int>> RC = { // {{"MUL",0 }, {"ALU",0 }},/*null*/ // {{"MUL",2 }, {"ALU",1 }},/*1*/ // {{"MUL",2 }, {"ALU",1 }},/*2*/ // {{"MUL",3 }, {"ALU",1 }},/*3*/ // {{"MUL",3 }, {"ALU",4 }},/*4*/ // {{"MUL",1 }, {"ALU",2 }},/*5*/ // {{"MUL",2 }, {"ALU",3 }},/*6*/ // {{"MUL",2 }, {"ALU",3 }},/*7*/ // {{"MUL",1 }, {"ALU",3 }},/*8*/ // {{"MUL",3 }, {"ALU",3 }},/*9*/ // {{"MUL",3 }, {"ALU",5 }},/*10*/ // {{"MUL",4 }, {"ALU",5 }},/*11*/ // {{"MUL",5 }, {"ALU",8 }},/*12*/ // {{"MUL",1 }, {"ALU",9 }},/*13*/ // {{"MUL",9 }, {"ALU",8 }},/*14*/ // {{"MUL",9 }, {"ALU",8 }},/*15*/ // {{"MUL",5 }, {"ALU",6 }},/*16*/ // {{"MUL",10}, {"ALU",9 }},/*17*/ // {{"MUL",5 }, {"ALU",7 }},/*18*/ // {{"MUL",8 }, {"ALU",9 }},/*19*/ // {{"MUL",15}, {"ALU",11}},/*20*/ // {{"MUL",5 }, {"ALU",9 }},/*21*/ // {{"MUL",6 }, {"ALU",12}},/*22*/ // {{"MUL",7 }, {"ALU",13}},/*23*/ // }; // Complex FU library const vector<map<string,int>> RC = { {{"MUL",0 }, {"ALU",0 }},/*null*/ {{"MUL",2 }, {"add",1 },{"sub",1},{"les",1}},/*1*/ {{"MUL",1 }, {"ADD",1 },{"LOD",1},{"STR",1}},/*2*/ {{"MUL",3 }, {"ADD",1 }},/*3*/ {{"MUL",3 }, {"LOD",1 },{"ADD",2},{"STR",1}},/*4*/ {{"MUL",1 }, {"ADD",2 }},/*5*/ {{"MUL",2 }, {"add",1 },{"exp",1},{"imp",2}},/*6*/ {{"MUL",2 }, {"ADD",2 },{"MemR",2},{"MemW",1}},/*7*/ {{"MUL",1 }, {"ADD",2 },{"ASR",1},{"STR",1},{"LOD",1}},/*8*/ {{"MUL",3 }, {"STR",2 },{"LOD",1},{"BGE",1},{"ADD",2}},/*9*/ {{"MUL",3 }, {"ADD",3 },{"SUB",1},{"STR",3},{"LSL",1},{"LOD",3},{"ASR",1}},/*10*/ {{"MUL",4 }, {"imp",6 },{"sub",1},{"exp",2},{"add",2}},/*11*/ {{"MUL",4 }, {"add",1 },{"exp",2},{"imp",2},{"sub",2}},/*12*/ {{"MUL",1 }, {"STR",3 },{"LSR",1},{"LOD",4},{"BNE",1},{"ASR",2},{"AND",2},{"ADD",4}},/*13*/ {{"MUL",9 }, {"ADD",4 },{"SUB",2},{"STR",2},{"LOD",5}},/*14*/ {{"MUL",8 }, {"STR",2 },{"LOD",3},{"ADD",3}},/*15*/ {{"MUL",4 }, {"SUB",2 },{"STR",2},{"LSL",1},{"LOD",2},{"ASR",2},{"ADD",2}},/*16*/ {{"MUL",4 }, {"SUB",1 },{"STR",2},{"LOD",4},{"ASR",1},{"ADD",4}},/*17*/ {{"MUL",4 }, {"SUB",2 },{"STR",2},{"LOD",4},{"ASR",1},{"ADD",4}},/*18*/ {{"MUL",8 }, {"SUB",3 },{"ADD",6},{"LOD",6}},/*19*/ {{"MUL",14}, {"SUB",3 },{"STR",3},{"NEG",2},{"LOD",8},{"ADD",8}},/*20*/ {{"MUL",5 }, {"add",9 }},/*21*/ {{"MUL",6 }, {"add",12}},/*22*/ {{"MUL",7 }, {"add",13}},/*23*/ }; void interactive() { while (1) { cout << "\nPlease enter the file num." << endl; for (int file_num = 1; file_num < dot_file.size(); ++file_num) cout << file_num << ": " << dot_file[file_num] << endl; int file_num; cin >> file_num; cout << "Begin reading dot file..." << endl; ifstream infile(path + dot_file[file_num] + ".dot"); if (infile) cout << "Read in dot file successfully!\n" << endl; else { cout << "Error: No such files!" << endl; return; } graph gp; vector<int> MODE; cout << "\nPlease enter the scheduling mode:" << endl; cout << "Time-constrained(TC):\t0 EDS\t1 IEDS\t2 ILP\t3 FDS\t4 LS" << endl; cout << "Resource-constrained(RC):\t10 EDS\t11 IEDS\t12 ILP\t13 FDS\t 14 LS" << endl; int mode; cin >> mode; MODE.push_back(mode); if (MODE[0] < 10) { double lc; cout << "Please enter the latency factor." << endl; cin >> lc; gp.setLC(lc); } else gp.setMAXRESOURCE(RC.at(file_num)); cout << "\nPlease enter the scheduling order:" << endl; cout << "0. Top-down\t 1.Bottom-up" << endl; cin >> mode; MODE.push_back(mode); gp.setMODE(MODE); gp.readFile(infile); if (MODE[0] == 2) { try{ system("md TC_ILP"); } catch(...){} char str[10]; snprintf(str,sizeof(str),"%.1f",gp.getLC()); ofstream outfile("./TC_ILP/"+dot_file[file_num]+"_"+string(str)+".lp"); gp.generateTC_ILP(outfile); outfile.close(); } else if (MODE[0] == 12) { try{ system("md RC_ILP"); } catch(...){} ofstream outfile("./RC_ILP/"+dot_file[file_num]+".lp"); gp.generateRC_ILP(outfile); outfile.close(); } else gp.mainScheduling(); infile.close(); } } // set these argv from cmd // argv[0] default file path: needn't give // argv[1] scheduling mode: // time-constrained(TC): 0 EDS 1 IEDS 2 ILP 3 FDS 4 LS // resource-constrained(RC): 10 EDS 11 IEDS 12 ILP 13 FDS 14 LS // ****** If the arguments below are not needed, you needn't type anything more. ****** // argv[2] latency factor (LC) or scheduling order // 0 top-down 1 bottom-up void commandline(char *argv[]) { vector<int> MODE; MODE.push_back(stoi(string(argv[1]))); // scheduling mode switch (MODE[0]) { case 0: case 1: case 3: case 4: MODE.push_back(stoi(string(argv[3])));break; case 10: case 11: case 13: case 14: MODE.push_back(stoi(string(argv[2])));break; case 2: MODE.push_back(stoi(string(argv[2])));break; case 12: MODE.push_back(stoi(string(argv[1])));break; default: cout << "Error: Mode wrong!" << endl;break; } for (int file_num = 1; file_num < dot_file.size(); ++file_num) { ifstream infile(path + dot_file[file_num] + ".dot"); if (!infile) { cout << "Error: No such files!" << endl; return; } graph gp; gp.setMODE(MODE); gp.setPRINT(0); gp.readFile(infile); if (MODE[0] >= 10) gp.setMAXRESOURCE(RC.at(file_num)); else gp.setLC(stod(string(argv[2]))); if (MODE[0] == 2) { try{ system("md TC_ILP"); } catch(...){} char str[10]; snprintf(str,sizeof(str),"%.1f",gp.getLC()); ofstream outfile("./TC_ILP/"+dot_file[file_num]+"_"+string(str)+".lp"); gp.generateTC_ILP(outfile); outfile.close(); } else if (MODE[0] == 12) { try{ system("md RC_ILP"); } catch(...){} ofstream outfile("./RC_ILP/"+dot_file[file_num]+".lp"); gp.generateRC_ILP(outfile); outfile.close(); } else { cout << "File # " << file_num << " (" << dot_file[file_num] << ") :" <<endl; gp.mainScheduling(1); } infile.close(); } } int main(int argc,char *argv[]) { if (argc == 1) // interactive interactive(); else // read from cmd commandline(argv); return 0; } // Some abbreviations appear in ExPRESS // 1.MUL // mul: multipy // div: divide // 2.ALU // imp: import // exp: export // MemR: memory read // MemW: memory write // str: store register // les: less // lod: load data into memory? // bge: ? // neg: negetive // add: add // sub: subtract // and: logical and // lsr: logical shift right // asr: arithmetic shift right // bne: Branch if Not Equal
8,236
3,925
/** * Orthanc - A Lightweight, RESTful DICOM Store * Copyright (C) 2012-2016 Sebastien Jodogne, Medical Physics * Department, University Hospital of Liege, Belgium * Copyright (C) 2017-2020 Osimis S.A., Belgium * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/>. **/ #include "../PrecompiledHeaders.h" #include "DicomModification.h" #include "../Compatibility.h" #include "../Logging.h" #include "../OrthancException.h" #include "../SerializationToolbox.h" #include "FromDcmtkBridge.h" #include "ITagVisitor.h" #include <memory> // For std::unique_ptr static const std::string ORTHANC_DEIDENTIFICATION_METHOD_2008 = "Orthanc " ORTHANC_VERSION " - PS 3.15-2008 Table E.1-1"; static const std::string ORTHANC_DEIDENTIFICATION_METHOD_2017c = "Orthanc " ORTHANC_VERSION " - PS 3.15-2017c Table E.1-1 Basic Profile"; namespace Orthanc { class DicomModification::RelationshipsVisitor : public ITagVisitor { private: DicomModification& that_; bool IsEnabled(const DicomTag& tag) const { return (!that_.IsCleared(tag) && !that_.IsRemoved(tag) && !that_.IsReplaced(tag)); } void RemoveIfEnabled(ParsedDicomFile& dicom, const DicomTag& tag) const { if (IsEnabled(tag)) { dicom.Remove(tag); } } public: explicit RelationshipsVisitor(DicomModification& that) : that_(that) { } virtual void VisitNotSupported(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, ValueRepresentation vr) { } virtual void VisitEmptySequence(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag) { } virtual void VisitBinary(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, ValueRepresentation vr, const void* data, size_t size) { } virtual void VisitIntegers(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, ValueRepresentation vr, const std::vector<int64_t>& values) { } virtual void VisitDoubles(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, ValueRepresentation vr, const std::vector<double>& value) { } virtual void VisitAttributes(const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, const std::vector<DicomTag>& value) { } virtual Action VisitString(std::string& newValue, const std::vector<DicomTag>& parentTags, const std::vector<size_t>& parentIndexes, const DicomTag& tag, ValueRepresentation vr, const std::string& value) { if (!IsEnabled(tag)) { return Action_None; } else if (parentTags.size() == 2 && parentTags[0] == DICOM_TAG_REFERENCED_FRAME_OF_REFERENCE_SEQUENCE && parentTags[1] == DICOM_TAG_RT_REFERENCED_STUDY_SEQUENCE && tag == DICOM_TAG_REFERENCED_SOP_INSTANCE_UID) { // in RT-STRUCT, this ReferencedSOPInstanceUID is actually referencing a StudyInstanceUID !! // (observed in many data sets including: https://wiki.cancerimagingarchive.net/display/Public/Lung+CT+Segmentation+Challenge+2017) // tested in test_anonymize_relationships_5 newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Study); return Action_Replace; } else if (tag == DICOM_TAG_FRAME_OF_REFERENCE_UID || tag == DICOM_TAG_REFERENCED_FRAME_OF_REFERENCE_UID || tag == DICOM_TAG_REFERENCED_SOP_INSTANCE_UID || tag == DICOM_TAG_RELATED_FRAME_OF_REFERENCE_UID) { newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Instance); return Action_Replace; } else if (parentTags.size() == 1 && parentTags[0] == DICOM_TAG_CURRENT_REQUESTED_PROCEDURE_EVIDENCE_SEQUENCE && tag == DICOM_TAG_STUDY_INSTANCE_UID) { newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Study); return Action_Replace; } else if (parentTags.size() == 2 && parentTags[0] == DICOM_TAG_CURRENT_REQUESTED_PROCEDURE_EVIDENCE_SEQUENCE && parentTags[1] == DICOM_TAG_REFERENCED_SERIES_SEQUENCE && tag == DICOM_TAG_SERIES_INSTANCE_UID) { newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Series); return Action_Replace; } else if (parentTags.size() == 3 && parentTags[0] == DICOM_TAG_REFERENCED_FRAME_OF_REFERENCE_SEQUENCE && parentTags[1] == DICOM_TAG_RT_REFERENCED_STUDY_SEQUENCE && parentTags[2] == DICOM_TAG_RT_REFERENCED_SERIES_SEQUENCE && tag == DICOM_TAG_SERIES_INSTANCE_UID) { newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Series); return Action_Replace; } else if (parentTags.size() == 1 && parentTags[0] == DICOM_TAG_REFERENCED_SERIES_SEQUENCE && tag == DICOM_TAG_SERIES_INSTANCE_UID) { newValue = that_.MapDicomIdentifier(Toolbox::StripSpaces(value), ResourceType_Series); return Action_Replace; } else { return Action_None; } } void RemoveRelationships(ParsedDicomFile& dicom) const { // Sequences containing the UID relationships RemoveIfEnabled(dicom, DICOM_TAG_REFERENCED_IMAGE_SEQUENCE); RemoveIfEnabled(dicom, DICOM_TAG_SOURCE_IMAGE_SEQUENCE); // Individual tags RemoveIfEnabled(dicom, DICOM_TAG_FRAME_OF_REFERENCE_UID); // The tags below should never occur at the first level of the // hierarchy, but remove them anyway RemoveIfEnabled(dicom, DICOM_TAG_REFERENCED_FRAME_OF_REFERENCE_UID); RemoveIfEnabled(dicom, DICOM_TAG_REFERENCED_SOP_INSTANCE_UID); RemoveIfEnabled(dicom, DICOM_TAG_RELATED_FRAME_OF_REFERENCE_UID); } }; bool DicomModification::CancelReplacement(const DicomTag& tag) { Replacements::iterator it = replacements_.find(tag); if (it != replacements_.end()) { delete it->second; replacements_.erase(it); return true; } else { return false; } } void DicomModification::ReplaceInternal(const DicomTag& tag, const Json::Value& value) { Replacements::iterator it = replacements_.find(tag); if (it != replacements_.end()) { delete it->second; it->second = NULL; // In the case of an exception during the clone it->second = new Json::Value(value); // Clone } else { replacements_[tag] = new Json::Value(value); // Clone } } void DicomModification::ClearReplacements() { for (Replacements::iterator it = replacements_.begin(); it != replacements_.end(); ++it) { delete it->second; } replacements_.clear(); } void DicomModification::MarkNotOrthancAnonymization() { Replacements::iterator it = replacements_.find(DICOM_TAG_DEIDENTIFICATION_METHOD); if (it != replacements_.end() && (it->second->asString() == ORTHANC_DEIDENTIFICATION_METHOD_2008 || it->second->asString() == ORTHANC_DEIDENTIFICATION_METHOD_2017c)) { delete it->second; replacements_.erase(it); } } void DicomModification::RegisterMappedDicomIdentifier(const std::string& original, const std::string& mapped, ResourceType level) { UidMap::const_iterator previous = uidMap_.find(std::make_pair(level, original)); if (previous == uidMap_.end()) { uidMap_.insert(std::make_pair(std::make_pair(level, original), mapped)); } } std::string DicomModification::MapDicomIdentifier(const std::string& original, ResourceType level) { std::string mapped; UidMap::const_iterator previous = uidMap_.find(std::make_pair(level, original)); if (previous == uidMap_.end()) { if (identifierGenerator_ == NULL) { mapped = FromDcmtkBridge::GenerateUniqueIdentifier(level); } else { if (!identifierGenerator_->Apply(mapped, original, level, currentSource_)) { throw OrthancException(ErrorCode_InternalError, "Unable to generate an anonymized ID"); } } uidMap_.insert(std::make_pair(std::make_pair(level, original), mapped)); } else { mapped = previous->second; } return mapped; } void DicomModification::MapDicomTags(ParsedDicomFile& dicom, ResourceType level) { std::unique_ptr<DicomTag> tag; switch (level) { case ResourceType_Study: tag.reset(new DicomTag(DICOM_TAG_STUDY_INSTANCE_UID)); break; case ResourceType_Series: tag.reset(new DicomTag(DICOM_TAG_SERIES_INSTANCE_UID)); break; case ResourceType_Instance: tag.reset(new DicomTag(DICOM_TAG_SOP_INSTANCE_UID)); break; default: throw OrthancException(ErrorCode_InternalError); } std::string original; if (!dicom.GetTagValue(original, *tag)) { original = ""; } std::string mapped = MapDicomIdentifier(Toolbox::StripSpaces(original), level); dicom.Replace(*tag, mapped, false /* don't try and decode data URI scheme for UIDs */, DicomReplaceMode_InsertIfAbsent, privateCreator_); } DicomModification::DicomModification() : removePrivateTags_(false), level_(ResourceType_Instance), allowManualIdentifiers_(true), keepStudyInstanceUid_(false), keepSeriesInstanceUid_(false), keepSopInstanceUid_(false), updateReferencedRelationships_(true), isAnonymization_(false), //privateCreator_("PrivateCreator"), identifierGenerator_(NULL) { } DicomModification::~DicomModification() { ClearReplacements(); } void DicomModification::Keep(const DicomTag& tag) { bool wasRemoved = IsRemoved(tag); bool wasCleared = IsCleared(tag); removals_.erase(tag); clearings_.erase(tag); bool wasReplaced = CancelReplacement(tag); if (tag == DICOM_TAG_STUDY_INSTANCE_UID) { keepStudyInstanceUid_ = true; } else if (tag == DICOM_TAG_SERIES_INSTANCE_UID) { keepSeriesInstanceUid_ = true; } else if (tag == DICOM_TAG_SOP_INSTANCE_UID) { keepSopInstanceUid_ = true; } else if (tag.IsPrivate()) { privateTagsToKeep_.insert(tag); } else if (!wasRemoved && !wasReplaced && !wasCleared) { LOG(WARNING) << "Marking this tag as to be kept has no effect: " << tag.Format(); } MarkNotOrthancAnonymization(); } void DicomModification::Remove(const DicomTag& tag) { removals_.insert(tag); clearings_.erase(tag); CancelReplacement(tag); privateTagsToKeep_.erase(tag); MarkNotOrthancAnonymization(); } void DicomModification::Clear(const DicomTag& tag) { removals_.erase(tag); clearings_.insert(tag); CancelReplacement(tag); privateTagsToKeep_.erase(tag); MarkNotOrthancAnonymization(); } bool DicomModification::IsRemoved(const DicomTag& tag) const { return removals_.find(tag) != removals_.end(); } bool DicomModification::IsCleared(const DicomTag& tag) const { return clearings_.find(tag) != clearings_.end(); } void DicomModification::Replace(const DicomTag& tag, const Json::Value& value, bool safeForAnonymization) { clearings_.erase(tag); removals_.erase(tag); privateTagsToKeep_.erase(tag); ReplaceInternal(tag, value); if (!safeForAnonymization) { MarkNotOrthancAnonymization(); } } bool DicomModification::IsReplaced(const DicomTag& tag) const { return replacements_.find(tag) != replacements_.end(); } const Json::Value& DicomModification::GetReplacement(const DicomTag& tag) const { Replacements::const_iterator it = replacements_.find(tag); if (it == replacements_.end()) { throw OrthancException(ErrorCode_InexistentItem); } else { return *it->second; } } std::string DicomModification::GetReplacementAsString(const DicomTag& tag) const { const Json::Value& json = GetReplacement(tag); if (json.type() != Json::stringValue) { throw OrthancException(ErrorCode_BadParameterType); } else { return json.asString(); } } void DicomModification::SetRemovePrivateTags(bool removed) { removePrivateTags_ = removed; if (!removed) { MarkNotOrthancAnonymization(); } } void DicomModification::SetLevel(ResourceType level) { uidMap_.clear(); level_ = level; if (level != ResourceType_Patient) { MarkNotOrthancAnonymization(); } } void DicomModification::SetupAnonymization2008() { // This is Table E.1-1 from PS 3.15-2008 - DICOM Part 15: Security and System Management Profiles // https://raw.githubusercontent.com/jodogne/dicom-specification/master/2008/08_15pu.pdf removals_.insert(DicomTag(0x0008, 0x0014)); // Instance Creator UID //removals_.insert(DicomTag(0x0008, 0x0018)); // SOP Instance UID => set in Apply() removals_.insert(DicomTag(0x0008, 0x0050)); // Accession Number removals_.insert(DicomTag(0x0008, 0x0080)); // Institution Name removals_.insert(DicomTag(0x0008, 0x0081)); // Institution Address removals_.insert(DicomTag(0x0008, 0x0090)); // Referring Physician's Name removals_.insert(DicomTag(0x0008, 0x0092)); // Referring Physician's Address removals_.insert(DicomTag(0x0008, 0x0094)); // Referring Physician's Telephone Numbers removals_.insert(DicomTag(0x0008, 0x1010)); // Station Name removals_.insert(DicomTag(0x0008, 0x1030)); // Study Description removals_.insert(DicomTag(0x0008, 0x103e)); // Series Description removals_.insert(DicomTag(0x0008, 0x1040)); // Institutional Department Name removals_.insert(DicomTag(0x0008, 0x1048)); // Physician(s) of Record removals_.insert(DicomTag(0x0008, 0x1050)); // Performing Physicians' Name removals_.insert(DicomTag(0x0008, 0x1060)); // Name of Physician(s) Reading Study removals_.insert(DicomTag(0x0008, 0x1070)); // Operators' Name removals_.insert(DicomTag(0x0008, 0x1080)); // Admitting Diagnoses Description //removals_.insert(DicomTag(0x0008, 0x1155)); // Referenced SOP Instance UID => RelationshipsVisitor removals_.insert(DicomTag(0x0008, 0x2111)); // Derivation Description //removals_.insert(DicomTag(0x0010, 0x0010)); // Patient's Name => cf. below (*) //removals_.insert(DicomTag(0x0010, 0x0020)); // Patient ID => cf. below (*) removals_.insert(DicomTag(0x0010, 0x0030)); // Patient's Birth Date removals_.insert(DicomTag(0x0010, 0x0032)); // Patient's Birth Time removals_.insert(DicomTag(0x0010, 0x0040)); // Patient's Sex removals_.insert(DicomTag(0x0010, 0x1000)); // Other Patient Ids removals_.insert(DicomTag(0x0010, 0x1001)); // Other Patient Names removals_.insert(DicomTag(0x0010, 0x1010)); // Patient's Age removals_.insert(DicomTag(0x0010, 0x1020)); // Patient's Size removals_.insert(DicomTag(0x0010, 0x1030)); // Patient's Weight removals_.insert(DicomTag(0x0010, 0x1090)); // Medical Record Locator removals_.insert(DicomTag(0x0010, 0x2160)); // Ethnic Group removals_.insert(DicomTag(0x0010, 0x2180)); // Occupation removals_.insert(DicomTag(0x0010, 0x21b0)); // Additional Patient's History removals_.insert(DicomTag(0x0010, 0x4000)); // Patient Comments removals_.insert(DicomTag(0x0018, 0x1000)); // Device Serial Number removals_.insert(DicomTag(0x0018, 0x1030)); // Protocol Name //removals_.insert(DicomTag(0x0020, 0x000d)); // Study Instance UID => set in Apply() //removals_.insert(DicomTag(0x0020, 0x000e)); // Series Instance UID => set in Apply() removals_.insert(DicomTag(0x0020, 0x0010)); // Study ID //removals_.insert(DicomTag(0x0020, 0x0052)); // Frame of Reference UID => cf. RelationshipsVisitor removals_.insert(DicomTag(0x0020, 0x0200)); // Synchronization Frame of Reference UID removals_.insert(DicomTag(0x0020, 0x4000)); // Image Comments removals_.insert(DicomTag(0x0040, 0x0275)); // Request Attributes Sequence removals_.insert(DicomTag(0x0040, 0xa124)); // UID removals_.insert(DicomTag(0x0040, 0xa730)); // Content Sequence removals_.insert(DicomTag(0x0088, 0x0140)); // Storage Media File-set UID //removals_.insert(DicomTag(0x3006, 0x0024)); // Referenced Frame of Reference UID => RelationshipsVisitor //removals_.insert(DicomTag(0x3006, 0x00c2)); // Related Frame of Reference UID => RelationshipsVisitor // Some more removals (from the experience of DICOM files at the CHU of Liege) removals_.insert(DicomTag(0x0010, 0x1040)); // Patient's Address removals_.insert(DicomTag(0x0032, 0x1032)); // Requesting Physician removals_.insert(DicomTag(0x0010, 0x2154)); // PatientTelephoneNumbers removals_.insert(DicomTag(0x0010, 0x2000)); // Medical Alerts // Set the DeidentificationMethod tag ReplaceInternal(DICOM_TAG_DEIDENTIFICATION_METHOD, ORTHANC_DEIDENTIFICATION_METHOD_2008); } void DicomModification::SetupAnonymization2017c() { /** * This is Table E.1-1 from PS 3.15-2017c (DICOM Part 15: Security * and System Management Profiles), "basic profile" column. It was * generated automatically with the * "../Resources/GenerateAnonymizationProfile.py" script. * https://raw.githubusercontent.com/jodogne/dicom-specification/master/2017c/part15.pdf **/ // TODO: (50xx,xxxx) with rule X // Curve Data // TODO: (60xx,3000) with rule X // Overlay Data // TODO: (60xx,4000) with rule X // Overlay Comments // Tag (0x0008, 0x0018) is set in Apply() /* U */ // SOP Instance UID // Tag (0x0008, 0x1140) => RelationshipsVisitor /* X/Z/U* */ // Referenced Image Sequence // Tag (0x0008, 0x1155) => RelationshipsVisitor /* U */ // Referenced SOP Instance UID // Tag (0x0008, 0x2112) => RelationshipsVisitor /* X/Z/U* */ // Source Image Sequence // Tag (0x0010, 0x0010) is set below (*) /* Z */ // Patient's Name // Tag (0x0010, 0x0020) is set below (*) /* Z */ // Patient ID // Tag (0x0020, 0x000d) is set in Apply() /* U */ // Study Instance UID // Tag (0x0020, 0x000e) is set in Apply() /* U */ // Series Instance UID // Tag (0x0020, 0x0052) => RelationshipsVisitor /* U */ // Frame of Reference UID // Tag (0x3006, 0x0024) => RelationshipsVisitor /* U */ // Referenced Frame of Reference UID // Tag (0x3006, 0x00c2) => RelationshipsVisitor /* U */ // Related Frame of Reference UID clearings_.insert(DicomTag(0x0008, 0x0020)); // Study Date clearings_.insert(DicomTag(0x0008, 0x0023)); /* Z/D */ // Content Date clearings_.insert(DicomTag(0x0008, 0x0030)); // Study Time clearings_.insert(DicomTag(0x0008, 0x0033)); /* Z/D */ // Content Time clearings_.insert(DicomTag(0x0008, 0x0050)); // Accession Number clearings_.insert(DicomTag(0x0008, 0x0090)); // Referring Physician's Name clearings_.insert(DicomTag(0x0008, 0x009c)); // Consulting Physician's Name clearings_.insert(DicomTag(0x0010, 0x0030)); // Patient's Birth Date clearings_.insert(DicomTag(0x0010, 0x0040)); // Patient's Sex clearings_.insert(DicomTag(0x0018, 0x0010)); /* Z/D */ // Contrast Bolus Agent clearings_.insert(DicomTag(0x0020, 0x0010)); // Study ID clearings_.insert(DicomTag(0x0040, 0x1101)); /* D */ // Person Identification Code Sequence clearings_.insert(DicomTag(0x0040, 0x2016)); // Placer Order Number / Imaging Service Request clearings_.insert(DicomTag(0x0040, 0x2017)); // Filler Order Number / Imaging Service Request clearings_.insert(DicomTag(0x0040, 0xa073)); /* D */ // Verifying Observer Sequence clearings_.insert(DicomTag(0x0040, 0xa075)); /* D */ // Verifying Observer Name clearings_.insert(DicomTag(0x0040, 0xa088)); // Verifying Observer Identification Code Sequence clearings_.insert(DicomTag(0x0040, 0xa123)); /* D */ // Person Name clearings_.insert(DicomTag(0x0070, 0x0001)); /* D */ // Graphic Annotation Sequence clearings_.insert(DicomTag(0x0070, 0x0084)); // Content Creator's Name removals_.insert(DicomTag(0x0000, 0x1000)); // Affected SOP Instance UID removals_.insert(DicomTag(0x0000, 0x1001)); /* TODO UID */ // Requested SOP Instance UID removals_.insert(DicomTag(0x0002, 0x0003)); /* TODO UID */ // Media Storage SOP Instance UID removals_.insert(DicomTag(0x0004, 0x1511)); /* TODO UID */ // Referenced SOP Instance UID in File removals_.insert(DicomTag(0x0008, 0x0014)); /* TODO UID */ // Instance Creator UID removals_.insert(DicomTag(0x0008, 0x0015)); // Instance Coercion DateTime removals_.insert(DicomTag(0x0008, 0x0021)); /* X/D */ // Series Date removals_.insert(DicomTag(0x0008, 0x0022)); /* X/Z */ // Acquisition Date removals_.insert(DicomTag(0x0008, 0x0024)); // Overlay Date removals_.insert(DicomTag(0x0008, 0x0025)); // Curve Date removals_.insert(DicomTag(0x0008, 0x002a)); /* X/D */ // Acquisition DateTime removals_.insert(DicomTag(0x0008, 0x0031)); /* X/D */ // Series Time removals_.insert(DicomTag(0x0008, 0x0032)); /* X/Z */ // Acquisition Time removals_.insert(DicomTag(0x0008, 0x0034)); // Overlay Time removals_.insert(DicomTag(0x0008, 0x0035)); // Curve Time removals_.insert(DicomTag(0x0008, 0x0058)); /* TODO UID */ // Failed SOP Instance UID List removals_.insert(DicomTag(0x0008, 0x0080)); /* X/Z/D */ // Institution Name removals_.insert(DicomTag(0x0008, 0x0081)); // Institution Address removals_.insert(DicomTag(0x0008, 0x0082)); /* X/Z/D */ // Institution Code Sequence removals_.insert(DicomTag(0x0008, 0x0092)); // Referring Physician's Address removals_.insert(DicomTag(0x0008, 0x0094)); // Referring Physician's Telephone Numbers removals_.insert(DicomTag(0x0008, 0x0096)); // Referring Physician Identification Sequence removals_.insert(DicomTag(0x0008, 0x009d)); // Consulting Physician Identification Sequence removals_.insert(DicomTag(0x0008, 0x0201)); // Timezone Offset From UTC removals_.insert(DicomTag(0x0008, 0x1010)); /* X/Z/D */ // Station Name removals_.insert(DicomTag(0x0008, 0x1030)); // Study Description removals_.insert(DicomTag(0x0008, 0x103e)); // Series Description removals_.insert(DicomTag(0x0008, 0x1040)); // Institutional Department Name removals_.insert(DicomTag(0x0008, 0x1048)); // Physician(s) of Record removals_.insert(DicomTag(0x0008, 0x1049)); // Physician(s) of Record Identification Sequence removals_.insert(DicomTag(0x0008, 0x1050)); // Performing Physicians' Name removals_.insert(DicomTag(0x0008, 0x1052)); // Performing Physician Identification Sequence removals_.insert(DicomTag(0x0008, 0x1060)); // Name of Physician(s) Reading Study removals_.insert(DicomTag(0x0008, 0x1062)); // Physician(s) Reading Study Identification Sequence removals_.insert(DicomTag(0x0008, 0x1070)); /* X/Z/D */ // Operators' Name removals_.insert(DicomTag(0x0008, 0x1072)); /* X/D */ // Operators' Identification Sequence removals_.insert(DicomTag(0x0008, 0x1080)); // Admitting Diagnoses Description removals_.insert(DicomTag(0x0008, 0x1084)); // Admitting Diagnoses Code Sequence removals_.insert(DicomTag(0x0008, 0x1110)); /* X/Z */ // Referenced Study Sequence removals_.insert(DicomTag(0x0008, 0x1111)); /* X/Z/D */ // Referenced Performed Procedure Step Sequence removals_.insert(DicomTag(0x0008, 0x1120)); // Referenced Patient Sequence removals_.insert(DicomTag(0x0008, 0x1195)); /* TODO UID */ // Transaction UID removals_.insert(DicomTag(0x0008, 0x2111)); // Derivation Description removals_.insert(DicomTag(0x0008, 0x3010)); /* TODO UID */ // Irradiation Event UID removals_.insert(DicomTag(0x0008, 0x4000)); // Identifying Comments removals_.insert(DicomTag(0x0010, 0x0021)); // Issuer of Patient ID removals_.insert(DicomTag(0x0010, 0x0032)); // Patient's Birth Time removals_.insert(DicomTag(0x0010, 0x0050)); // Patient's Insurance Plan Code Sequence removals_.insert(DicomTag(0x0010, 0x0101)); // Patient's Primary Language Code Sequence removals_.insert(DicomTag(0x0010, 0x0102)); // Patient's Primary Language Modifier Code Sequence removals_.insert(DicomTag(0x0010, 0x1000)); // Other Patient IDs removals_.insert(DicomTag(0x0010, 0x1001)); // Other Patient Names removals_.insert(DicomTag(0x0010, 0x1002)); // Other Patient IDs Sequence removals_.insert(DicomTag(0x0010, 0x1005)); // Patient's Birth Name removals_.insert(DicomTag(0x0010, 0x1010)); // Patient's Age removals_.insert(DicomTag(0x0010, 0x1020)); // Patient's Size removals_.insert(DicomTag(0x0010, 0x1030)); // Patient's Weight removals_.insert(DicomTag(0x0010, 0x1040)); // Patient Address removals_.insert(DicomTag(0x0010, 0x1050)); // Insurance Plan Identification removals_.insert(DicomTag(0x0010, 0x1060)); // Patient's Mother's Birth Name removals_.insert(DicomTag(0x0010, 0x1080)); // Military Rank removals_.insert(DicomTag(0x0010, 0x1081)); // Branch of Service removals_.insert(DicomTag(0x0010, 0x1090)); // Medical Record Locator removals_.insert(DicomTag(0x0010, 0x1100)); // Referenced Patient Photo Sequence removals_.insert(DicomTag(0x0010, 0x2000)); // Medical Alerts removals_.insert(DicomTag(0x0010, 0x2110)); // Allergies removals_.insert(DicomTag(0x0010, 0x2150)); // Country of Residence removals_.insert(DicomTag(0x0010, 0x2152)); // Region of Residence removals_.insert(DicomTag(0x0010, 0x2154)); // Patient's Telephone Numbers removals_.insert(DicomTag(0x0010, 0x2155)); // Patient's Telecom Information removals_.insert(DicomTag(0x0010, 0x2160)); // Ethnic Group removals_.insert(DicomTag(0x0010, 0x2180)); // Occupation removals_.insert(DicomTag(0x0010, 0x21a0)); // Smoking Status removals_.insert(DicomTag(0x0010, 0x21b0)); // Additional Patient's History removals_.insert(DicomTag(0x0010, 0x21c0)); // Pregnancy Status removals_.insert(DicomTag(0x0010, 0x21d0)); // Last Menstrual Date removals_.insert(DicomTag(0x0010, 0x21f0)); // Patient's Religious Preference removals_.insert(DicomTag(0x0010, 0x2203)); /* X/Z */ // Patient Sex Neutered removals_.insert(DicomTag(0x0010, 0x2297)); // Responsible Person removals_.insert(DicomTag(0x0010, 0x2299)); // Responsible Organization removals_.insert(DicomTag(0x0010, 0x4000)); // Patient Comments removals_.insert(DicomTag(0x0018, 0x1000)); /* X/Z/D */ // Device Serial Number removals_.insert(DicomTag(0x0018, 0x1002)); /* TODO UID */ // Device UID removals_.insert(DicomTag(0x0018, 0x1004)); // Plate ID removals_.insert(DicomTag(0x0018, 0x1005)); // Generator ID removals_.insert(DicomTag(0x0018, 0x1007)); // Cassette ID removals_.insert(DicomTag(0x0018, 0x1008)); // Gantry ID removals_.insert(DicomTag(0x0018, 0x1030)); /* X/D */ // Protocol Name removals_.insert(DicomTag(0x0018, 0x1400)); /* X/D */ // Acquisition Device Processing Description removals_.insert(DicomTag(0x0018, 0x2042)); /* TODO UID */ // Target UID removals_.insert(DicomTag(0x0018, 0x4000)); // Acquisition Comments removals_.insert(DicomTag(0x0018, 0x700a)); /* X/D */ // Detector ID removals_.insert(DicomTag(0x0018, 0x9424)); // Acquisition Protocol Description removals_.insert(DicomTag(0x0018, 0x9516)); /* X/D */ // Start Acquisition DateTime removals_.insert(DicomTag(0x0018, 0x9517)); /* X/D */ // End Acquisition DateTime removals_.insert(DicomTag(0x0018, 0xa003)); // Contribution Description removals_.insert(DicomTag(0x0020, 0x0200)); /* TODO UID */ // Synchronization Frame of Reference UID removals_.insert(DicomTag(0x0020, 0x3401)); // Modifying Device ID removals_.insert(DicomTag(0x0020, 0x3404)); // Modifying Device Manufacturer removals_.insert(DicomTag(0x0020, 0x3406)); // Modified Image Description removals_.insert(DicomTag(0x0020, 0x4000)); // Image Comments removals_.insert(DicomTag(0x0020, 0x9158)); // Frame Comments removals_.insert(DicomTag(0x0020, 0x9161)); /* TODO UID */ // Concatenation UID removals_.insert(DicomTag(0x0020, 0x9164)); /* TODO UID */ // Dimension Organization UID removals_.insert(DicomTag(0x0028, 0x1199)); /* TODO UID */ // Palette Color Lookup Table UID removals_.insert(DicomTag(0x0028, 0x1214)); /* TODO UID */ // Large Palette Color Lookup Table UID removals_.insert(DicomTag(0x0028, 0x4000)); // Image Presentation Comments removals_.insert(DicomTag(0x0032, 0x0012)); // Study ID Issuer removals_.insert(DicomTag(0x0032, 0x1020)); // Scheduled Study Location removals_.insert(DicomTag(0x0032, 0x1021)); // Scheduled Study Location AE Title removals_.insert(DicomTag(0x0032, 0x1030)); // Reason for Study removals_.insert(DicomTag(0x0032, 0x1032)); // Requesting Physician removals_.insert(DicomTag(0x0032, 0x1033)); // Requesting Service removals_.insert(DicomTag(0x0032, 0x1060)); /* X/Z */ // Requested Procedure Description removals_.insert(DicomTag(0x0032, 0x1070)); // Requested Contrast Agent removals_.insert(DicomTag(0x0032, 0x4000)); // Study Comments removals_.insert(DicomTag(0x0038, 0x0004)); // Referenced Patient Alias Sequence removals_.insert(DicomTag(0x0038, 0x0010)); // Admission ID removals_.insert(DicomTag(0x0038, 0x0011)); // Issuer of Admission ID removals_.insert(DicomTag(0x0038, 0x001e)); // Scheduled Patient Institution Residence removals_.insert(DicomTag(0x0038, 0x0020)); // Admitting Date removals_.insert(DicomTag(0x0038, 0x0021)); // Admitting Time removals_.insert(DicomTag(0x0038, 0x0040)); // Discharge Diagnosis Description removals_.insert(DicomTag(0x0038, 0x0050)); // Special Needs removals_.insert(DicomTag(0x0038, 0x0060)); // Service Episode ID removals_.insert(DicomTag(0x0038, 0x0061)); // Issuer of Service Episode ID removals_.insert(DicomTag(0x0038, 0x0062)); // Service Episode Description removals_.insert(DicomTag(0x0038, 0x0300)); // Current Patient Location removals_.insert(DicomTag(0x0038, 0x0400)); // Patient's Institution Residence removals_.insert(DicomTag(0x0038, 0x0500)); // Patient State removals_.insert(DicomTag(0x0038, 0x4000)); // Visit Comments removals_.insert(DicomTag(0x0040, 0x0001)); // Scheduled Station AE Title removals_.insert(DicomTag(0x0040, 0x0002)); // Scheduled Procedure Step Start Date removals_.insert(DicomTag(0x0040, 0x0003)); // Scheduled Procedure Step Start Time removals_.insert(DicomTag(0x0040, 0x0004)); // Scheduled Procedure Step End Date removals_.insert(DicomTag(0x0040, 0x0005)); // Scheduled Procedure Step End Time removals_.insert(DicomTag(0x0040, 0x0006)); // Scheduled Performing Physician Name removals_.insert(DicomTag(0x0040, 0x0007)); // Scheduled Procedure Step Description removals_.insert(DicomTag(0x0040, 0x000b)); // Scheduled Performing Physician Identification Sequence removals_.insert(DicomTag(0x0040, 0x0010)); // Scheduled Station Name removals_.insert(DicomTag(0x0040, 0x0011)); // Scheduled Procedure Step Location removals_.insert(DicomTag(0x0040, 0x0012)); // Pre-Medication removals_.insert(DicomTag(0x0040, 0x0241)); // Performed Station AE Title removals_.insert(DicomTag(0x0040, 0x0242)); // Performed Station Name removals_.insert(DicomTag(0x0040, 0x0243)); // Performed Location removals_.insert(DicomTag(0x0040, 0x0244)); // Performed Procedure Step Start Date removals_.insert(DicomTag(0x0040, 0x0245)); // Performed Procedure Step Start Time removals_.insert(DicomTag(0x0040, 0x0250)); // Performed Procedure Step End Date removals_.insert(DicomTag(0x0040, 0x0251)); // Performed Procedure Step End Time removals_.insert(DicomTag(0x0040, 0x0253)); // Performed Procedure Step ID removals_.insert(DicomTag(0x0040, 0x0254)); // Performed Procedure Step Description removals_.insert(DicomTag(0x0040, 0x0275)); // Request Attributes Sequence removals_.insert(DicomTag(0x0040, 0x0280)); // Comments on the Performed Procedure Step removals_.insert(DicomTag(0x0040, 0x0555)); // Acquisition Context Sequence removals_.insert(DicomTag(0x0040, 0x1001)); // Requested Procedure ID removals_.insert(DicomTag(0x0040, 0x1004)); // Patient Transport Arrangements removals_.insert(DicomTag(0x0040, 0x1005)); // Requested Procedure Location removals_.insert(DicomTag(0x0040, 0x1010)); // Names of Intended Recipient of Results removals_.insert(DicomTag(0x0040, 0x1011)); // Intended Recipients of Results Identification Sequence removals_.insert(DicomTag(0x0040, 0x1102)); // Person Address removals_.insert(DicomTag(0x0040, 0x1103)); // Person's Telephone Numbers removals_.insert(DicomTag(0x0040, 0x1104)); // Person's Telecom Information removals_.insert(DicomTag(0x0040, 0x1400)); // Requested Procedure Comments removals_.insert(DicomTag(0x0040, 0x2001)); // Reason for the Imaging Service Request removals_.insert(DicomTag(0x0040, 0x2008)); // Order Entered By removals_.insert(DicomTag(0x0040, 0x2009)); // Order Enterer Location removals_.insert(DicomTag(0x0040, 0x2010)); // Order Callback Phone Number removals_.insert(DicomTag(0x0040, 0x2011)); // Order Callback Telecom Information removals_.insert(DicomTag(0x0040, 0x2400)); // Imaging Service Request Comments removals_.insert(DicomTag(0x0040, 0x3001)); // Confidentiality Constraint on Patient Data Description removals_.insert(DicomTag(0x0040, 0x4005)); // Scheduled Procedure Step Start DateTime removals_.insert(DicomTag(0x0040, 0x4010)); // Scheduled Procedure Step Modification DateTime removals_.insert(DicomTag(0x0040, 0x4011)); // Expected Completion DateTime removals_.insert(DicomTag(0x0040, 0x4023)); /* TODO UID */ // Referenced General Purpose Scheduled Procedure Step Transaction UID removals_.insert(DicomTag(0x0040, 0x4025)); // Scheduled Station Name Code Sequence removals_.insert(DicomTag(0x0040, 0x4027)); // Scheduled Station Geographic Location Code Sequence removals_.insert(DicomTag(0x0040, 0x4028)); // Performed Station Name Code Sequence removals_.insert(DicomTag(0x0040, 0x4030)); // Performed Station Geographic Location Code Sequence removals_.insert(DicomTag(0x0040, 0x4034)); // Scheduled Human Performers Sequence removals_.insert(DicomTag(0x0040, 0x4035)); // Actual Human Performers Sequence removals_.insert(DicomTag(0x0040, 0x4036)); // Human Performers Organization removals_.insert(DicomTag(0x0040, 0x4037)); // Human Performers Name removals_.insert(DicomTag(0x0040, 0x4050)); // Performed Procedure Step Start DateTime removals_.insert(DicomTag(0x0040, 0x4051)); // Performed Procedure Step End DateTime removals_.insert(DicomTag(0x0040, 0x4052)); // Procedure Step Cancellation DateTime removals_.insert(DicomTag(0x0040, 0xa027)); // Verifying Organization removals_.insert(DicomTag(0x0040, 0xa078)); // Author Observer Sequence removals_.insert(DicomTag(0x0040, 0xa07a)); // Participant Sequence removals_.insert(DicomTag(0x0040, 0xa07c)); // Custodial Organization Sequence removals_.insert(DicomTag(0x0040, 0xa124)); /* TODO UID */ // UID removals_.insert(DicomTag(0x0040, 0xa171)); /* TODO UID */ // Observation UID removals_.insert(DicomTag(0x0040, 0xa172)); /* TODO UID */ // Referenced Observation UID (Trial) removals_.insert(DicomTag(0x0040, 0xa192)); // Observation Date (Trial) removals_.insert(DicomTag(0x0040, 0xa193)); // Observation Time (Trial) removals_.insert(DicomTag(0x0040, 0xa307)); // Current Observer (Trial) removals_.insert(DicomTag(0x0040, 0xa352)); // Verbal Source (Trial) removals_.insert(DicomTag(0x0040, 0xa353)); // Address (Trial) removals_.insert(DicomTag(0x0040, 0xa354)); // Telephone Number (Trial) removals_.insert(DicomTag(0x0040, 0xa358)); // Verbal Source Identifier Code Sequence (Trial) removals_.insert(DicomTag(0x0040, 0xa402)); /* TODO UID */ // Observation Subject UID (Trial) removals_.insert(DicomTag(0x0040, 0xa730)); // Content Sequence removals_.insert(DicomTag(0x0040, 0xdb0c)); /* TODO UID */ // Template Extension Organization UID removals_.insert(DicomTag(0x0040, 0xdb0d)); /* TODO UID */ // Template Extension Creator UID removals_.insert(DicomTag(0x0062, 0x0021)); /* TODO UID */ // Tracking UID removals_.insert(DicomTag(0x0070, 0x0086)); // Content Creator's Identification Code Sequence removals_.insert(DicomTag(0x0070, 0x031a)); /* TODO UID */ // Fiducial UID removals_.insert(DicomTag(0x0070, 0x1101)); /* TODO UID */ // Presentation Display Collection UID removals_.insert(DicomTag(0x0070, 0x1102)); /* TODO UID */ // Presentation Sequence Collection UID removals_.insert(DicomTag(0x0088, 0x0140)); /* TODO UID */ // Storage Media File-set UID removals_.insert(DicomTag(0x0088, 0x0200)); // Icon Image Sequence(see Note 12) removals_.insert(DicomTag(0x0088, 0x0904)); // Topic Title removals_.insert(DicomTag(0x0088, 0x0906)); // Topic Subject removals_.insert(DicomTag(0x0088, 0x0910)); // Topic Author removals_.insert(DicomTag(0x0088, 0x0912)); // Topic Keywords removals_.insert(DicomTag(0x0400, 0x0100)); // Digital Signature UID removals_.insert(DicomTag(0x0400, 0x0402)); // Referenced Digital Signature Sequence removals_.insert(DicomTag(0x0400, 0x0403)); // Referenced SOP Instance MAC Sequence removals_.insert(DicomTag(0x0400, 0x0404)); // MAC removals_.insert(DicomTag(0x0400, 0x0550)); // Modified Attributes Sequence removals_.insert(DicomTag(0x0400, 0x0561)); // Original Attributes Sequence removals_.insert(DicomTag(0x2030, 0x0020)); // Text String removals_.insert(DicomTag(0x3008, 0x0105)); // Source Serial Number removals_.insert(DicomTag(0x300a, 0x0013)); /* TODO UID */ // Dose Reference UID removals_.insert(DicomTag(0x300c, 0x0113)); // Reason for Omission Description removals_.insert(DicomTag(0x300e, 0x0008)); /* X/Z */ // Reviewer Name removals_.insert(DicomTag(0x4000, 0x0010)); // Arbitrary removals_.insert(DicomTag(0x4000, 0x4000)); // Text Comments removals_.insert(DicomTag(0x4008, 0x0042)); // Results ID Issuer removals_.insert(DicomTag(0x4008, 0x0102)); // Interpretation Recorder removals_.insert(DicomTag(0x4008, 0x010a)); // Interpretation Transcriber removals_.insert(DicomTag(0x4008, 0x010b)); // Interpretation Text removals_.insert(DicomTag(0x4008, 0x010c)); // Interpretation Author removals_.insert(DicomTag(0x4008, 0x0111)); // Interpretation Approver Sequence removals_.insert(DicomTag(0x4008, 0x0114)); // Physician Approving Interpretation removals_.insert(DicomTag(0x4008, 0x0115)); // Interpretation Diagnosis Description removals_.insert(DicomTag(0x4008, 0x0118)); // Results Distribution List Sequence removals_.insert(DicomTag(0x4008, 0x0119)); // Distribution Name removals_.insert(DicomTag(0x4008, 0x011a)); // Distribution Address removals_.insert(DicomTag(0x4008, 0x0202)); // Interpretation ID Issuer removals_.insert(DicomTag(0x4008, 0x0300)); // Impressions removals_.insert(DicomTag(0x4008, 0x4000)); // Results Comments removals_.insert(DicomTag(0xfffa, 0xfffa)); // Digital Signatures Sequence removals_.insert(DicomTag(0xfffc, 0xfffc)); // Data Set Trailing Padding // Set the DeidentificationMethod tag ReplaceInternal(DICOM_TAG_DEIDENTIFICATION_METHOD, ORTHANC_DEIDENTIFICATION_METHOD_2017c); } void DicomModification::SetupAnonymization(DicomVersion version) { isAnonymization_ = true; removals_.clear(); clearings_.clear(); ClearReplacements(); removePrivateTags_ = true; level_ = ResourceType_Patient; uidMap_.clear(); privateTagsToKeep_.clear(); switch (version) { case DicomVersion_2008: SetupAnonymization2008(); break; case DicomVersion_2017c: SetupAnonymization2017c(); break; default: throw OrthancException(ErrorCode_ParameterOutOfRange); } // Set the PatientIdentityRemoved tag ReplaceInternal(DicomTag(0x0012, 0x0062), "YES"); // (*) Choose a random patient name and ID std::string patientId = FromDcmtkBridge::GenerateUniqueIdentifier(ResourceType_Patient); ReplaceInternal(DICOM_TAG_PATIENT_ID, patientId); ReplaceInternal(DICOM_TAG_PATIENT_NAME, patientId); } void DicomModification::Apply(ParsedDicomFile& toModify) { // Check the request assert(ResourceType_Patient + 1 == ResourceType_Study && ResourceType_Study + 1 == ResourceType_Series && ResourceType_Series + 1 == ResourceType_Instance); if (IsRemoved(DICOM_TAG_PATIENT_ID) || IsRemoved(DICOM_TAG_STUDY_INSTANCE_UID) || IsRemoved(DICOM_TAG_SERIES_INSTANCE_UID) || IsRemoved(DICOM_TAG_SOP_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest); } // Sanity checks at the patient level if (level_ == ResourceType_Patient && !IsReplaced(DICOM_TAG_PATIENT_ID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a patient, her PatientID is required to be modified"); } if (!allowManualIdentifiers_) { if (level_ == ResourceType_Patient && IsReplaced(DICOM_TAG_STUDY_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a patient, the StudyInstanceUID cannot be manually modified"); } if (level_ == ResourceType_Patient && IsReplaced(DICOM_TAG_SERIES_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a patient, the SeriesInstanceUID cannot be manually modified"); } if (level_ == ResourceType_Patient && IsReplaced(DICOM_TAG_SOP_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a patient, the SopInstanceUID cannot be manually modified"); } } // Sanity checks at the study level if (level_ == ResourceType_Study && IsReplaced(DICOM_TAG_PATIENT_ID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a study, the parent PatientID cannot be manually modified"); } if (!allowManualIdentifiers_) { if (level_ == ResourceType_Study && IsReplaced(DICOM_TAG_SERIES_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a study, the SeriesInstanceUID cannot be manually modified"); } if (level_ == ResourceType_Study && IsReplaced(DICOM_TAG_SOP_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a study, the SopInstanceUID cannot be manually modified"); } } // Sanity checks at the series level if (level_ == ResourceType_Series && IsReplaced(DICOM_TAG_PATIENT_ID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a series, the parent PatientID cannot be manually modified"); } if (level_ == ResourceType_Series && IsReplaced(DICOM_TAG_STUDY_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a series, the parent StudyInstanceUID cannot be manually modified"); } if (!allowManualIdentifiers_) { if (level_ == ResourceType_Series && IsReplaced(DICOM_TAG_SOP_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying a series, the SopInstanceUID cannot be manually modified"); } } // Sanity checks at the instance level if (level_ == ResourceType_Instance && IsReplaced(DICOM_TAG_PATIENT_ID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying an instance, the parent PatientID cannot be manually modified"); } if (level_ == ResourceType_Instance && IsReplaced(DICOM_TAG_STUDY_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying an instance, the parent StudyInstanceUID cannot be manually modified"); } if (level_ == ResourceType_Instance && IsReplaced(DICOM_TAG_SERIES_INSTANCE_UID)) { throw OrthancException(ErrorCode_BadRequest, "When modifying an instance, the parent SeriesInstanceUID cannot be manually modified"); } // (0) Create a summary of the source file, if a custom generator // is provided if (identifierGenerator_ != NULL) { toModify.ExtractDicomSummary(currentSource_, ORTHANC_MAXIMUM_TAG_LENGTH); } // (1) Make sure the relationships are updated with the ids that we force too // i.e: an RT-STRUCT is referencing its own StudyInstanceUID if (isAnonymization_ && updateReferencedRelationships_) { if (IsReplaced(DICOM_TAG_STUDY_INSTANCE_UID)) { std::string original; std::string replacement = GetReplacementAsString(DICOM_TAG_STUDY_INSTANCE_UID); toModify.GetTagValue(original, DICOM_TAG_STUDY_INSTANCE_UID); RegisterMappedDicomIdentifier(original, replacement, ResourceType_Study); } if (IsReplaced(DICOM_TAG_SERIES_INSTANCE_UID)) { std::string original; std::string replacement = GetReplacementAsString(DICOM_TAG_SERIES_INSTANCE_UID); toModify.GetTagValue(original, DICOM_TAG_SERIES_INSTANCE_UID); RegisterMappedDicomIdentifier(original, replacement, ResourceType_Series); } if (IsReplaced(DICOM_TAG_SOP_INSTANCE_UID)) { std::string original; std::string replacement = GetReplacementAsString(DICOM_TAG_SOP_INSTANCE_UID); toModify.GetTagValue(original, DICOM_TAG_SOP_INSTANCE_UID); RegisterMappedDicomIdentifier(original, replacement, ResourceType_Instance); } } // (2) Remove the private tags, if need be if (removePrivateTags_) { toModify.RemovePrivateTags(privateTagsToKeep_); } // (3) Clear the tags specified by the user for (SetOfTags::const_iterator it = clearings_.begin(); it != clearings_.end(); ++it) { toModify.Clear(*it, true /* only clear if the tag exists in the original file */); } // (4) Remove the tags specified by the user for (SetOfTags::const_iterator it = removals_.begin(); it != removals_.end(); ++it) { toModify.Remove(*it); } // (5) Replace the tags for (Replacements::const_iterator it = replacements_.begin(); it != replacements_.end(); ++it) { toModify.Replace(it->first, *it->second, true /* decode data URI scheme */, DicomReplaceMode_InsertIfAbsent, privateCreator_); } // (6) Update the DICOM identifiers if (level_ <= ResourceType_Study && !IsReplaced(DICOM_TAG_STUDY_INSTANCE_UID)) { if (keepStudyInstanceUid_) { LOG(WARNING) << "Modifying a study while keeping its original StudyInstanceUID: This should be avoided!"; } else { MapDicomTags(toModify, ResourceType_Study); } } if (level_ <= ResourceType_Series && !IsReplaced(DICOM_TAG_SERIES_INSTANCE_UID)) { if (keepSeriesInstanceUid_) { LOG(WARNING) << "Modifying a series while keeping its original SeriesInstanceUID: This should be avoided!"; } else { MapDicomTags(toModify, ResourceType_Series); } } if (level_ <= ResourceType_Instance && // Always true !IsReplaced(DICOM_TAG_SOP_INSTANCE_UID)) { if (keepSopInstanceUid_) { LOG(WARNING) << "Modifying an instance while keeping its original SOPInstanceUID: This should be avoided!"; } else { MapDicomTags(toModify, ResourceType_Instance); } } // (7) Update the "referenced" relationships in the case of an anonymization if (isAnonymization_) { RelationshipsVisitor visitor(*this); if (updateReferencedRelationships_) { toModify.Apply(visitor); } else { visitor.RemoveRelationships(toModify); } } } static bool IsDatabaseKey(const DicomTag& tag) { return (tag == DICOM_TAG_PATIENT_ID || tag == DICOM_TAG_STUDY_INSTANCE_UID || tag == DICOM_TAG_SERIES_INSTANCE_UID || tag == DICOM_TAG_SOP_INSTANCE_UID); } static void ParseListOfTags(DicomModification& target, const Json::Value& query, DicomModification::TagOperation operation, bool force) { if (!query.isArray()) { throw OrthancException(ErrorCode_BadRequest); } for (Json::Value::ArrayIndex i = 0; i < query.size(); i++) { if (query[i].type() != Json::stringValue) { throw OrthancException(ErrorCode_BadRequest); } std::string name = query[i].asString(); DicomTag tag = FromDcmtkBridge::ParseTag(name); if (!force && IsDatabaseKey(tag)) { throw OrthancException(ErrorCode_BadRequest, "Marking tag \"" + name + "\" as to be " + (operation == DicomModification::TagOperation_Keep ? "kept" : "removed") + " requires the \"Force\" option to be set to true"); } switch (operation) { case DicomModification::TagOperation_Keep: target.Keep(tag); VLOG(1) << "Keep: " << name << " " << tag; break; case DicomModification::TagOperation_Remove: target.Remove(tag); VLOG(1) << "Remove: " << name << " " << tag; break; default: throw OrthancException(ErrorCode_InternalError); } } } static void ParseReplacements(DicomModification& target, const Json::Value& replacements, bool force) { if (!replacements.isObject()) { throw OrthancException(ErrorCode_BadRequest); } Json::Value::Members members = replacements.getMemberNames(); for (size_t i = 0; i < members.size(); i++) { const std::string& name = members[i]; const Json::Value& value = replacements[name]; DicomTag tag = FromDcmtkBridge::ParseTag(name); if (!force && IsDatabaseKey(tag)) { throw OrthancException(ErrorCode_BadRequest, "Marking tag \"" + name + "\" as to be replaced " + "requires the \"Force\" option to be set to true"); } target.Replace(tag, value, false); VLOG(1) << "Replace: " << name << " " << tag << " == " << value.toStyledString(); } } static bool GetBooleanValue(const std::string& member, const Json::Value& json, bool defaultValue) { if (!json.isMember(member)) { return defaultValue; } else if (json[member].type() == Json::booleanValue) { return json[member].asBool(); } else { throw OrthancException(ErrorCode_BadFileFormat, "Member \"" + member + "\" should be a Boolean value"); } } void DicomModification::ParseModifyRequest(const Json::Value& request) { if (!request.isObject()) { throw OrthancException(ErrorCode_BadFileFormat); } bool force = GetBooleanValue("Force", request, false); if (GetBooleanValue("RemovePrivateTags", request, false)) { SetRemovePrivateTags(true); } if (request.isMember("Remove")) { ParseListOfTags(*this, request["Remove"], TagOperation_Remove, force); } if (request.isMember("Replace")) { ParseReplacements(*this, request["Replace"], force); } // The "Keep" operation only makes sense for the tags // StudyInstanceUID, SeriesInstanceUID and SOPInstanceUID. Avoid // this feature as much as possible, as this breaks the DICOM // model of the real world, except if you know exactly what // you're doing! if (request.isMember("Keep")) { ParseListOfTags(*this, request["Keep"], TagOperation_Keep, force); } // New in Orthanc 1.6.0 if (request.isMember("PrivateCreator")) { privateCreator_ = SerializationToolbox::ReadString(request, "PrivateCreator"); } } void DicomModification::ParseAnonymizationRequest(bool& patientNameReplaced, const Json::Value& request) { if (!request.isObject()) { throw OrthancException(ErrorCode_BadFileFormat); } bool force = GetBooleanValue("Force", request, false); // As of Orthanc 1.3.0, the default anonymization is done // according to PS 3.15-2017c Table E.1-1 (basic profile) DicomVersion version = DicomVersion_2017c; if (request.isMember("DicomVersion")) { if (request["DicomVersion"].type() != Json::stringValue) { throw OrthancException(ErrorCode_BadFileFormat); } else { version = StringToDicomVersion(request["DicomVersion"].asString()); } } SetupAnonymization(version); std::string patientName = GetReplacementAsString(DICOM_TAG_PATIENT_NAME); if (GetBooleanValue("KeepPrivateTags", request, false)) { SetRemovePrivateTags(false); } if (request.isMember("Remove")) { ParseListOfTags(*this, request["Remove"], TagOperation_Remove, force); } if (request.isMember("Replace")) { ParseReplacements(*this, request["Replace"], force); } if (request.isMember("Keep")) { ParseListOfTags(*this, request["Keep"], TagOperation_Keep, force); } patientNameReplaced = (IsReplaced(DICOM_TAG_PATIENT_NAME) && GetReplacement(DICOM_TAG_PATIENT_NAME) == patientName); // New in Orthanc 1.6.0 if (request.isMember("PrivateCreator")) { privateCreator_ = SerializationToolbox::ReadString(request, "PrivateCreator"); } } static const char* REMOVE_PRIVATE_TAGS = "RemovePrivateTags"; static const char* LEVEL = "Level"; static const char* ALLOW_MANUAL_IDENTIFIERS = "AllowManualIdentifiers"; static const char* KEEP_STUDY_INSTANCE_UID = "KeepStudyInstanceUID"; static const char* KEEP_SERIES_INSTANCE_UID = "KeepSeriesInstanceUID"; static const char* KEEP_SOP_INSTANCE_UID = "KeepSOPInstanceUID"; static const char* UPDATE_REFERENCED_RELATIONSHIPS = "UpdateReferencedRelationships"; static const char* IS_ANONYMIZATION = "IsAnonymization"; static const char* REMOVALS = "Removals"; static const char* CLEARINGS = "Clearings"; static const char* PRIVATE_TAGS_TO_KEEP = "PrivateTagsToKeep"; static const char* REPLACEMENTS = "Replacements"; static const char* MAP_PATIENTS = "MapPatients"; static const char* MAP_STUDIES = "MapStudies"; static const char* MAP_SERIES = "MapSeries"; static const char* MAP_INSTANCES = "MapInstances"; static const char* PRIVATE_CREATOR = "PrivateCreator"; // New in Orthanc 1.6.0 void DicomModification::Serialize(Json::Value& value) const { if (identifierGenerator_ != NULL) { throw OrthancException(ErrorCode_InternalError, "Cannot serialize a DicomModification with a custom identifier generator"); } value = Json::objectValue; value[REMOVE_PRIVATE_TAGS] = removePrivateTags_; value[LEVEL] = EnumerationToString(level_); value[ALLOW_MANUAL_IDENTIFIERS] = allowManualIdentifiers_; value[KEEP_STUDY_INSTANCE_UID] = keepStudyInstanceUid_; value[KEEP_SERIES_INSTANCE_UID] = keepSeriesInstanceUid_; value[KEEP_SOP_INSTANCE_UID] = keepSopInstanceUid_; value[UPDATE_REFERENCED_RELATIONSHIPS] = updateReferencedRelationships_; value[IS_ANONYMIZATION] = isAnonymization_; value[PRIVATE_CREATOR] = privateCreator_; SerializationToolbox::WriteSetOfTags(value, removals_, REMOVALS); SerializationToolbox::WriteSetOfTags(value, clearings_, CLEARINGS); SerializationToolbox::WriteSetOfTags(value, privateTagsToKeep_, PRIVATE_TAGS_TO_KEEP); Json::Value& tmp = value[REPLACEMENTS]; tmp = Json::objectValue; for (Replacements::const_iterator it = replacements_.begin(); it != replacements_.end(); ++it) { assert(it->second != NULL); tmp[it->first.Format()] = *it->second; } Json::Value& mapPatients = value[MAP_PATIENTS]; Json::Value& mapStudies = value[MAP_STUDIES]; Json::Value& mapSeries = value[MAP_SERIES]; Json::Value& mapInstances = value[MAP_INSTANCES]; mapPatients = Json::objectValue; mapStudies = Json::objectValue; mapSeries = Json::objectValue; mapInstances = Json::objectValue; for (UidMap::const_iterator it = uidMap_.begin(); it != uidMap_.end(); ++it) { Json::Value* tmp2 = NULL; switch (it->first.first) { case ResourceType_Patient: tmp2 = &mapPatients; break; case ResourceType_Study: tmp2 = &mapStudies; break; case ResourceType_Series: tmp2 = &mapSeries; break; case ResourceType_Instance: tmp2 = &mapInstances; break; default: throw OrthancException(ErrorCode_InternalError); } assert(tmp2 != NULL); (*tmp2) [it->first.second] = it->second; } } void DicomModification::UnserializeUidMap(ResourceType level, const Json::Value& serialized, const char* field) { if (!serialized.isMember(field) || serialized[field].type() != Json::objectValue) { throw OrthancException(ErrorCode_BadFileFormat); } Json::Value::Members names = serialized[field].getMemberNames(); for (Json::Value::Members::const_iterator it = names.begin(); it != names.end(); ++it) { const Json::Value& value = serialized[field][*it]; if (value.type() != Json::stringValue) { throw OrthancException(ErrorCode_BadFileFormat); } else { uidMap_[std::make_pair(level, *it)] = value.asString(); } } } DicomModification::DicomModification(const Json::Value& serialized) : identifierGenerator_(NULL) { removePrivateTags_ = SerializationToolbox::ReadBoolean(serialized, REMOVE_PRIVATE_TAGS); level_ = StringToResourceType(SerializationToolbox::ReadString(serialized, LEVEL).c_str()); allowManualIdentifiers_ = SerializationToolbox::ReadBoolean(serialized, ALLOW_MANUAL_IDENTIFIERS); keepStudyInstanceUid_ = SerializationToolbox::ReadBoolean(serialized, KEEP_STUDY_INSTANCE_UID); keepSeriesInstanceUid_ = SerializationToolbox::ReadBoolean(serialized, KEEP_SERIES_INSTANCE_UID); keepSopInstanceUid_ = SerializationToolbox::ReadBoolean(serialized, KEEP_SOP_INSTANCE_UID); updateReferencedRelationships_ = SerializationToolbox::ReadBoolean (serialized, UPDATE_REFERENCED_RELATIONSHIPS); isAnonymization_ = SerializationToolbox::ReadBoolean(serialized, IS_ANONYMIZATION); if (serialized.isMember(PRIVATE_CREATOR)) { privateCreator_ = SerializationToolbox::ReadString(serialized, PRIVATE_CREATOR); } SerializationToolbox::ReadSetOfTags(removals_, serialized, REMOVALS); SerializationToolbox::ReadSetOfTags(clearings_, serialized, CLEARINGS); SerializationToolbox::ReadSetOfTags(privateTagsToKeep_, serialized, PRIVATE_TAGS_TO_KEEP); if (!serialized.isMember(REPLACEMENTS) || serialized[REPLACEMENTS].type() != Json::objectValue) { throw OrthancException(ErrorCode_BadFileFormat); } Json::Value::Members names = serialized[REPLACEMENTS].getMemberNames(); for (Json::Value::Members::const_iterator it = names.begin(); it != names.end(); ++it) { DicomTag tag(0, 0); if (!DicomTag::ParseHexadecimal(tag, it->c_str())) { throw OrthancException(ErrorCode_BadFileFormat); } else { const Json::Value& value = serialized[REPLACEMENTS][*it]; replacements_.insert(std::make_pair(tag, new Json::Value(value))); } } UnserializeUidMap(ResourceType_Patient, serialized, MAP_PATIENTS); UnserializeUidMap(ResourceType_Study, serialized, MAP_STUDIES); UnserializeUidMap(ResourceType_Series, serialized, MAP_SERIES); UnserializeUidMap(ResourceType_Instance, serialized, MAP_INSTANCES); } }
68,386
23,774
/* Copyright (c) 2020 - present Advanced Micro Devices, Inc. All rights reserved. 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 "rdc_lib/RdcLibraryLoader.h" namespace amd { namespace rdc { RdcLibraryLoader::RdcLibraryLoader(): libHandler_(nullptr) { } rdc_status_t RdcLibraryLoader::load(const char* filename) { if (filename == nullptr) { return RDC_ST_FAIL_LOAD_MODULE; } if (libHandler_) { unload(); } std::lock_guard<std::mutex> guard(library_mutex_); libHandler_ = dlopen(filename, RTLD_LAZY); if (!libHandler_) { char* error = dlerror(); RDC_LOG(RDC_ERROR, "Fail to open " << filename <<": " << error); return RDC_ST_FAIL_LOAD_MODULE; } return RDC_ST_OK; } rdc_status_t RdcLibraryLoader::unload() { std::lock_guard<std::mutex> guard(library_mutex_); if (libHandler_) { dlclose(libHandler_); libHandler_ = nullptr; } return RDC_ST_OK; } RdcLibraryLoader::~RdcLibraryLoader() { unload(); } } // namespace rdc } // namespace amd
2,073
703
//===- Offset.hpp ------------------------------------------------*- C++-*-===// // // Copyright (C) 2020 GrammaTech, Inc. // // This code is licensed under the MIT license. See the LICENSE file in the // project root for license terms. // // This project is sponsored by the Office of Naval Research, One Liberty // Center, 875 N. Randolph Street, Arlington, VA 22203 under contract # // N68335-17-C-0700. The content of the information does not necessarily // reflect the position or policy of the Government and no official // endorsement should be inferred. // //===----------------------------------------------------------------------===// #ifndef GTIRB_OFFSET_H #define GTIRB_OFFSET_H #include <gtirb/Context.hpp> #include <gtirb/Export.hpp> #include <boost/functional/hash.hpp> #include <cstdint> #include <functional> namespace gtirb { namespace proto { class Offset; } /// \class Offset /// /// \brief Describes a location inside a node (byte interval, block, etc). struct GTIRB_EXPORT_API Offset { /// \brief The UUID of the node. UUID ElementId; /// \brief The displacement from the start of the node, in bytes. uint64_t Displacement{0}; /// \brief Constructor using a ElemId uuid and a Displacement. Offset(const UUID& ElemId, uint64_t Disp) : ElementId(ElemId), Displacement(Disp) {} /// \brief Default constructor. Offset() = default; /// \brief Equality operator for \ref Offset. // Note: boost::uuid is not constexpr. friend bool operator==(const Offset& LHS, const Offset& RHS) noexcept { return LHS.ElementId == RHS.ElementId && LHS.Displacement == RHS.Displacement; } /// \brief Inequality operator for \ref Offset. friend bool operator!=(const Offset& LHS, const Offset& RHS) noexcept { return !operator==(LHS, RHS); } /// \brief Less-than operator for \ref Offset. friend constexpr bool operator<(const Offset& LHS, const Offset& RHS) noexcept { return std::tie(LHS.ElementId, LHS.Displacement) < std::tie(RHS.ElementId, RHS.Displacement); } /// \brief Greater-than operator for \ref Offset. friend constexpr bool operator>(const Offset& LHS, const Offset& RHS) noexcept { return operator<(RHS, LHS); } /// \brief Less-than-or-equal operator for \ref Offset. friend constexpr bool operator<=(const Offset& LHS, const Offset& RHS) noexcept { return !operator<(RHS, LHS); } /// \brief Greater-than-or-equal operator for \ref Offset. friend constexpr bool operator>=(const Offset& LHS, const Offset& RHS) noexcept { return !operator<(LHS, RHS); } private: /// @cond INTERNAL /// \brief The protobuf message type used for serializing Offset. using MessageType = proto::Offset; /// \brief Serialize into a protobuf message. /// /// \param[out] Message Serialize into this message. /// /// \return void void toProtobuf(MessageType* Message) const; /// \brief Construct a Offset from a protobuf message. /// /// \param C The Context in which the deserialized Offset will be /// held. /// \param Message The protobuf message from which to deserialize. /// /// \return true if the \ref Offset could be deserialized, false otherwise. bool fromProtobuf(Context& C, const MessageType& Message); /// @endcond // Enables serialization. friend bool fromProtobuf(Context&, Offset&, const MessageType&); }; } // namespace gtirb namespace std { /// \brief Hash operation for \ref Offset. template <> struct hash<gtirb::Offset> { size_t operator()(const gtirb::Offset& X) const { std::size_t Seed = 0; boost::hash_combine(Seed, X.ElementId); boost::hash_combine(Seed, X.Displacement); return Seed; } }; } // namespace std #endif // GTIRB_OFFSET_H
3,898
1,279
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file eggMorphList.cxx * @author drose * @date 2001-05-15 */ #include "eggMorphList.h" // Continue all of the vector import definitions. #define EXPCL EXPCL_PANDAEGG #define EXPTP EXPTP_PANDAEGG #define TYPE LVector3d #define NAME vector_LVector3d #include "vector_src.cxx" #define EXPCL EXPCL_PANDAEGG #define EXPTP EXPTP_PANDAEGG #define TYPE LVector2d #define NAME vector_LVector2d #include "vector_src.cxx" #define EXPCL EXPCL_PANDAEGG #define EXPTP EXPTP_PANDAEGG #define TYPE LVector4 #define NAME vector_LVector4 #include "vector_src.cxx"
845
327
#include <cpplib/stdinc.hpp> bool check(int n, int m, vector<list<int> > iadj, vvb mat, vi dg, int k){ queue<ii> q; set<int> inq; for(int u=0; u<n; ++u){ for(int v=0; v<n; ++v){ } } while(!q.empty()){ int u = q.front(); q.pop(); inq.erase(u); for(auto it=iadj[u].begin(); it != iadj[u].end();){ int v = *it; if(dg[u] + dg[v] < k){ it++; continue; } m++; dg[u]++; dg[v]++; if(!inq.count(u)){ inq.ep(u); q.ep(u); } if(!inq.count(v)){ inq.ep(v); q.ep(v); } it = iadj[u].erase(it); } } return m == n*(n-1)/2; } int32_t main(){ desync(); int n, m; cin >> n >> m; vi dg(n); vvb mat(n, vb(n)); for(int i=0; i<m; ++i){ int u, v; cin >> u >> v; u--; v--; dg[u]++; dg[v]++; mat[u][v] = mat[v][u] = true; } vector<list<int> > iadj(n); for(int u=0; u<n; ++u){ for(int v=u+1; v<n; ++v){ if(mat[u][v]) continue; iadj[u].eb(v); } } int lo = 0, hi = 2*n, ans = hi; while(lo <= hi){ int mid = (lo+hi)/2; if(check(n, m, iadj, mat, dg, mid)){ ans = mid; lo = mid+1; } else hi = mid-1; } cout << ans << endl; return 0; }
1,562
630
#include "bits/stdc++.h" using namespace std; # define s(n) scanf("%d",&n) # define sc(n) scanf("%c",&n) # define sl(n) scanf("%lld",&n) # define sf(n) scanf("%lf",&n) # define ss(n) scanf("%s",n) #define R(i,n) for(int i=0;i<(n);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define FORD(i,a,b) for(int i=(a);i>=(b);i--) # define INF (int)1e9 # define EPS 1e-9 # define MOD 1000000007 typedef long long ll; int main() { int t=1; // cin >> t; while(t--){ int n,m,r,x; s(n);s(m); char a[7]; int row[n], col[n]; fill_n(row,n,0); fill_n(col,n,0); R(i,m){ ss(a); s(r); s(x); if(a[0]=='R'){ row[r-1]+=x; } else col[r-1]+=x; } int max_row=0,max_col=0; R(i,n){ if(row[i]>max_row) max_row=row[i]; if(col[i]>max_col) max_col=col[i]; } printf("%d\n",max_row + max_col ); } return 0; }
1,032
523
#include <math.h> #include "MathHelper.h" double pythagorean(float a, float b) { return sqrt(a * a + b * b); }
115
50
#include <iostream> #include <vector> #include <cstdio> using namespace std; const int MAX = 1001; int numberOfDivisors(int number) { int divisors = 2; for(int i = 2; i*i <= number; ++i) { if(number % i == 0) divisors += 2; if(i*i == number) --divisors; } return divisors; } int calculateDivisors(int naturalNumber) { int divisors; if(naturalNumber % 2 == 0 ) { divisors = numberOfDivisors(naturalNumber/2); divisors *= numberOfDivisors(naturalNumber + 1); } else { divisors = numberOfDivisors((naturalNumber + 1)/2); divisors *= numberOfDivisors(naturalNumber); } return divisors; } vector<int> maxDivisors(const int MAX) { vector<int> max_divisors(MAX, 0); max_divisors[1] = 3; int naturalNumber = 3, divisors; for(int i = 2; i < MAX; ++i) { divisors = calculateDivisors(naturalNumber); while(i >= divisors) divisors = calculateDivisors(++naturalNumber); int sum = naturalNumber*(naturalNumber + 1)/2; while(i < divisors && i < MAX) max_divisors[i++] = sum; --i; } return max_divisors; } int main() { vector<int> divisors = maxDivisors(MAX); int tests; cin >> tests; for(int i = 0; i < tests; ++i) { int n; cin >> n; cout << divisors[n] << endl; } return 0; }
1,357
499