hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d40960e250f4afb2536688a7804e145f19e73e1c | 9,716 | cpp | C++ | src/CCsharpCounter.cpp | dutchedge/Unified_Code_Count | 8c2d12942595dc11f13f36e2282e3821707b8ffd | [
"DOC"
] | 12 | 2015-06-08T16:19:33.000Z | 2020-02-11T13:40:58.000Z | src/CCsharpCounter.cpp | dutchedge/Unified_Code_Count | 8c2d12942595dc11f13f36e2282e3821707b8ffd | [
"DOC"
] | null | null | null | src/CCsharpCounter.cpp | dutchedge/Unified_Code_Count | 8c2d12942595dc11f13f36e2282e3821707b8ffd | [
"DOC"
] | 6 | 2016-09-09T11:55:19.000Z | 2020-07-08T16:04:04.000Z | //! Code counter class methods for the C# language.
/*!
* \file CCsharpCounter.cpp
*
* This file contains the code counter class methods for the C# language.
*/
#include "CCsharpCounter.h"
/*!
* Constructs a CCsharpCounter object.
*/
CCsharpCounter::CCsharpCounter()
{
classtype = CSHARP;
language_name = "C#";
isVerbatim = false;
file_extension.push_back(".cs");
directive.push_back("#define");
directive.push_back("#else");
directive.push_back("#elif");
directive.push_back("#endif");
directive.push_back("#endregion");
directive.push_back("#error");
directive.push_back("#if");
directive.push_back("#line");
directive.push_back("#region");
directive.push_back("#undef");
directive.push_back("#warning");
data_name_list.push_back("abstract");
data_name_list.push_back("bool");
data_name_list.push_back("byte");
data_name_list.push_back("char");
data_name_list.push_back("class");
data_name_list.push_back("const");
data_name_list.push_back("decimal");
data_name_list.push_back("delegate");
data_name_list.push_back("double");
data_name_list.push_back("enum");
data_name_list.push_back("event");
data_name_list.push_back("explicit");
data_name_list.push_back("extern");
data_name_list.push_back("float");
data_name_list.push_back("implicit");
data_name_list.push_back("int");
data_name_list.push_back("interface");
data_name_list.push_back("internal");
data_name_list.push_back("long");
data_name_list.push_back("namespace");
data_name_list.push_back("object");
data_name_list.push_back("operator");
data_name_list.push_back("override");
data_name_list.push_back("private");
data_name_list.push_back("protected");
data_name_list.push_back("public");
data_name_list.push_back("readonly");
data_name_list.push_back("sbyte");
data_name_list.push_back("sealed");
data_name_list.push_back("short");
data_name_list.push_back("static");
data_name_list.push_back("string");
data_name_list.push_back("struct");
data_name_list.push_back("uint");
data_name_list.push_back("ulong");
data_name_list.push_back("unsafe");
data_name_list.push_back("ushort");
data_name_list.push_back("using");
data_name_list.push_back("virtual");
data_name_list.push_back("void");
data_name_list.push_back("volatile");
exec_name_list.push_back("as");
exec_name_list.push_back("base");
exec_name_list.push_back("break");
exec_name_list.push_back("case");
exec_name_list.push_back("catch");
exec_name_list.push_back("checked");
exec_name_list.push_back("continue");
exec_name_list.push_back("default");
exec_name_list.push_back("do");
exec_name_list.push_back("else");
exec_name_list.push_back("finally");
exec_name_list.push_back("fixed");
exec_name_list.push_back("for");
exec_name_list.push_back("foreach");
exec_name_list.push_back("goto");
exec_name_list.push_back("if");
exec_name_list.push_back("lock");
exec_name_list.push_back("new");
exec_name_list.push_back("return");
exec_name_list.push_back("sizeof");
exec_name_list.push_back("stackalloc");
exec_name_list.push_back("switch");
exec_name_list.push_back("this");
exec_name_list.push_back("throw");
exec_name_list.push_back("try");
exec_name_list.push_back("typeof");
exec_name_list.push_back("unchecked");
exec_name_list.push_back("while");
math_func_list.push_back("abs");
math_func_list.push_back("cbrt");
math_func_list.push_back("ceil");
math_func_list.push_back("copysign");
math_func_list.push_back("erf");
math_func_list.push_back("erfc");
math_func_list.push_back("exp");
math_func_list.push_back("exp2");
math_func_list.push_back("expm1");
math_func_list.push_back("fabs");
math_func_list.push_back("floor");
math_func_list.push_back("fdim");
math_func_list.push_back("fma");
math_func_list.push_back("fmax");
math_func_list.push_back("fmin");
math_func_list.push_back("fmod");
math_func_list.push_back("frexp");
math_func_list.push_back("hypot");
math_func_list.push_back("ilogb");
math_func_list.push_back("ldexp");
math_func_list.push_back("lgamma");
math_func_list.push_back("llrint");
math_func_list.push_back("lrint");
math_func_list.push_back("llround");
math_func_list.push_back("lround");
math_func_list.push_back("modf");
math_func_list.push_back("nan");
math_func_list.push_back("nearbyint");
math_func_list.push_back("nextafter");
math_func_list.push_back("nexttoward");
math_func_list.push_back("pow");
math_func_list.push_back("remainder");
math_func_list.push_back("remquo");
math_func_list.push_back("rint");
math_func_list.push_back("round");
math_func_list.push_back("scalbln");
math_func_list.push_back("scalbn");
math_func_list.push_back("sqrt");
math_func_list.push_back("tgamma");
math_func_list.push_back("trunc");
trig_func_list.push_back("cos");
trig_func_list.push_back("cosh");
trig_func_list.push_back("sin");
trig_func_list.push_back("sinh");
trig_func_list.push_back("tan");
trig_func_list.push_back("tanh");
trig_func_list.push_back("acos");
trig_func_list.push_back("acosh");
trig_func_list.push_back("asinh");
trig_func_list.push_back("atanh");
trig_func_list.push_back("asin");
trig_func_list.push_back("atan");
trig_func_list.push_back("atan2");
log_func_list.push_back("log");
log_func_list.push_back("log10");
log_func_list.push_back("log1p");
log_func_list.push_back("log2");
log_func_list.push_back("logb");
cmplx_preproc_list.push_back("define");
cmplx_preproc_list.push_back("elif");
cmplx_preproc_list.push_back("else");
cmplx_preproc_list.push_back("endif");
cmplx_preproc_list.push_back("endregion");
cmplx_preproc_list.push_back("error");
cmplx_preproc_list.push_back("if");
cmplx_preproc_list.push_back("import");
cmplx_preproc_list.push_back("line");
cmplx_preproc_list.push_back("region");
cmplx_preproc_list.push_back("undef");
cmplx_preproc_list.push_back("warning");
cmplx_cyclomatic_list.push_back("if");
cmplx_cyclomatic_list.push_back("case");
cmplx_cyclomatic_list.push_back("while");
cmplx_cyclomatic_list.push_back("for");
cmplx_cyclomatic_list.push_back("foreach");
cmplx_cyclomatic_list.push_back("catch");
cmplx_cyclomatic_list.push_back("?");
}
/*!
* Perform preprocessing of file lines before counting.
*
* \param fmap list of file lines
*
* \return method status
*/
int CCsharpCounter::PreCountProcess(filemap* fmap)
{
size_t i;
bool found;
filemap::iterator fit;
for (fit = fmap->begin(); fit != fmap->end(); fit++)
{
if (fit->line.empty())
continue;
// check for parenthesis within attribute brackets [...()]
found = false;
for (i = 0; i < fit->line.length(); i++)
{
if (fit->line[i] == '[')
found = true;
else if (found)
{
if (fit->line[i] == ']')
found = false;
else if (fit->line[i] == '(' || fit->line[i] == ')')
fit->line[i] = '$';
}
}
}
return 0;
}
/*!
* Replaces up to ONE quoted string inside a string starting at idx_start.
*
* \param strline string to be processed
* \param idx_start index of line character to start search
* \param contd specifies the quote string is continued from the previous line
* \param CurrentQuoteEnd end quote character of the current status
*
* \return method status
*/
int CCsharpCounter::ReplaceQuote(string &strline, size_t &idx_start, bool &contd, char &CurrentQuoteEnd)
{
size_t idx_end, idx_quote, idx_verbatim;
char noQuoteEscapeFront = 0x00;
if (contd)
{
idx_start = 0;
if (strline[0] == CurrentQuoteEnd)
{
if (!isVerbatim || (strline.length() < 2) || (strline[1] != '"'))
{
idx_start = 1;
contd = false;
return 1;
}
}
else
strline[0] = '$';
}
else
{
// accommodate C# verbatim string (e.g. @"\")
isVerbatim = false;
idx_verbatim = strline.find_first_of("@");
if (idx_verbatim != string::npos && idx_verbatim + 1 == idx_start)
isVerbatim = true;
// handle two quote chars in some languages, both " and ' may be accepted
idx_start = FindQuote(strline, QuoteStart, idx_start, QuoteEscapeFront);
if (idx_start != string::npos)
{
idx_quote = QuoteStart.find_first_of(strline[idx_start]);
CurrentQuoteEnd = QuoteEnd[idx_quote];
}
else
{
idx_start = strline.length();
return 0;
}
}
// accommodate C# verbatim string (e.g. @"\")
if (isVerbatim) // verbatim string
idx_end = CUtil::FindCharAvoidEscape(strline, CurrentQuoteEnd, idx_start + 1, noQuoteEscapeFront);
else
idx_end = CUtil::FindCharAvoidEscape(strline, CurrentQuoteEnd, idx_start + 1, QuoteEscapeFront);
if (idx_end == string::npos)
{
idx_end = strline.length() - 1;
strline.replace(idx_start + 1, idx_end - idx_start, idx_end - idx_start, '$');
contd = true;
idx_start = idx_end + 1;
}
else
{
if ((isVerbatim && (strline.length() > idx_end + 1) && (strline[idx_end+1] == '"')) ||
((QuoteEscapeRear) && (strline.length() > idx_end + 1) && (strline[idx_end+1] == QuoteEscapeRear)))
{
strline[idx_end] = '$';
strline[idx_end+1] = '$';
}
else
{
isVerbatim = false;
contd = false;
strline.replace(idx_start + 1, idx_end - idx_start - 1, idx_end - idx_start - 1, '$');
idx_start = idx_end + 1;
}
}
return 1;
}
/*!
* Constructs a CCsharpHtmlCounter object.
*/
CCsharpHtmlCounter::CCsharpHtmlCounter()
{
classtype = CSHARP_HTML;
language_name = "C#/HTML";
file_extension.clear();
file_extension.push_back(".*cshtm");
}
/*!
* Constructs a CCsharpXmlCounter object.
*/
CCsharpXmlCounter::CCsharpXmlCounter()
{
classtype = CSHARP_XML;
language_name = "C#/XML";
file_extension.clear();
file_extension.push_back(".*csxml");
}
/*!
* Constructs a CCsharpAspCounter object.
*/
CCsharpAspCounter::CCsharpAspCounter()
{
classtype = CSHARP_ASP_S;
language_name = "C#/ASPNET";
file_extension.clear();
file_extension.push_back(".*csasps");
}
| 28.576471 | 104 | 0.729621 | dutchedge |
d40af53711c3b295b82c686813acf65244981432 | 2,638 | cpp | C++ | emulator/src/devices/bus/cpc/cpcexp.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/devices/bus/cpc/cpcexp.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/devices/bus/cpc/cpcexp.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Barry Rodewald
/*
* cpcexp.c -- Amstrad CPC Expansion port
*
* Created on: 16/07/2011
*
*/
#include "emu.h"
#include "cpcexp.h"
//**************************************************************************
// GLOBAL VARIABLES
//**************************************************************************
DEFINE_DEVICE_TYPE(CPC_EXPANSION_SLOT, cpc_expansion_slot_device, "cpc_expansion_slot", "Amstrad CPC expansion port")
//**************************************************************************
// DEVICE CPC_EXPANSION CARD INTERFACE
//**************************************************************************
device_cpc_expansion_card_interface::device_cpc_expansion_card_interface(const machine_config &mconfig, device_t &device)
: device_slot_card_interface(mconfig,device)
, m_rom_sel(0)
{
}
device_cpc_expansion_card_interface::~device_cpc_expansion_card_interface()
{
}
//**************************************************************************
// LIVE DEVICE
//**************************************************************************
cpc_expansion_slot_device::cpc_expansion_slot_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, CPC_EXPANSION_SLOT, tag, owner, clock)
, device_slot_interface(mconfig, *this)
, m_out_irq_cb(*this)
, m_out_nmi_cb(*this)
, m_out_reset_cb(*this)
, m_out_romdis_cb(*this)
, m_out_rom_select(*this)
, m_card(nullptr)
{
}
cpc_expansion_slot_device::~cpc_expansion_slot_device()
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void cpc_expansion_slot_device::device_start()
{
m_card = dynamic_cast<device_cpc_expansion_card_interface *>(get_card_device());
// resolve callbacks
m_out_irq_cb.resolve_safe();
m_out_nmi_cb.resolve_safe();
m_out_reset_cb.resolve_safe();
m_out_romdis_cb.resolve_safe();
m_out_rom_select.resolve_safe();
}
//-------------------------------------------------
// device_reset - device-specific reset
//-------------------------------------------------
void cpc_expansion_slot_device::device_reset()
{
}
WRITE_LINE_MEMBER( cpc_expansion_slot_device::irq_w ) { m_out_irq_cb(state); }
WRITE_LINE_MEMBER( cpc_expansion_slot_device::nmi_w ) { m_out_nmi_cb(state); }
WRITE_LINE_MEMBER( cpc_expansion_slot_device::reset_w ) { m_out_reset_cb(state); }
WRITE_LINE_MEMBER( cpc_expansion_slot_device::romdis_w ) { m_out_romdis_cb(state); }
WRITE8_MEMBER( cpc_expansion_slot_device::rom_select ) { m_out_rom_select(data); }
| 28.989011 | 133 | 0.584913 | rjw57 |
d40c7c2597e6bd0f2c60fbcb6c61c868c7ab704d | 34,479 | hpp | C++ | externals/source/testdog/pack/inc/testdog/runner.hpp | skarab/coffee-master | 6c3ff71b7f15735e41c9859b6db981b94414c783 | [
"MIT"
] | null | null | null | externals/source/testdog/pack/inc/testdog/runner.hpp | skarab/coffee-master | 6c3ff71b7f15735e41c9859b6db981b94414c783 | [
"MIT"
] | null | null | null | externals/source/testdog/pack/inc/testdog/runner.hpp | skarab/coffee-master | 6c3ff71b7f15735e41c9859b6db981b94414c783 | [
"MIT"
] | null | null | null | //---------------------------------------------------------------------------
// PROJECT : TEST-DOG
// FILENAME : testdog/runner.hpp
// DESCRIPTION : Test runner class.
// COPYRIGHT : Andy Thomas (C) 2010
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// LICENSE
//---------------------------------------------------------------------------
// This file is part of the "TEST-DOG" program.
// TEST-DOG 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 3 of the License, or
// (at your option) any later version.
// TEST-DOG 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 TEST-DOG. If not, see <http://www.gnu.org/licenses/>.
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// HEADER GUARD
//---------------------------------------------------------------------------
#ifndef TDOG_RUNNER_H
#define TDOG_RUNNER_H
//---------------------------------------------------------------------------
// INCLUDES
//---------------------------------------------------------------------------
#include "private/basic_test.hpp"
#include "private/test_case.hpp"
#include <string>
#include <vector>
#include <map>
#include <ctime>
#include <ostream>
//---------------------------------------------------------------------------
// DOCUMENTATION
//---------------------------------------------------------------------------
//! \file testdog/runner.hpp
//! \brief This file provides the testdog::runner class and associated types.
//! \sa testdog::runner
//---------------------------------------------------------------------------
// DECLARATIONS
//---------------------------------------------------------------------------
// Namespace
namespace testdog {
//! \brief An enumerated type used to designate the style of test run reports.
//! \details Test reports are subdivided according to their "log level", and
//! are considered to be verbose or standard.
//!
//! Standard reports contain only summary information pertaining to test
//! cases which pass, but further details are provided for those tests which
//! fail. Whereas verbose reports contain the same detailed trace information
//! irrespective of whether the test case passed or not.
//! \sa runner::set_report_style(), runner::generate_report()
enum report_style_t
{
RS_NONE = 0, //!< None (no report is generated).
RS_TEXT_STD, //!< Human readable test report.
RS_TEXT_VERBOSE, //!< Human readable test report (verbose).
RS_XML, //!< XML test report (verbose).
RS_HTML_STD, //!< HTML test report.
RS_HTML_VERBOSE, //!< HTML test report (verbose).
RS_HTML_SUMMARY, //!< HTML test report (summary only).
};
//! \brief An enumerated type used to designate what tests should be run.
//! \sa runner::run()
enum run_scope_t
{
RUN_NONE = 0, //!< Run none (no tests were run).
RUN_ALL, //!< Run all tests.
RUN_SUITE, //!< Run only the specified test suite.
RUN_TEST //!< Run only the specified test case.
};
//! \brief An enumerated type used to designate a required statistic from
//! the last test run.
//! \sa runner::stat_result()
enum result_stat_t
{
ST_RAN = 0, //!< Number of tests executed in the test run.
ST_SKIPPED, //!< Number of tests skipped (i.e. were disabled).
ST_PASSED, //!< Number of tests that passed.
ST_FAILED, //!< Number of tests that failed.
ST_ERRORS, //!< Number of tests which implementation errors.
ST_PASS_RATE //!< Percentage of tests that passed.
};
//! \brief An enumerated type used to provide the a test case result.
//! \details The runner::test_result() method can be used to query the
//! result state of any test in the runner.
//! \sa runner::test_result()
enum test_result_t
{
TR_NOT_EXIST = 0, //!< The test case does not exist in the runner.
TR_NOT_RUN, //!< Test was not run.
TR_PASSED, //!< All test conditions passed OK.
TR_FAILED, //!< One or more test conditions failed.
TR_TEST_ERROR //!< The test failed because of a possible implementation error.
};
// Forward declaration
class basic_reporter;
//---------------------------------------------------------------------------
// MACROS
//---------------------------------------------------------------------------
//! \brief Synonym for: testdog::runner::global()
//! \details This macro is provided for convenience. The following two
//! lines of code are equivalent:
//!
//! Example:
//!
//! \code
//! // 1. Run all tests
//! int rslt = testdog::runner::global().run();
//! ...
//! // 2. Run all tests
//! int rslt = TDOG().run();
//! \endcode
//! \sa runner::global()
#define TDOG() testdog::runner::global()
//---------------------------------------------------------------------------
// CLASS runner
//---------------------------------------------------------------------------
//! \class runner
//! \brief The runner class is used to run test cases and collate
//! result information.
//! \details The runner cannot be instantiated directly, rather access to a
//! global instance is granted through its singleton method: runner::global().
class runner
{
protected:
// Protected properties
std::string m_project_name;
std::string m_project_version;
report_style_t m_report_style;
std::string m_report_charset;
std::string m_html_report_stylesheet;
bool m_report_loc;
int m_text_report_break_width;
bool m_html_report_author_col;
int m_tests_ran;
int m_tests_skipped;
int m_tests_passed;
int m_tests_failed;
int m_test_errors;
run_scope_t m_run_scope;
std::time_t m_start_time;
std::time_t m_end_time;
bool m_contains_suites;
int m_global_time_limit;
std::string m_prev_suite_name;
std::vector<basic_test*> m_basic_tests;
typedef std::map<std::string, bool> suite_state_t;
suite_state_t m_suite_state_map;
// Protected methods
basic_test* m_find_tc(const std::string& tname) const;
bool m_suite_enabled(const std::string& sname) const;
basic_reporter* m_create_reporter(report_style_t rs) const;
void m_clear_results();
// Hidden contructor
runner();
public:
//! @name Class Instantiation
//! @{
//! \brief Destructor.
virtual ~runner();
//! \brief Singleton access
//! \details There is no public constructor for this class, and all
//! access is via this singleton method to a single class instance.
//!
//! Example:
//!
//! \code
//! // Run all tests
//! testdog::runner::global().run();
//! \endcode
//!
//! \return Reference to global instance
static runner& global();
static void create();
static void destroy();
//! @}
//! @name Project Information
//! @{
//! \brief Returns the user supplied name of the project under test.
//! \details The project name is an optional string which is displayed
//! in test report outputs.
//! \return Project name string
//! \sa set_project_name(), project_version()
std::string project_name() const;
//! \brief Sets the name of the project under test.
//! \details The project name is an optional string which is displayed
//! in test report outputs.
//!
//! Example:
//! \code
//! testdog::runner().global().set_project_name("smppd");
//! \endcode
//! \param[in] pname Project name
//! \sa project_name(), set_project_version()
void set_project_name(const std::string& pname);
//! \brief Returns the user supplied version string for the test project.
//! \details The project version is an optional string which is displayed
//! in test report outputs.
//! \return Project version string
//! \sa set_project_version(), project_name()
std::string project_version() const;
//! \brief Sets the version string of the project under test.
//! \details The project version is an optional string which is displayed
//! in test report outputs.
//!
//! Example:
//! /code
//! testdog::runner().global().set_project_version("3.1.6");
//! /endcode
//! \param[in] ver Project version string
//! \sa project_version(), set_project_name()
void set_project_version(const std::string& ver);
//! @}
//! @name Test Registration
//! @{
//! \brief Explicitly registers a test case instance with the runner.
//! \details Normally there is no need to call this method, as test cases
//! automatically register themselves with the global runner instance
//! when they are instantiated.
//!
//! However, it is possible to disable the automatic registration of
//! test cases by pre-defining the TDOG_DISABLE_AUTO_REG macro. In this case,
//! the register_test() method must be used to add tests to the runner
//! explicitly. In addition, the TDOG_TEST_REFINST() macro must be used to
//! reference the underlying test case implementation instance, as follows:
//!
//! \code
//! #define TDOG_DISABLE_AUTO_REG
//! #include <testdog/unit_test.hpp>
//!
//! // Define test
//! TDOG_TEST_CASE(some_test)
//! {
//! ...
//! }
//!
//! int main(int argc, char **argv)
//! {
//! // Explicitly register the test
//! testdog::runner::global().register_test(TDOG_TEST_REFINST(some_test));
//! ...
//! }
//! \endcode
//!
//! If the test case belongs within a test suite, you should use the
//! the suite name as a namespaced prefix. For example:
//!
//! \code
//! testdog::runner::global().register_test(TDOG_TEST_REFINST(suite_name::some_test));
//! \endcode
//!
//! With self-registration, tests are run in the order that they are
//! declared. One possible benefit of registering tests explicitly, therefore,
//! is that it provides some control over the run order.
//! \param[in] tc Underlying test instance
//! \sa TDOG_TEST_REFINST(), registered_count()
void register_test(test_case& tc);
//! \overload
//! \param[in] tc Underlying test instance
void register_test(basic_test& tc);
//! \brief Returns the number of tests registered in the runner.
//! \return Number of tests
//! \sa register_test(), stat_result()
int registered_count() const;
//! \brief Clears all tests registered with the runner.
//! \sa register_test()
void clear_tests();
//! \brief Returns whether the test case with the given name exists.
//! \details The test name should be fully qualified with the suite name.
//!
//! For example:
//! \code
//! bool ex = testdog::runner::global().test_exists("SUITE_NAME::TEST_NAME");
//! \endcode
//!
//! Test names are case sensitive.
//!
//! If the test case is not part of a suite, just the test name should
//! be used.
//! \param[in] tname Test case name
//! \return Boolean result
//! \sa suite_exists()
bool test_exists(const std::string& tname) const;
//! \brief Returns whether the test suite with the given name exists.
//! \details Suite names are case sensitive.
//! \param[in] sname Suite name
//! \return Boolean result
//! \sa test_exists(), contains_suites()
bool suite_exists(const std::string& sname) const;
//! \brief Returns true if one or more tests were declared within
//! a test suite.
//! \return Boolean result
//! \sa suite_exists()
bool contains_suites() const;
//! \brief Enumerates the fully qualified names of all test cases registered
//! with the runner.
//! \details The results are returned using "rslt_out", which
//! supplies a vector array of std::string. The rslt_out array will
//! first be emptied before being re-populated with test case names.
//!
//! Test names are provided in the order which they were originally
//! registered, which is also their run order.
//! \param[out] rslt_out A vector array of strings used to retrieve results
//! \return A reference to rslt_out
//! \sa enum_suite_names()
std::vector<std::string>& enum_test_names(
std::vector<std::string>& rslt_out) const;
//! \brief Enumerates the names of all test suites in the runner.
//! \details The results are returned using "rslt_out", which
//! supplies a vector array of std::string. The rslt_out array will
//! first be emptied before being repopulated with test suite names.
//!
//! An empty string will be used to designate the default suit, i.e.
//! where test cases are declared outside of a test suite.
//! \param[out] rslt_out A vector array of strings used to retrieve results
//! \return A reference to rslt_out
//! \sa enum_test_names()
std::vector<std::string>& enum_suite_names(
std::vector<std::string>& rslt_out) const;
//! @}
//! @name Disabling Tests
//! @{
//! \brief Returns whether a test case with the given name is enabled.
//! \details Tests which have been disabled will not be executed by the runner.
//!
//! Use the fully qualified test name. For example:
//!
//! \code
//! bool en = testdog::runner::global().test_enabled("SUITE_NAME::TEST_NAME");
//! \endcode
//!
//! Test names are case sensitive.
//!
//! If the test case is not part of a suite, just the test name should be
//! used without any namespace.
//!
//! The default enabled state for tests is true. The result will be false
//! if a test of the given name does not exist.
//!
//! Note. The enabled state of test cases and their suites are independent,
//! and both must be enabled for a test to run.
//! \param[in] tname Test case name
//! \return Boolean result value
//! \sa set_test_enabled(), suit_enabled(), test_exists()
bool test_enabled(const std::string& tname) const;
//! \brief Allows an individual test case with the given name to be disabled
//! (or re-enabled).
//! \details Tests which have been disabled will not be executed by the runner.
//!
//! Use the fully qualified test name. For example:
//!
//! \code
//! testdog::runner::global().set_test_enabled("SUITE_NAME::TEST_NAME", false);
//! \endcode
//!
//! Test names are case sensitive.
//!
//! If the test case is not part of a suite, just the test name should be
//! used without any namespace.
//!
//! The default enabled state for tests is true. This call does nothing if
//! a test of the given name does not exist.
//!
//! Note. The enabled state of test cases and their suites are independent,
//! and both must be enabled for a test to run.
//! \param[in] tname Test case name
//! \param[in] e Enabled flag
//! \sa test_enabled(), set_all_tests_enabled(), set_suit_enabled(),
//! test_exists()
void set_test_enabled(const std::string& tname, bool e);
//! \brief Sets the enabled states for all tests (in all suites).
//! \param[in] e Enabled flag
//! \sa set_all_suites_enabled(), set_test_enabled()
void set_all_tests_enabled(bool e);
//! \brief Returns whether the test suite with the given name is enabled.
//! \details Tests belonging to a disabled suite will not be executed by
//! the runner.
//!
//! When calling this method, use the fully qualified test name. For example:
//!
//! \code
//! bool en = testdog::runner::global().suite_enabled("SUITE_NAME");
//! \endcode
//!
//! The default enabled state for suites is true. Suite names are case
//! sensitive. The result will be false if a suite of the given name does
//! not exist.
//!
//! Note. The enabled state of test cases and their suites are independent,
//! and both must be enabled for a test to run.
//! \param[in] sname Suite name
//! \return Boolean result value
//! \sa set_suite_enabled(), test_enabled(), suit_exists()
bool suite_enabled(const std::string& sname) const;
//! \brief Allows the test suite with the given name to be disabled
//! (or re-enabled).
//! \details Tests belonging to a disabled suite will not be executed by
//! the runner.
//!
//! When calling this method, use the fully qualified test name. For example:
//!
//! \code
//! bool en = testdog::runner::global().suite_enabled("SUITE_NAME");
//! \endcode
//!
//! The default enabled state for suites is true. Suite names are case
//! sensitive. This call does nothing if a suite of the given name does
//! not exist. The default suite state can be set by using an empty string
//! ("") for its name.
//!
//! Note. The enabled state of test cases and their suites are independent,
//! and both must be enabled for a test to run.
//! \param[in] sname Suite name
//! \param[in] e Enabled flag
//! \sa suite_enabled(), set_all_suites_enabled(), set_test_enabled(),
//! suite_exists()
void set_suite_enabled(const std::string& sname, bool e);
//! \brief Sets the enabled states for all test suites.
//! \param[in] e Enabled flag
//! \sa set_all_tests_enabled(), set_suite_enabled()
void set_all_suites_enabled(bool e);
//! @}
//! @name Running Tests
//! @{
//! \brief Run all tests, or just those specified.
//! \details The "scope" parameter defines the scope of the test run,
//! and may be one of the following values:
//! - RUN_NONE - Run none (no tests were run).
//! - RUN_ALL - Run all tests.
//! - RUN_SUITE - Run only the specified test suite.
//! - RUN_TEST - Run only the specified test case.
//! .
//! The name parameter supplies the suite name if the scope is RUN_SUITE,
//! or the fully qualified test name if RUN_TEST. It is ignored for
//! the RUN_ALL scope.
//!
//! The run() method does nothing if RUN_NONE is specified--this is really
//! a result value for use with the run_scope() method.
//!
//! Both scope and name have default values so that calling run() without
//! any parameters will execute all tests. For example, to run all tests
//! simply call:
//!
//! \code
//! return testdog::runner::global().run();
//! \endcode
//!
//! To run an individual test, call:
//!
//! \code
//! testdog::runner::global().run(RUN_TEST, "SUITE_NAME::TEST_NAME");
//! \endcode
//!
//! To run a single suite, use RUN_SUITE and supply the suite name. Use
//! an empty string to run only the tests in the default suite, i.e. those
//! tests declared outside of any TDOG_TEST_SUITE() macro.
//!
//! Test and suite names are case sensitive.
//!
//! The return value gives the number of test cases which failed, or had
//! errors. The value will be 0 if all test cases ran successfully without
//! asserting failures or test errors. If, however, no tests were run,
//! the return value will be -1, rather than 0. This distinguishes a
//! successful test run from one that doesn't actually test anything.
//! This may occur if all test cases are disabled or if no
//! tests have been registered with the runner.
//! \return Number of test failures, or -1 if no tests performed
//! \param[in] scope Scope of tests to run
//! \param[in] name Name of suite or individual test case
//! \sa test_result(), stat_result(), run_scope()
int run(run_scope_t scope = RUN_ALL, const std::string& name = "");
//! \brief Returns the "scope" used in the last call to the run()
//! method.
//! \details If run() was never called, the return value is RUN_NONE.
//! \return Last run scope value
//! \sa run()
run_scope_t run_scope() const;
//! \brief Returns the global time limit for test cases in seconds.
//! \details The global test contraint is the maximum amount of time
//! that individual test cases can take to complete.
//! If any test case takes longer than this value, it will be deemed to
//! have failed. A value of 0, the default, disables the global time
//! constaint.
//!
//! Time constraints may also be applied to test cases on an individual
//! basis, and where a test case has its a local time limit defined, it will
//! be used in preference to the global one.
//! \return Time limit applied to all test cases
//! \sa set_global_time_limit()
int global_time_limit() const;
//! \brief Sets the global time limit for test cases in seconds.
//! \details The global test contraint is the maximum amount of time
//! that individual test cases can take to complete.
//! If any test case takes longer than this value, it will be deemed to
//! have failed. A value of 0, the default, disables the global time
//! constaint.
//!
//! Time constraints may also be applied to test cases on an individual
//! basis, and where a test case has its a local time limit defined, it will
//! be used in preference to the global one.
//! \param[in] gc_sec Time limit in seconds
//! \sa global_time_limit()
void set_global_time_limit(int gc_sec);
//! @}
//! @name Generating Test Reports
//! @{
//! \brief Returns the report style written to STDOUT during the test run.
//! \details This setting controls the style of this report, which can be
//! one of:
//! - RS_NONE - None (no report is generated).
//! - RS_TEXT_STD - Human readable test report.
//! - RS_TEXT_VERBOSE - Human readable test report (verbose).
//! - RS_XML - XML test report (verbose).
//! - RS_HTML_STD - HTML test report.
//! - RS_HTML_VERBOSE - HTML test report (verbose).
//! - RS_HTML_SUMMARY - HTML test report (summary only).
//! .
//! A report is generated to STDOUT when one or more test cases are
//! run. The default value is RS_TEXT_STD.
//!
//! Test reports are subdivided according to their "log level", and
//! are considered to be verbose or standard.
//!
//! Standard reports contain only summary information pertaining to test
//! cases which pass, but further details are provided for those tests which
//! fail. Whereas verbose reports contain the same detailed trace information
//! irrespective of whether the test case passed or not.
//! \return Stdout reporting style
//! \sa set_report_style(), generate_report(), run()
report_style_t report_style() const;
//! \brief Set the report style written to STDOUT during the test run.
//! \details This setting controls the style of this report, which can be
//! one of:
//! - RS_NONE - None (no report is generated).
//! - RS_TEXT_STD - Human readable test report.
//! - RS_TEXT_VERBOSE - Human readable test report (verbose).
//! - RS_XML - XML test report (verbose).
//! - RS_HTML_STD - HTML test report.
//! - RS_HTML_VERBOSE - HTML test report (verbose).
//! - RS_HTML_SUMMARY - HTML test report (summary only).
//! .
//! A report is generated to STDOUT when one or more tests are
//! run. The default value is RS_TEXT_STD.
//!
//! Example:
//!
//! \code
//! // Use verbose report
//! testdog::runner::global().set_report_style(testdog::RS_TEXT_VERBOSE);
//! \endcode
//!
//! Test reports are subdivided according to their "log level", and
//! are considered to be verbose or standard.
//!
//! Standard reports contain only summary information pertaining to test
//! cases which pass, but further details are provided for those tests which
//! fail. Whereas verbose reports contain the same detailed trace information
//! irrespective of whether the test case passed or not.
//! \param[in] rs Report style
//! \sa report_style(), generate_report(), run()
void set_report_style(report_style_t rs);
//! \brief Generates a test report pertaining to the last test run and writes
//! it to the supplied output stream.
//! \details The report is generated according to the style rs, and
//! is useful where test reports in multiple formats are required. Note that
//! the report generated with this method would be in addition to that
//! written to STDOUT as the the test runs.
//!
//! Here's an example of where a text style report is written to the STDOUT as
//! the tests are executed, and a further XML report is written to file
//! after the test run.
//!
//! \code
//! #include <testdog/unit_test.hpp>
//! ...
//!
//! int main(int argc, char **argv)
//! {
//! // Set default STDOUT report
//! testdog::set_report_style(testdog::RS_TEXT_VERBOSE);
//!
//! // Run all tests
//! int rslt = testdog::runner::global().run();
//!
//! // Generate XML report file
//! std::ofstream file_out;
//! file_out.open("test_report.xml");
//! testdog::runner::global().generate_report(file_out, testdog::RS_XML);
//! file_out.close();
//!
//! return rslt;
//! }
//! \endcode
//!
//! Unlike reports normally written to STDOUT during the test run,
//! reports generated with a call to generate_report() are not progressive.
//! I.e. the report will be realized only after the test run has fully
//! completed.
//!
//! The generate_report() method does nothing if passed the report style
//! value RS_NONE.
//! \param[in,out] ro Output stream
//! \param[in] rs Report style
//! \return Reference to output stream
//! \sa set_report_style()
std::ostream& generate_report(std::ostream& ro, report_style_t rs) const;
//! \brief Returns the test report character set encoding.
//! \details This is a short string specifying a valid character set encoding
//! for use in generating XML and HTML test reports. The value supplied is
//! used simply to populate the "charset" field of XML and HTML documents.
//! Valid examples include, "utf-8" and "iso-8859-1".
//!
//! The default value is an empty string which leaves the field unspecified.
//! \return Report character set encoding
//! \sa set_report_charset(), html_report_stylesheet(), report_style()
std::string report_charset() const;
//! \brief Sets the test report character set encoding.
//! \details This is a short string specifying a valid character set encoding
//! for use in generating XML and HTML test reports. The value supplied is
//! used simply to populate the "charset" field of XML and HTML documents.
//! Valid examples include, "utf-8" and "iso-8859-1".
//!
//! The default value is an empty string which leaves the field unspecified.
//! \param[in] cs Report character set encoding
//! \sa report_charset(), set_html_report_stylesheet(), set_report_style()
void set_report_charset(const std::string& cs);
//! \brief Returns whether filename and line number information is included
//! in test reports or not.
//! \details The default is true.
//! \return Boolean result value
//!\sa set_report_loc(), report_style()
bool report_loc() const;
//! \brief Sets whether filenames and line number information is included
//! in test reports or not.
//! \details The default is true.
//! \param[in] l Location information switch
//!\sa set_report_loc(), report_style()
void set_report_loc(bool l);
//! \brief Returns the number of '-' characters used to create a
//! 'breaker line' in the text reporting style.
//! \details A 'breaker line' is a sequence of '-' characters used to create
//! a visual separator in text report outputs. This setting applies only
//! to the RS_TEXT_STD and RS_TEXT_VERBOSE report styles.
//!
//! A value of 0 will disable the appearence of breaker lines in the output.
//! \return Number of characters
//! \sa set_text_report_break_width(), report_style()
int text_report_break_width() const;
//! \brief Sets the number of '-' characters used to create a
//! 'breaker line' in the text reporting style.
//! \details A 'breaker line' is a sequence of '-' characters used to create
//! a visual separator in text report outputs. This setting applies only
//! to the RS_TEXT_STD and RS_TEXT_VERBOSE report style.
//!
//! A value of 0 will disable the appearence of breaker lines in the output.
//! \param[in] bw Break width (num of chars)
//! \sa text_report_break_width(), set_report_style()
void set_text_report_break_width(int bw);
//! \brief Gets the stylesheet name for HTML test reports.
//! \details The field is used to populate the stylesheet field when
//! generating HTML test reports. It is not used for other reports.
//!
//! The default value is an empty string which means that HTML reports do
//! not use a stylesheet.
//! \return Stylesheet name
//! \sa set_html_report_stylesheet(), report_charset(), report_style()
std::string html_report_stylesheet() const;
//! \brief Sets the external stylesheet filename for HTML test reports.
//! \details The field is used to populate the stylesheet field when
//! generating HTML test reports. It is not used for other reports.
//!
//! Example:
//!
//! \code
//! // Supply the path of a local stylesheet
//! testdog::runner::global().set_stylesheet("./styles.css");
//! \endcode
//!
//! This can be used to override the document's styles.
//!
//! The default value is an empty string which means that HTML reports do
//! not use an external stylesheet.
//! \param[in] ss Stylesheet filename
//! \sa html_report_stylesheet(), set_report_charset(), set_report_style()
void set_html_report_stylesheet(const std::string& ss);
//! \brief Returns whether the HTML reports have an "author" column in
//! the result tables.
//! \details In multi-author environments, it is possible to associate
//! author names with test cases. This setting controls whether a separate
//! column is used for author names in in HTML reports tables.
//!
//! This setting applies to the RS_HTML_STD and RS_HTML_VERBOSE and
//! RS_HTML_SUMMARY report styles only. The default value is true.
//! \return Author flag
//! \sa set_html_report_author_col(), text_report_break_width(), report_style()
bool html_report_author_col() const;
//! \brief Sets whether the HTML reports have an "author" column in
//! the result tables.
//! \details In multi-author environments, it is possible to associate
//! author names with test cases. This setting controls whether a separate
//! column is used for author names in in HTML reports tables.
//!
//! This setting applies to the RS_HTML_STD and RS_HTML_VERBOSE and
//! RS_HTML_SUMMARY report styles only. The default value is true.
//! \param[in] a Author flag
//! \sa html_report_author_col(), set_text_report_break_width(),
//! set_report_style()
void set_html_report_author_col(bool a);
//! @}
//! @name Accessing Test Statistics
//! @{
//! \brief Returns a statistical result for the last test run.
//! \details The result will pertain to the following input values:
//! - ST_RAN - Number of tests executed in the test run.
//! - ST_SKIPPED - Number of tests skipped (i.e. were disabled).
//! - ST_PASSED - Number of tests that passed.
//! - ST_FAILED - Number of tests that failed.
//! - ST_ERRORS - Number of tests which implementation errors.
//! - ST_PASS_RATE - Percentage of tests that passed.
//! .
//! The return value will be zero if no test run was performed prior to
//! calling this method, or -1 if the input value is invalid.
//! \param[in] st Required statistic
//! \return Statistical count
//! \sa test_result(), registered_count()
int stat_result(result_stat_t st) const;
//! \brief Returns the state of a given test case.
//! \details Given a test name, this method returns one of the following
//! values:
//! - TR_NOT_RUN - Test was not run.
//! - TR_PASSED - All test conditions passed OK.
//! - TR_FAILED - One or more test conditions failed.
//! - TR_TEST_ERROR - The test failed because of a possible implementation error.
//! .
//! If the test case was declared within a test suite, the suite
//! name should prefix the test name with "::" as the separator. If the test
//! case is not part of a suite, just the test name should be used.
//!
//! Example:
//! \code
//! test_result_t rslt = testdog::runner::global().test_result("SUITE_NAME::TEST_NAME");
//! \endcode
//!
//! Test names are case sensitive.
//! \param[in] tname Test case name
//! \return Test result state
//! \sa stat_result()
test_result_t test_result(const std::string& tname) const;
//! \brief Returns the date/time when the last test run started.
//! \details The result is in the form of std::time_t and accurate
//! only to the second.
//!
//! If no tests have been run, or the clear_results() method
//! was called, the return value is zero.
//! \return Test run start time
//! \sa end_time(), test_duration()
std::time_t start_time() const;
//! \brief Returns the date/time when the last test run completed.
//! \details The result is in the form of std::time_t and accurate
//! only to the second.
//!
//! If no tests have been run, or the clear_results() method
//! was called, the return value is zero.
//! \return Test run end time
//! \sa start_time(), duration()
std::time_t end_time() const;
//! \brief Returns the total duration of the last test run in seconds.
//! \details If no tests have been run, or the clear_results() method
//! was called, the return value is zero.
//! \return Duration of the test run
//! \sa start_time(), end_time()
int duration() const;
//! @}
};
//---------------------------------------------------------------------------
} // namespace
#endif // HEADER GUARD
//---------------------------------------------------------------------------
| 40.326316 | 91 | 0.638215 | skarab |
d40e360b49c504fb7af840b42d9928426493f04a | 17,140 | cpp | C++ | src/Magnum/Implementation/FramebufferState.cpp | costashatz/magnum | 8f87ca92334b326a54d27789f370fd8556d557de | [
"MIT"
] | null | null | null | src/Magnum/Implementation/FramebufferState.cpp | costashatz/magnum | 8f87ca92334b326a54d27789f370fd8556d557de | [
"MIT"
] | null | null | null | src/Magnum/Implementation/FramebufferState.cpp | costashatz/magnum | 8f87ca92334b326a54d27789f370fd8556d557de | [
"MIT"
] | null | null | null | /*
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 "FramebufferState.h"
#include "Magnum/Context.h"
#include "Magnum/Extensions.h"
#include "Magnum/Renderbuffer.h"
#include "State.h"
namespace Magnum { namespace Implementation {
constexpr const Range2Di FramebufferState::DisengagedViewport;
FramebufferState::FramebufferState(Context& context, std::vector<std::string>& extensions): readBinding{0}, drawBinding{0}, renderbufferBinding{0}, maxDrawBuffers{0}, maxColorAttachments{0}, maxRenderbufferSize{0},
#if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2))
maxSamples{0},
#endif
#ifndef MAGNUM_TARGET_GLES
maxDualSourceDrawBuffers{0},
#endif
viewport{DisengagedViewport}
{
/* Create implementation */
#ifndef MAGNUM_TARGET_GLES
if(context.isExtensionSupported<Extensions::GL::ARB::direct_state_access>()) {
extensions.emplace_back(Extensions::GL::ARB::direct_state_access::string());
createImplementation = &Framebuffer::createImplementationDSA;
createRenderbufferImplementation = &Renderbuffer::createImplementationDSA;
} else
#endif
{
createImplementation = &Framebuffer::createImplementationDefault;
createRenderbufferImplementation = &Renderbuffer::createImplementationDefault;
}
/* DSA/non-DSA implementation */
#ifndef MAGNUM_TARGET_GLES
if(context.isExtensionSupported<Extensions::GL::ARB::direct_state_access>()) {
/* Extension added above */
checkStatusImplementation = &AbstractFramebuffer::checkStatusImplementationDSA;
clearIImplementation = &AbstractFramebuffer::clearImplementationDSA;
clearUIImplementation = &AbstractFramebuffer::clearImplementationDSA;
clearFImplementation = &AbstractFramebuffer::clearImplementationDSA;
clearFIImplementation = &AbstractFramebuffer::clearImplementationDSA;
drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationDSA;
drawBufferImplementation = &AbstractFramebuffer::drawBufferImplementationDSA;
readBufferImplementation = &AbstractFramebuffer::readBufferImplementationDSA;
copySub1DImplementation = &AbstractFramebuffer::copySub1DImplementationDSA;
copySub2DImplementation = &AbstractFramebuffer::copySub2DImplementationDSA;
copySubCubeMapImplementation = &AbstractFramebuffer::copySubCubeMapImplementationDSA;
copySub3DImplementation = &AbstractFramebuffer::copySub3DImplementationDSA;
renderbufferImplementation = &Framebuffer::renderbufferImplementationDSA;
/* The 1D implementation uses the same function as the layered attachment */
texture1DImplementation = &Framebuffer::textureImplementationDSA;
/* DSA doesn't have texture target parameter so we need to use different
function to specify cube map face */
texture2DImplementation = &Framebuffer::texture2DImplementationDSA;
textureImplementation = &Framebuffer::textureImplementationDSA;
textureCubeMapImplementation = &Framebuffer::textureCubeMapImplementationDSA;
textureLayerImplementation = &Framebuffer::textureLayerImplementationDSA;
renderbufferStorageImplementation = &Renderbuffer::storageImplementationDSA;
} else if(context.isExtensionSupported<Extensions::GL::EXT::direct_state_access>()) {
extensions.emplace_back(Extensions::GL::EXT::direct_state_access::string());
checkStatusImplementation = &AbstractFramebuffer::checkStatusImplementationDSAEXT;
/* I don't bother with EXT_DSA anymore */
clearIImplementation = &AbstractFramebuffer::clearImplementationDefault;
clearUIImplementation = &AbstractFramebuffer::clearImplementationDefault;
clearFImplementation = &AbstractFramebuffer::clearImplementationDefault;
clearFIImplementation = &AbstractFramebuffer::clearImplementationDefault;
drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationDSAEXT;
drawBufferImplementation = &AbstractFramebuffer::drawBufferImplementationDSAEXT;
readBufferImplementation = &AbstractFramebuffer::readBufferImplementationDSAEXT;
copySub1DImplementation = &AbstractFramebuffer::copySub1DImplementationDSAEXT;
copySub2DImplementation = &AbstractFramebuffer::copySub2DImplementationDSAEXT;
copySubCubeMapImplementation = &AbstractFramebuffer::copySub2DImplementationDSAEXT;
copySub3DImplementation = &AbstractFramebuffer::copySub3DImplementationDSAEXT;
renderbufferImplementation = &Framebuffer::renderbufferImplementationDSAEXT;
texture1DImplementation = &Framebuffer::texture1DImplementationDSAEXT;
/* The EXT_DSA implementation is the same for both 2D and cube map textures */
texture2DImplementation = &Framebuffer::texture2DImplementationDSAEXT;
textureImplementation = &Framebuffer::textureImplementationDSAEXT;
textureCubeMapImplementation = &Framebuffer::texture2DImplementationDSAEXT;
textureLayerImplementation = &Framebuffer::textureLayerImplementationDSAEXT;
renderbufferStorageImplementation = &Renderbuffer::storageImplementationDSAEXT;
} else
#endif
{
checkStatusImplementation = &AbstractFramebuffer::checkStatusImplementationDefault;
#ifndef MAGNUM_TARGET_GLES2
clearIImplementation = &AbstractFramebuffer::clearImplementationDefault;
clearUIImplementation = &AbstractFramebuffer::clearImplementationDefault;
clearFImplementation = &AbstractFramebuffer::clearImplementationDefault;
clearFIImplementation = &AbstractFramebuffer::clearImplementationDefault;
#endif
#ifndef MAGNUM_TARGET_GLES2
drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationDefault;
#endif
#ifndef MAGNUM_TARGET_GLES
drawBufferImplementation = &AbstractFramebuffer::drawBufferImplementationDefault;
#endif
#if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2))
readBufferImplementation = &AbstractFramebuffer::readBufferImplementationDefault;
#endif
#ifndef MAGNUM_TARGET_GLES
copySub1DImplementation = &AbstractFramebuffer::copySub1DImplementationDefault;
#endif
copySub2DImplementation = &AbstractFramebuffer::copySub2DImplementationDefault;
copySubCubeMapImplementation = &AbstractFramebuffer::copySub2DImplementationDefault;
#if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2))
copySub3DImplementation = &AbstractFramebuffer::copySub3DImplementationDefault;
#endif
renderbufferImplementation = &Framebuffer::renderbufferImplementationDefault;
#ifndef MAGNUM_TARGET_GLES
texture1DImplementation = &Framebuffer::texture1DImplementationDefault;
#endif
/* The default implementation is the same for both 2D and cube map textures */
texture2DImplementation = &Framebuffer::texture2DImplementationDefault;
#if !defined(MAGNUM_TARGET_WEBGL) && !defined(MAGNUM_TARGET_GLES2)
textureImplementation = &Framebuffer::textureImplementationDefault;
#endif
textureCubeMapImplementation = &Framebuffer::texture2DImplementationDefault;
#if !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2))
textureLayerImplementation = &Framebuffer::textureLayerImplementationDefault;
#endif
renderbufferStorageImplementation = &Renderbuffer::storageImplementationDefault;
}
#ifdef MAGNUM_TARGET_GLES2
/* Framebuffer binding and checking on ES2 */
/* Optimistically set separate binding targets and check if one of the
extensions providing them is available */
#ifndef MAGNUM_TARGET_WEBGL
bindImplementation = &Framebuffer::bindImplementationDefault;
bindInternalImplementation = &Framebuffer::bindImplementationDefault;
#endif
checkStatusImplementation = &Framebuffer::checkStatusImplementationDefault;
#ifndef MAGNUM_TARGET_WEBGL
if(context.isExtensionSupported<Extensions::GL::ANGLE::framebuffer_blit>()) {
extensions.push_back(Extensions::GL::ANGLE::framebuffer_blit::string());
} else if(context.isExtensionSupported<Extensions::GL::APPLE::framebuffer_multisample>()) {
extensions.push_back(Extensions::GL::APPLE::framebuffer_multisample::string());
} else if(context.isExtensionSupported<Extensions::GL::NV::framebuffer_blit>()) {
extensions.push_back(Extensions::GL::NV::framebuffer_blit::string());
/* NV_framebuffer_multisample requires NV_framebuffer_blit, which has these
enums. However, on my system only NV_framebuffer_multisample is
supported, but NV_framebuffer_blit isn't. I will hold my breath and
assume these enums are available. */
} else if(context.isExtensionSupported<Extensions::GL::NV::framebuffer_multisample>()) {
extensions.push_back(Extensions::GL::NV::framebuffer_multisample::string());
/* If no such extension is available, reset back to single target */
} else {
bindImplementation = &Framebuffer::bindImplementationSingle;
bindInternalImplementation = &Framebuffer::bindImplementationSingle;
checkStatusImplementation = &Framebuffer::checkStatusImplementationSingle;
}
#endif
#ifndef MAGNUM_TARGET_WEBGL
/* Framebuffer draw mapping on ES2 */
if(context.isExtensionSupported<Extensions::GL::EXT::draw_buffers>()) {
extensions.push_back(Extensions::GL::EXT::draw_buffers::string());
drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationEXT;
} else if(context.isExtensionSupported<Extensions::GL::NV::draw_buffers>()) {
extensions.push_back(Extensions::GL::NV::draw_buffers::string());
drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationNV;
} else drawBuffersImplementation = nullptr;
#else
if(context.isExtensionSupported<Extensions::GL::WEBGL::draw_buffers>()) {
extensions.push_back(Extensions::GL::WEBGL::draw_buffers::string());
/* The EXT implementation is exposed in Emscripten */
drawBuffersImplementation = &AbstractFramebuffer::drawBuffersImplementationEXT;
} else drawBuffersImplementation = nullptr;
#endif
#endif
/* Framebuffer reading implementation in desktop/ES */
#ifndef MAGNUM_TARGET_WEBGL
#ifndef MAGNUM_TARGET_GLES
if(context.isExtensionSupported<Extensions::GL::ARB::robustness>())
#else
if(context.isExtensionSupported<Extensions::GL::EXT::robustness>())
#endif
{
#ifndef MAGNUM_TARGET_GLES
extensions.emplace_back(Extensions::GL::ARB::robustness::string());
#else
extensions.push_back(Extensions::GL::EXT::robustness::string());
#endif
readImplementation = &AbstractFramebuffer::readImplementationRobustness;
} else readImplementation = &AbstractFramebuffer::readImplementationDefault;
/* Framebuffer reading in WebGL */
#else
readImplementation = &AbstractFramebuffer::readImplementationDefault;
#endif
/* Multisample renderbuffer storage implementation */
#ifndef MAGNUM_TARGET_GLES
if(context.isExtensionSupported<Extensions::GL::ARB::direct_state_access>()) {
/* Extension added above */
renderbufferStorageMultisampleImplementation = &Renderbuffer::storageMultisampleImplementationDSA;
} else if(context.isExtensionSupported<Extensions::GL::EXT::direct_state_access>()) {
/* Extension added above */
renderbufferStorageMultisampleImplementation = &Renderbuffer::storageMultisampleImplementationDSAEXT;
} else
#endif
{
#if defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL)
if(context.isExtensionSupported<Extensions::GL::ANGLE::framebuffer_multisample>()) {
extensions.push_back(Extensions::GL::ANGLE::framebuffer_multisample::string());
renderbufferStorageMultisampleImplementation = &Renderbuffer::storageMultisampleImplementationANGLE;
} else if (context.isExtensionSupported<Extensions::GL::NV::framebuffer_multisample>()) {
extensions.push_back(Extensions::GL::NV::framebuffer_multisample::string());
renderbufferStorageMultisampleImplementation = &Renderbuffer::storageMultisampleImplementationNV;
} else renderbufferStorageMultisampleImplementation = nullptr;
#elif !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2))
renderbufferStorageMultisampleImplementation = &Renderbuffer::storageMultisampleImplementationDefault;
#endif
}
/* Framebuffer invalidation implementation on desktop GL */
#ifndef MAGNUM_TARGET_GLES
if(context.isExtensionSupported<Extensions::GL::ARB::invalidate_subdata>()) {
extensions.emplace_back(Extensions::GL::ARB::invalidate_subdata::string());
if(context.isExtensionSupported<Extensions::GL::ARB::direct_state_access>()) {
/* Extension added above */
invalidateImplementation = &AbstractFramebuffer::invalidateImplementationDSA;
invalidateSubImplementation = &AbstractFramebuffer::invalidateImplementationDSA;
} else {
invalidateImplementation = &AbstractFramebuffer::invalidateImplementationDefault;
invalidateSubImplementation = &AbstractFramebuffer::invalidateImplementationDefault;
}
} else {
invalidateImplementation = &AbstractFramebuffer::invalidateImplementationNoOp;
invalidateSubImplementation = &AbstractFramebuffer::invalidateImplementationNoOp;
}
/* Framebuffer invalidation implementation on ES2 */
#elif defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL)
if(context.isExtensionSupported<Extensions::GL::EXT::discard_framebuffer>()) {
extensions.push_back(Extensions::GL::EXT::discard_framebuffer::string());
invalidateImplementation = &AbstractFramebuffer::invalidateImplementationDefault;
} else {
invalidateImplementation = &AbstractFramebuffer::invalidateImplementationNoOp;
}
/* Always available on ES3 */
#elif !(defined(MAGNUM_TARGET_WEBGL) && defined(MAGNUM_TARGET_GLES2))
invalidateImplementation = &AbstractFramebuffer::invalidateImplementationDefault;
invalidateSubImplementation = &AbstractFramebuffer::invalidateImplementationDefault;
#endif
/* Blit implementation on desktop GL */
#ifndef MAGNUM_TARGET_GLES
if(context.isExtensionSupported<Extensions::GL::ARB::direct_state_access>()) {
/* Extension added above */
blitImplementation = &AbstractFramebuffer::blitImplementationDSA;
} else blitImplementation = &AbstractFramebuffer::blitImplementationDefault;
/* Blit implementation on ES2 */
#elif defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL)
if(context.isExtensionSupported<Extensions::GL::ANGLE::framebuffer_blit>()) {
extensions.push_back(Extensions::GL::ANGLE::framebuffer_blit::string());
blitImplementation = &AbstractFramebuffer::blitImplementationANGLE;
} else if(context.isExtensionSupported<Extensions::GL::NV::framebuffer_blit>()) {
extensions.push_back(Extensions::GL::NV::framebuffer_blit::string());
blitImplementation = &AbstractFramebuffer::blitImplementationNV;
} else blitImplementation = nullptr;
/* Always available on ES3 and WebGL 2 */
#elif !defined(MAGNUM_TARGET_GLES2)
blitImplementation = &AbstractFramebuffer::blitImplementationDefault;
#endif
#if defined(MAGNUM_TARGET_WEBGL) && !defined(MAGNUM_TARGET_GLES2)
static_cast<void>(context);
static_cast<void>(extensions);
#endif
}
void FramebufferState::reset() {
readBinding = drawBinding = renderbufferBinding = State::DisengagedBinding;
viewport = DisengagedViewport;
}
}}
| 49.111748 | 214 | 0.751692 | costashatz |
d410fe2fe8014681408cde2a9711f0967d8b81c2 | 325 | cpp | C++ | 16. Heaps/07 Delete.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | 190 | 2021-02-10T17:01:01.000Z | 2022-03-20T00:21:43.000Z | 16. Heaps/07 Delete.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | null | null | null | 16. Heaps/07 Delete.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | 27 | 2021-03-26T11:35:15.000Z | 2022-03-06T07:34:54.000Z | #include<bits/stdc++.h>
using namespace std;
class MinHeap
{
int arr[];
int size;
int capacity;
public:
MinHeap(int c)
{
arr = new int[c];
size = 0;
capacity = c;
}
int left(int i)
{
return (2 * i + 1);
}
int right(int i)
{
return (2 * i + 2);
}
int parent(int i)
{
return (i - 1) / 2;
}
}; | 9.285714 | 23 | 0.532308 | VivekYadav105 |
d411603bf325af6c52e9fe2e37fb54d32bcf2d30 | 1,411 | cpp | C++ | examples/container/bitfield.cpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | examples/container/bitfield.cpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | examples/container/bitfield.cpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// 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)
#include <fcppt/container/bitfield/object.hpp>
#include <fcppt/container/bitfield/operators.hpp>
#include <fcppt/config/external_begin.hpp>
#include <iostream>
#include <fcppt/config/external_end.hpp>
//! [bitfield]
namespace
{
enum class person_status
{
hungry,
tired,
fcppt_maximum = tired // note the extra field here
};
using bitfield = fcppt::container::bitfield::object<person_status>;
void output(bitfield const &_field)
{
std::cout << "Person status: hungry: " << (_field & person_status::hungry) << '\n'
<< "Person status: tired: " << (_field & person_status::tired) << '\n';
}
}
int main()
{
// Initialize the bitfield to all zeros
bitfield field(bitfield::null());
output(field);
// Set a flag, the bitwise kind of way
field |= person_status::hungry;
output(field);
// And unset it again
field &= ~bitfield{person_status::hungry};
// You can access a single flag via operator[]
std::cout << "person is hungry: " << field[person_status::hungry] << '\n';
// You can also set a flag this way:
field[person_status::hungry] = false;
std::cout << ("person is hungry: ") << field[person_status::hungry] << '\n';
}
//! [bitfield]
| 25.654545 | 84 | 0.671155 | freundlich |
d4116138318b85b96e4066df7c006aa82500c72f | 9,355 | cc | C++ | towr/src/quadruped_gait_generator.cc | IoannisDadiotis/towr | cbbe6d30d637b4271558e31bf522536451a9110c | [
"BSD-3-Clause"
] | null | null | null | towr/src/quadruped_gait_generator.cc | IoannisDadiotis/towr | cbbe6d30d637b4271558e31bf522536451a9110c | [
"BSD-3-Clause"
] | null | null | null | towr/src/quadruped_gait_generator.cc | IoannisDadiotis/towr | cbbe6d30d637b4271558e31bf522536451a9110c | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
Copyright (c) 2018, Alexander W. Winkler. 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 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 <towr/initialization/quadruped_gait_generator.h>
#include <cassert>
#include <iostream>
#include <towr/models/endeffector_mappings.h>
namespace towr {
QuadrupedGaitGenerator::QuadrupedGaitGenerator ()
{
int n_ee = 4;
ContactState init(n_ee, false);
II_ = init; // flight_phase
PI_ = bI_ = IP_ = Ib_ = init; // single contact
Pb_ = bP_ = BI_ = IB_ = PP_ = bb_ = init; // two leg support
Bb_ = BP_ = bB_ = PB_ = init; // three-leg support
BB_ = init; // four-leg support phase
// flight_phase
II_ = ContactState(n_ee, false);
// one stanceleg
PI_.at(LH) = true;
bI_.at(RH) = true;
IP_.at(LF) = true;
Ib_.at(RF) = true;
// two stancelegs
Pb_.at(LH) = true; Pb_.at(RF) = true;
bP_.at(RH) = true; bP_.at(LF) = true;
BI_.at(LH) = true; BI_.at(RH) = true;
IB_.at(LF) = true; IB_.at(RF) = true;
PP_.at(LH) = true; PP_.at(LF) = true;
bb_.at(RH) = true; bb_.at(RF) = true;
// three stancelegs
Bb_.at(LH) = true; Bb_.at(RH) = true; Bb_.at(RF)= true;
BP_.at(LH) = true; BP_.at(RH) = true; BP_.at(LF)= true;
bB_.at(RH) = true; bB_.at(LF) = true; bB_.at(RF)= true;
PB_.at(LH) = true; PB_.at(LF) = true; PB_.at(RF)= true;
// four stancelgs
BB_ = ContactState(n_ee, true);
// default gait
SetGaits({Stand});
}
void
QuadrupedGaitGenerator::SetCombo (Combos combo)
{
switch (combo) {
case C0: SetGaits({Stand, Walk2, Walk2, Walk2, Walk2E, Stand}); break; // overlap-walk
case C1: SetGaits({Stand, Run2, Run2, Run2, Run2E, Stand}); break; // fly trot
case C2: SetGaits({Stand, Run3, Run3, Run3, Run3E, Stand}); break; // pace
case C3: SetGaits({Stand, Hop1, Hop1, Hop1, Hop1E, Stand}); break; // bound
case C4: SetGaits({Stand, Hop3, Hop3, Hop3, Hop3E, Stand}); break; // gallop
case C5: SetGaits({Stand, WalkSlow, Stand}); break; // slow walk for centauro
default: assert(false); std::cout << "Gait not defined\n"; break;
}
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetGait(Gaits gait) const
{
switch (gait) {
case Stand: return GetStrideStand();
case Flight: return GetStrideFlight();
case WalkSlow: return GetStrideWalkSlow();
case Walk1: return GetStrideWalk();
case Walk2: return GetStrideWalkOverlap();
case Walk2E: return RemoveTransition(GetStrideWalkOverlap());
case Run1: return GetStrideTrot();
case Run2: return GetStrideTrotFly();
case Run2E: return GetStrideTrotFlyEnd();
case Run3: return GetStridePace();
case Run3E: return GetStridePaceEnd();
case Hop1: return GetStrideBound();
case Hop1E: return GetStrideBoundEnd();
case Hop2: return GetStridePronk();
case Hop3: return GetStrideGallop();
case Hop3E: return RemoveTransition(GetStrideGallop());
case Hop5: return GetStrideLimp();
default: assert(false); // gait not implemented
}
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideStand () const
{
auto times =
{
0.3,
};
auto contacts =
{
BB_,
};
return std::make_pair(times, contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideFlight () const
{
auto times =
{
0.3,
};
auto contacts =
{
Bb_,
};
return std::make_pair(times, contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStridePronk () const
{
double push = 0.3;
double flight = 0.4;
double land = 0.3;
auto times =
{
push, flight, land
};
auto phase_contacts =
{
BB_, II_, BB_,
};
return std::make_pair(times, phase_contacts);
}
// Slow walking stride for Centauro
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideWalkSlow () const
{
double step = 1.0;
double stand = 1.0;
// start with stand
auto times =
{
stand, step, stand, step, stand,
step, stand, step, stand,
};
auto phase_contacts =
{
BB_, bB_, BB_, Bb_, BB_,
PB_, BB_, BP_, BB_
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideWalk () const
{
double step = 0.3;
double stand = 0.2;
auto times =
{
step, stand, step, stand,
step, stand, step, stand,
};
auto phase_contacts =
{
bB_, BB_, Bb_, BB_,
PB_, BB_, BP_, BB_
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideWalkOverlap () const
{
double three = 0.25;
double lateral = 0.13;
double diagonal = 0.13;
auto times =
{
three, lateral, three,
diagonal,
three, lateral, three,
diagonal,
};
auto phase_contacts =
{
bB_, bb_, Bb_,
Pb_, // start lifting RH
PB_, PP_, BP_,
bP_, // start lifting LH
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideTrot () const
{
double t_step = 0.3;
double t_stand = 0.2;
auto times =
{
t_step, t_stand, t_step, t_stand,
};
auto phase_contacts =
{
bP_, BB_, Pb_, BB_,
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideTrotFly () const
{
double stand = 0.4;
double flight = 0.1;
auto times =
{
stand, flight,
stand, flight,
};
auto phase_contacts =
{
bP_, II_,
Pb_, II_,
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideTrotFlyEnd () const
{
auto times =
{
0.4,
};
auto phase_contacts =
{
bP_
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStridePace () const
{
double stand = 0.3;
double flight = 0.1;
auto times =
{
stand, flight, stand, flight
};
auto phase_contacts =
{
PP_, II_, bb_, II_,
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStridePaceEnd () const
{
auto times =
{
0.3,
};
auto phase_contacts =
{
PP_,
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideBound () const
{
double stand = 0.3;
double flight = 0.1;
auto times =
{
stand, flight, stand, flight
};
auto phase_contacts =
{
BI_, II_, IB_, II_
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideBoundEnd () const
{
auto times =
{
0.3,
};
auto phase_contacts =
{
BI_,
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideGallop () const
{
double A = 0.3; // both feet in air
double B = 0.2; // overlap
double C = 0.2; // transition front->hind
auto times =
{
B, A, B,
C,
B, A, B,
C
};
auto phase_contacts =
{
Bb_, BI_, BP_, // front legs swing forward
bP_, // transition phase
bB_, IB_, PB_, // hind legs swing forward
Pb_
};
return std::make_pair(times, phase_contacts);
}
QuadrupedGaitGenerator::GaitInfo
QuadrupedGaitGenerator::GetStrideLimp () const
{
double A = 0.1; // three in contact
double B = 0.2; // all in contact
double C = 0.1; // one in contact
auto times =
{
A, B, C,
A, B, C,
};
auto phase_contacts =
{
Bb_, BB_, IP_,
Bb_, BB_, IP_,
};
return std::make_pair(times, phase_contacts);
}
} /* namespace towr */
| 23.743655 | 90 | 0.649813 | IoannisDadiotis |
d4124780e16cb155c4f5f1c306b374d3504951c1 | 29,410 | cpp | C++ | Source/System/Physics/ColliderPrimitive/ConvexHull3D/ColliderPolyhedron.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | 2 | 2020-01-09T07:48:24.000Z | 2020-01-09T07:48:26.000Z | Source/System/Physics/ColliderPrimitive/ConvexHull3D/ColliderPolyhedron.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | null | null | null | Source/System/Physics/ColliderPrimitive/ConvexHull3D/ColliderPolyhedron.cpp | arian153/Engine-5 | 34f85433bc0a74a7ebe7da350d3f3698de77226e | [
"MIT"
] | null | null | null | #include "ColliderPolyhedron.hpp"
#include "../../../Graphics/Utility/PrimitiveRenderer.hpp"
#include "../../BroadPhase/BoundingAABB.hpp"
#include <list>
#include "../../../../Manager/Resource/ResourceType/JsonResource.hpp"
#include "../../../../External/JSONCPP/json/json.h"
namespace Engine5
{
ColliderPolyhedron::ColliderPolyhedron()
{
m_type = eColliderType::Polyhedron;
}
ColliderPolyhedron::~ColliderPolyhedron()
{
}
void ColliderPolyhedron::Initialize()
{
if (m_vertices == nullptr)
{
m_vertices = new std::vector<Vector3>();
}
if (m_scaled_vertices == nullptr)
{
m_scaled_vertices = new std::vector<Vector3>();
}
if (m_edges == nullptr)
{
m_edges = new std::vector<ColliderEdge>();
}
if (m_faces == nullptr)
{
m_faces = new std::vector<ColliderFace>();
}
UpdatePrimitive();
}
void ColliderPolyhedron::Shutdown()
{
if (m_vertices != nullptr)
{
m_vertices->clear();
delete m_vertices;
m_vertices = nullptr;
}
if (m_scaled_vertices != nullptr)
{
m_scaled_vertices->clear();
delete m_scaled_vertices;
m_scaled_vertices = nullptr;
}
if (m_edges != nullptr)
{
m_edges->clear();
delete m_edges;
m_edges = nullptr;
}
if (m_faces != nullptr)
{
m_faces->clear();
delete m_faces;
m_faces = nullptr;
}
}
Vector3 ColliderPolyhedron::Support(const Vector3& direction)
{
Real p = Math::REAL_NEGATIVE_MAX;
Vector3 result;
std::vector<Vector3>* vertices;
if (m_collider_set != nullptr)
{
vertices = m_scaled_vertices;
}
else
{
vertices = m_vertices;
}
size_t size = vertices->size();
for (size_t i = 0; i < size; ++i)
{
Real projection = vertices->at(i).DotProduct(direction);
if (projection > p)
{
result = vertices->at(i);
p = projection;
}
}
return result;
}
bool ColliderPolyhedron::TestRayIntersection(const Ray& local_ray, Real& minimum_t, Real& maximum_t) const
{
bool b_first = true;
int hit_count = 0;
minimum_t = -1.0f;
maximum_t = -1.0f;
for (auto& face : *m_faces)
{
Real t = -1.0f;
if (IntersectRayFace(local_ray, face, t) == true)
{
if (b_first == true)
{
minimum_t = t;
maximum_t = t;
b_first = false;
}
else
{
if (t > maximum_t)
{
maximum_t = t;
}
if (t < minimum_t)
{
minimum_t = t;
}
}
hit_count++;
}
}
if (hit_count > 0)
{
if (minimum_t < 0.0f && maximum_t < 0.0f)
{
return false;
}
if (minimum_t <= 0.0f)
{
minimum_t = 0.0f;
}
return true;
}
return false;
}
Vector3 ColliderPolyhedron::GetNormal(const Vector3& local_point_on_collider)
{
Vector3 normal;
for (auto& face : *m_faces)
{
if (this->IsFaceContainPoint(face, local_point_on_collider, normal) == true)
{
return normal;
}
}
return normal;
}
void ColliderPolyhedron::SetMassData(Real density)
{
if (Math::IsNotEqual(m_material.density, density))
{
m_material.density = density;
m_material.type = Physics::eMaterial::UserType;
}
m_centroid = 0.0f;
m_local_inertia_tensor.SetZero();
m_mass = 0.0f;
Vector3 ref_point = Math::Vector3::ORIGIN;
for (auto& face : *m_faces)
{
auto sub_data = CalculateTetrahedronMassData(ref_point, Vertex(face.a), Vertex(face.b), Vertex(face.c), density);
m_centroid += sub_data.mass * sub_data.centroid;
m_mass += sub_data.mass;
m_local_inertia_tensor += sub_data.inertia;
}
if (Math::IsZero(m_mass) == false)
{
m_centroid /= m_mass;
}
else
{
m_centroid = 0.0f;
}
m_local_inertia_tensor = TranslateInertia(m_local_inertia_tensor, m_centroid, m_mass, ref_point - m_centroid);
}
Real ColliderPolyhedron::GetVolume()
{
Real volume = 0.0f;
Vector3 ref_point = Math::Vector3::ORIGIN;
for (auto& face : *m_faces)
{
Matrix33 tetrahedron_matrix;
tetrahedron_matrix.SetColumns(Vertex(face.a) - ref_point, Vertex(face.b) - ref_point, Vertex(face.c) - ref_point);
volume += tetrahedron_matrix.Determinant() / 6.0f;
}
return volume;
}
void ColliderPolyhedron::SetScaleData(const Vector3& scale)
{
m_scaled_vertices->clear();
size_t size = m_vertices->size();
m_scaled_vertices->reserve(size);
for (size_t i = 0; i < size; ++i)
{
m_scaled_vertices->push_back(m_vertices->at(i).HadamardProduct(scale.HadamardProduct(m_local.scale)));
for (size_t j = 0; j < 3; ++j)
{
if (m_max_bound[j] < m_scaled_vertices->at(i)[j])
{
m_max_bound[j] = m_scaled_vertices->at(i)[j];
}
if (m_min_bound[j] > m_scaled_vertices->at(i)[j])
{
m_min_bound[j] = m_scaled_vertices->at(i)[j];
}
}
}
}
void ColliderPolyhedron::SetUnit()
{
CalculateMinMaxBound();
auto scale_factor = (m_max_bound - m_min_bound).Inverse();
size_t size = m_vertices->size();
for (size_t i = 0; i < size; ++i)
{
m_scaled_vertices->at(i) = m_vertices->at(i).HadamardProduct(scale_factor);
}
UpdatePrimitive();
}
void ColliderPolyhedron::UpdateBoundingVolume()
{
Real bounding_factor = (m_max_bound - m_min_bound).Length();
Vector3 pos = m_rigid_body != nullptr ? m_rigid_body->LocalToWorldPoint(m_local.position) : m_local.position;
Vector3 min_max(bounding_factor, bounding_factor, bounding_factor);
m_bounding_volume->Set(-min_max + pos, min_max + pos);
Vector3 obb_vertices[8];
obb_vertices[0].Set(m_max_bound.x, m_max_bound.y, m_max_bound.z);
obb_vertices[1].Set(m_max_bound.x, m_max_bound.y, m_min_bound.z);
obb_vertices[2].Set(m_max_bound.x, m_min_bound.y, m_max_bound.z);
obb_vertices[3].Set(m_max_bound.x, m_min_bound.y, m_min_bound.z);
obb_vertices[4].Set(m_min_bound.x, m_max_bound.y, m_max_bound.z);
obb_vertices[5].Set(m_min_bound.x, m_max_bound.y, m_min_bound.z);
obb_vertices[6].Set(m_min_bound.x, m_min_bound.y, m_max_bound.z);
obb_vertices[7].Set(m_min_bound.x, m_min_bound.y, m_min_bound.z);
bool has_body = m_rigid_body != nullptr;
Vector3 min = has_body
? m_rigid_body->LocalToWorldPoint(m_local.LocalToWorldPoint(obb_vertices[0]))
: m_local.LocalToWorldPoint(obb_vertices[0]);
Vector3 max = min;
if (has_body)
{
for (int i = 1; i < 8; ++i)
{
Vector3 vertex = m_rigid_body->LocalToWorldPoint(m_local.LocalToWorldPoint(obb_vertices[i]));
min.x = Math::Min(min.x, vertex.x);
min.y = Math::Min(min.y, vertex.y);
min.z = Math::Min(min.z, vertex.z);
max.x = Math::Max(max.x, vertex.x);
max.y = Math::Max(max.y, vertex.y);
max.z = Math::Max(max.z, vertex.z);
}
}
else
{
for (int i = 1; i < 8; ++i)
{
Vector3 vertex = m_local.LocalToWorldPoint(obb_vertices[i]);
min.x = Math::Min(min.x, vertex.x);
min.y = Math::Min(min.y, vertex.y);
min.z = Math::Min(min.z, vertex.z);
max.x = Math::Max(max.x, vertex.x);
max.y = Math::Max(max.y, vertex.y);
max.z = Math::Max(max.z, vertex.z);
}
}
m_bounding_volume->Set(min, max);
}
void ColliderPolyhedron::Draw(PrimitiveRenderer* renderer, eRenderingMode mode, const Color& color) const
{
I32 index = static_cast<I32>(renderer->VerticesSize(mode));
std::vector<Vector3>* vertices;
if (m_collider_set != nullptr)
{
vertices = m_scaled_vertices;
}
else
{
vertices = m_vertices;
}
size_t size = vertices->size();
renderer->ReserveVertices(size, mode);
Transform* body_transform = GetBodyTransform();
for (auto& vertex : *vertices)
{
//collider local space to object space(body local)
vertex = LocalToWorldPoint(vertex);
vertex = body_transform->LocalToWorldPoint(vertex);
//push to renderer
renderer->PushVertex(vertex, mode, color);
}
//add indices
if (mode == eRenderingMode::Dot)
{
for (I32 i = 0; i < size; ++i)
{
renderer->PushIndex(index + i, mode);
}
}
else if (mode == eRenderingMode::Line)
{
for (auto& face : *m_faces)
{
renderer->PushLineIndices(index + (I32)face.a, index + (I32)face.b);
renderer->PushLineIndices(index + (I32)face.b, index + (I32)face.c);
renderer->PushLineIndices(index + (I32)face.c, index + (I32)face.a);
}
}
else if (mode == eRenderingMode::Face)
{
for (auto& face : *m_faces)
{
renderer->PushFaceIndices(index + (I32)face.a, index + (I32)face.b, index + (I32)face.c);
}
}
}
Vector3 ColliderPolyhedron::Vertex(size_t i) const
{
if (m_collider_set != nullptr)
{
return m_scaled_vertices->at(i);
}
return m_vertices->at(i);
}
size_t ColliderPolyhedron::Size() const
{
if (m_collider_set != nullptr)
{
return m_scaled_vertices->size();
}
return m_vertices->size();
}
bool ColliderPolyhedron::SetPolyhedron(const std::vector<Vector3>& input_vertices)
{
//0. Early quit when not enough vertices.
size_t size = input_vertices.size();
if (size < 4)
{
return false;
}
//1. Allocate a Polyhedron which will be our return value.
if (m_vertices == nullptr)
{
m_vertices = new std::vector<Vector3>();
m_vertices->reserve(size);
}
else
{
m_vertices->clear();
m_vertices->reserve(size);
}
std::vector<Vector3> vertices = input_vertices;
//2. Find a maximal simplex of the current dimension.In our case,
//find 4 points which define maximal tetrahedron, and create the tetrahedron which will be our seed partial answer.
//CREATE_SIMPLEX(Polyhedron, listVertices).
//If this returns a dimension lower than 3, report the degeneracy and quit.
size_t dimension = CreateSimplex(vertices);
if (dimension < 3)
{
return false;
}
//3. Divide the points of the cloud into the outside sets of the four faces of the tetrahedron.
//This is done by calling ADD_TO_OUTSIDE_SET(face, listVertices) on each of the 4 faces in turn.
//Points that could be put in multiple sets will be randomly placed in one of them, and it does not matter which one.
//Any points which are inside or on all of the planes do not contribute to the convex hull.
//These points are removed from the rest of the calculation.
std::list<OutsideSetFace> outside_set_list;
for (auto face : *m_faces)
{
OutsideSetFace outside_set(face);
AddToOutsideSet(vertices, outside_set);
outside_set_list.push_back(outside_set);
}
//4. While(There exists currFace = a face on the current convex hull which has a non - empty outside set of vertices)
while (!outside_set_list.empty())
{
//1. Find the point in currFace's outside set which is farthest away from the plane of the currFace.
//This is the eyePoint.
//2. Compute the horizon of the current polyhedron as seen from this eyePoint.
//CALCULATE_HORIZON(eyePoint, NULL, currFace, listHorizonEdges, listUnclaimedVertices).
//This will mark all of the visible faces as not on the convex hull and place all of their outside set points on the listUnclaimedVertices.
//It is creates the listHorizonEdges which is a counterclockwise ordered list of edges around the horizon contour of the polyhedron as viewed from the eyePoint.
//3. Construct a cone from the eye point to all of the edges of the horizon.
//Before a triangle of this cone is created and added to the polyhedron a test to see if it coplanar to the face on the other side of the horizon edge is applied.
//If the faces are coplanar then they are merged together and that horizon edge is marked as not on the convex hull.Then a similar check must also be applied to edges which cross the horizon to see if they are collinear.
//If so then the vertex on the horizon which is on this line must be marked as not on the horizon.
//4. Divide the points of the listUnclaimedVertices into the outside sets of the new cone faces and the faces which were merged with what would be new cone faces.
//This is done by calling ADD_TO_OUTSIDE_SET(face, listUnclaimedVertices) on each of these faces in turn.
//Points that could be put in multiple sets will be randomly placed in one of them, and it does not matter which one.
//Any points which are inside or on all of the planes do not contribute to the convex hull.
//These points are marked as not on the convex hull.
//5. Remove all faces, edges, and vertices which have been marked as not on the convex hull.
//These faces, edges, and vertices have all been enclosed by the new cone emanating from the eyePoint.
//6. Continue the loop
}
//5. When all the faces with outside points have been processed we are done.
//The polyhedron should a clean convex hull where all coplanar faces have been merged.
//All collinear edges have been merged.
//And all coincident vertices have had their DualFace pointers merged.
return true;
}
void ColliderPolyhedron::Clone(ColliderPrimitive* origin)
{
if (origin != this && origin != nullptr && origin->Type() == m_type)
{
ColliderPolyhedron* polyhedron = static_cast<ColliderPolyhedron*>(origin);
//collider local space data
m_local = polyhedron->m_local;
//collider mass data
m_centroid = polyhedron->m_centroid;
m_mass = polyhedron->m_mass;
m_local_inertia_tensor = polyhedron->m_local_inertia_tensor;
m_material = polyhedron->m_material;
//polyhedron
*m_vertices = *polyhedron->m_vertices;
*m_scaled_vertices = *polyhedron->m_scaled_vertices;
*m_edges = *polyhedron->m_edges;
*m_faces = *polyhedron->m_faces;
m_min_bound = polyhedron->m_min_bound;
m_max_bound = polyhedron->m_max_bound;
}
}
void ColliderPolyhedron::Load(const Json::Value& data)
{
LoadTransform(data);
//polyhedron data
if (JsonResource::HasMember(data, "Vertices") && data["Vertices"].isArray() && data["Vertices"].size() >= 4)
{
m_vertices->clear();
m_scaled_vertices->clear();
for (auto it = data["Vertices"].begin(); it != data["Vertices"].end(); ++it)
{
if (JsonResource::IsVector3(*it))
{
Vector3 vertex = JsonResource::AsVector3(*it);
m_vertices->push_back(vertex);
}
}
}
if (JsonResource::HasMember(data, "Edges") && data["Edges"].isArray())
{
m_edges->clear();
for (auto it = data["Edges"].begin(); it != data["Edges"].end(); ++it)
{
if (JsonResource::IsVector2(*it))
{
m_edges->emplace_back((size_t)data[0].asUInt64(), (size_t)data[1].asUInt64());
}
}
}
if (JsonResource::HasMember(data, "Faces") && data["Faces"].isArray())
{
m_faces->clear();
for (auto it = data["Faces"].begin(); it != data["Faces"].end(); ++it)
{
if (JsonResource::IsVector3(*it))
{
m_faces->emplace_back((size_t)data[0].asUInt64(), (size_t)data[1].asUInt64(), (size_t)data[2].asUInt64());
}
}
}
SetPolyhedron(*m_vertices);
LoadMaterial(data);
LoadMass(data);
}
void ColliderPolyhedron::Save(const Json::Value& data)
{
}
void ColliderPolyhedron::EditPrimitive(CommandRegistry* registry)
{
}
bool ColliderPolyhedron::IntersectRayFace(const Ray& ray, const ColliderFace& face, Real& t) const
{
std::vector<Vector3>* vertices;
if (m_collider_set != nullptr)
{
vertices = m_scaled_vertices;
}
else
{
vertices = m_vertices;
}
Vector3 edge1 = (*vertices)[face.b] - (*vertices)[face.a];
Vector3 edge2 = (*vertices)[face.c] - (*vertices)[face.a];
Vector3 h = ray.direction.CrossProduct(edge2);
Real a = edge1.DotProduct(h);
t = -1.0f;
if (Math::IsZero(a))
{
return false;
}
Real f = 1.0f / a;
Vector3 s = ray.position - (*vertices)[face.a];
Real u = f * (s.DotProduct(h));
if (u < 0.0f || u > 1.0f)
{
return false;
}
Vector3 q = s.CrossProduct(edge1);
Real v = f * ray.direction.DotProduct(q);
if (v < 0.0f || u + v > 1.0f)
{
return false;
}
// At this stage we can compute t to find out where the intersection point is on the line.
t = f * edge2.DotProduct(q);
if (t > Math::EPSILON) // ray intersection
{
return true;
}
// intersect back side of ray.
return false;
}
bool ColliderPolyhedron::IsFaceContainPoint(const ColliderFace& face, const Vector3& point, Vector3& normal) const
{
std::vector<Vector3>* vertices;
if (m_collider_set != nullptr)
{
vertices = m_scaled_vertices;
}
else
{
vertices = m_vertices;
}
Vector3 v0 = vertices->at(face.a);
Vector3 v1 = vertices->at(face.b);
Vector3 v2 = vertices->at(face.c);
Vector3 edge01 = v1 - v0;
Vector3 edge12 = v2 - v1;
normal = edge01.CrossProduct(edge12);
Vector3 w_test = edge01.CrossProduct(point - v0);
if (w_test.DotProduct(normal) < 0.0f)
{
return false;
}
w_test = edge12.CrossProduct(point - v1);
if (w_test.DotProduct(normal) < 0.0f)
{
return false;
}
Vector3 edge3 = v0 - v2;
w_test = edge3.CrossProduct(point - v2);
if (w_test.DotProduct(normal) < 0.0f)
{
return false;
}
normal.SetNormalize();
return true;
}
Matrix33 ColliderPolyhedron::TranslateInertia(const Matrix33& input, const Vector3& centroid, Real mass, const Vector3& offset) const
{
return input + mass * (offset.OuterProduct(centroid) + centroid.OuterProduct(offset) + offset.OuterProduct(offset));
}
ColliderPolyhedron::SubMassData ColliderPolyhedron::CalculateTetrahedronMassData(const Vector3& ref, const Vector3& v1, const Vector3& v2, const Vector3& v3, Real density) const
{
SubMassData result;
//canonical moment of inertia data.
Real axis = 1.0f / 60.0f;
Real prod = 1.0f / 120.0f;
Matrix33 canonical_matrix(axis, prod, prod, prod, axis, prod, prod, prod, axis);
Matrix33 transformation_matrix;
transformation_matrix.SetColumns(v1 - ref, v2 - ref, v3 - ref);
//calculate sub inertia
result.inertia = transformation_matrix.Determinant() * transformation_matrix * canonical_matrix * transformation_matrix.Transpose();
//volume is 1 / 6 of triple product, that is 1/6 det of transformation matrix.
result.mass = density * transformation_matrix.Determinant() / 6.0f;
//The center-of-mass is just the mean of the four vertex coordinates.
result.centroid = (ref + v1 + v2 + v3) * 0.25f;
if (ref.IsZero() == false)
{
result.inertia = TranslateInertia(result.inertia, result.centroid, result.mass, ref);
}
return result;
}
void ColliderPolyhedron::CalculateMinMaxBound()
{
m_max_bound = Math::REAL_NEGATIVE_MAX;
m_min_bound = Math::REAL_POSITIVE_MAX;
size_t size = m_scaled_vertices->size();
for (size_t i = 0; i < size; ++i)
{
for (size_t j = 0; j < 3; ++j)
{
Real value = m_scaled_vertices->at(i)[j];
if (m_max_bound[j] < value)
{
m_max_bound[j] = value;
}
if (m_min_bound[j] > value)
{
m_min_bound[j] = value;
}
}
}
}
size_t ColliderPolyhedron::CreateSimplex(const std::vector<Vector3>& vertices) const
{
//1. For each principle direction(X - axis, Y - axis, Z - axis)
Vector3 min_vertex, max_vertex;
bool b_succeed = false;
for (size_t i = 0; i < 3; ++i)
{
// 1. Find the minimum and maximum point in that dimension
Real min = Math::REAL_POSITIVE_MAX;
Real max = Math::REAL_NEGATIVE_MAX;
for (auto& vertex : vertices)
{
if (vertex[i] < min)
{
min = vertex[i];
min_vertex = vertex;
}
if (vertex[i] > max)
{
max = vertex[i];
max_vertex = vertex;
}
}
// 2. If min != max then break out of loop with success
if (min != max)
{
b_succeed = true;
break;
}
// 3. Continue the loop
}
//2. If the loop finished without success return and report that we have a degenerate point cloud, either 1D or 2D.
if (b_succeed == false)
{
return 0;
}
//3. Find the point which is furthest distant from the line defined by the first two points.If this maximum distance is zero, then our point cloud is 1D, so report the degeneracy.
Segment segment(min_vertex, max_vertex);
Real max_distance = 0.0f;
Real t = 0.0f;
Vector3 max_triangle;
for (auto& vertex : vertices)
{
Real distance = segment.DistanceSquared(vertex, t);
if (distance > max_distance)
{
max_distance = distance;
max_triangle = vertex;
}
}
if (Math::IsZero(max_distance))
{
return 1;
}
//4. Find the point which has the largest absolute distance from the plane defined by the first three points.If this maximum distance is zero, then our point cloud is 2D, so report the the degeneracy.
max_distance = 0.0f;
Vector3 max_tetrahedron;
for (auto& vertex : vertices)
{
Real distance = Triangle::DistanceSquared(vertex, min_vertex, max_vertex, max_triangle);
if (distance > max_distance)
{
max_distance = distance;
max_tetrahedron = vertex;
}
}
if (Math::IsZero(max_distance))
{
return 2;
}
//5. Create the tetrahedron polyhedron.Remember that if the distance from the plane of the fourth point was negative, then the order of the first three vertices must be reversed.
Plane plane;
plane.Set(min_vertex, max_vertex, max_triangle);
Real order = plane.PlaneTest(max_tetrahedron);
if (order > 0.0f)
{
m_vertices->push_back(min_vertex);
m_vertices->push_back(max_vertex);
m_vertices->push_back(max_triangle);
m_vertices->push_back(max_tetrahedron);
}
else
{
m_vertices->push_back(max_triangle);
m_vertices->push_back(max_vertex);
m_vertices->push_back(min_vertex);
m_vertices->push_back(max_tetrahedron);
}
//6. Return the fact that we created a non - degenerate tetrahedron of dimension 3.
m_faces->emplace_back(0, 1, 2);
m_faces->emplace_back(1, 2, 3);
m_faces->emplace_back(2, 3, 0);
m_faces->emplace_back(3, 0, 1);
return 3;
}
void ColliderPolyhedron::AddToOutsideSet(std::vector<Vector3>& vertices, OutsideSetFace& result) const
{
Vector3 face_a(m_vertices->at(result.a));
Vector3 face_b(m_vertices->at(result.b));
Vector3 face_c(m_vertices->at(result.c));
Plane plane(face_a, face_b, face_c);
auto begin = vertices.begin();
auto end = vertices.end();
std::list<std::vector<Vector3>::iterator> erase_list;
//1. For each vertex in the listVertices
for (auto it = begin; it != end; ++it)
{
//1. distance = Distance from the plane of the face to the vertex
Real distance = plane.Distance(*it);
//2. If the vertex is in the plane of the face(i.e.distance == 0)
if (Math::IsZero(distance))
{
//3. Then check to see if the vertex is coincident with any vertices of the face, and if so merge it into that face vertex.
if (Triangle::IsContainPoint(*it, face_a, face_b, face_c))
{
//merge
erase_list.push_back(it);
}
}
//4. Else If distance > 0
else if (distance > 0.0f)
{
//5. Then claim the vertex by removing it from this list and adding it the face's set of outside vertices
result.outside_vertices.push_back(*it);
erase_list.push_back(it);
}
//6. Continue the loop
}
for (auto& it : erase_list)
{
vertices.erase(it);
}
}
void ColliderPolyhedron::CalculateHorizon()
{
//If the currFace is not on the convex hull
//Mark the crossedEdge as not on the convex hull and return.
//If the currFace is visible from the eyePoint
//Mark the currFace as not on the convex hull.
//Remove all vertices from the currFace's outside set, and add them to the listUnclaimedVertices. c.
//If the crossedEdge != NULL (only for the first face) then mark the crossedEdge as not on the convex hull d.
//Cross each of the edges of currFace which are still on the convex hull
//in counterclockwise order starting from the edge after the crossedEdge
//(in the case of the first face, pick any edge to start with).
//For each currEdge recurse with the call.
}
}
| 38.095855 | 232 | 0.53985 | arian153 |
d41fd04e7f4b9da20b10302fd3eba3089453ff21 | 1,694 | cpp | C++ | c/csc-220/h2.cpp | dindoliboon/archive | a5b54367dbb57260f9230375ac81e86c5fce0d7d | [
"MIT"
] | 4 | 2020-10-02T15:24:20.000Z | 2021-11-02T04:20:38.000Z | c/csc-220/h2.cpp | dindoliboon/archive | a5b54367dbb57260f9230375ac81e86c5fce0d7d | [
"MIT"
] | null | null | null | c/csc-220/h2.cpp | dindoliboon/archive | a5b54367dbb57260f9230375ac81e86c5fce0d7d | [
"MIT"
] | 2 | 2019-10-28T01:20:07.000Z | 2020-10-02T15:25:13.000Z | /* ////////////////////////////////////////////////////////////////////////
NAME: Dindo Liboon
DATE: July 17, 2001
PROJECT: Homework #2, CSC-220-01
PURPOSE: Determine if a positive integer that is 4 to 10 digits in length
can be divisible by a variety of numbers.
COMPILE: cxx h2.cpp
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */
#include <fstream.h>
#include "h2.h"
/* ////////////////////////////////////////////////////////////////////////
INPUT: none
OUTPUT: 0 for success
PURPOSE: Core application code that will open the data file and read any
amount of integers into a buffer stored in the clsdiv class.
Integers will be tested for divisibility for certain numbers.
Results for each integer will be shown on the screen.
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */
int main()
{
ifstream fpDataIn;
clsdiv div;
/* read data file until EOF */
fpDataIn.open("h2data");
while (!fpDataIn.eof() && fpDataIn >> div.chBuffer)
{
/* check for end of integer */
if (div.chBuffer == '.')
{
/* check if array has items */
if (div.length())
{
div.printdiv();
div.reset();
}
}
else
{
/* set the next array item */
div.set();
}
}
fpDataIn.close();
/* quit program successfully */
return 0;
}
/* ////////////////////////////////////////////////////////////////////////
END OF CODE
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ */
| 30.8 | 76 | 0.403188 | dindoliboon |
d4215eb81abc80b2d6331fba1e548fca4d4838f4 | 854 | hpp | C++ | Server/levelParsing/ParsingLevel.hpp | KillianG/R-Type | e3fd801ae58fcea49ac75c400ec0a2837cb0da2e | [
"MIT"
] | 1 | 2019-08-14T12:31:50.000Z | 2019-08-14T12:31:50.000Z | Server/levelParsing/ParsingLevel.hpp | KillianG/R-Type | e3fd801ae58fcea49ac75c400ec0a2837cb0da2e | [
"MIT"
] | null | null | null | Server/levelParsing/ParsingLevel.hpp | KillianG/R-Type | e3fd801ae58fcea49ac75c400ec0a2837cb0da2e | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2018
** Epitech scolarship project (4 years remaining)
** File description:
** Made on 2018/11 by ebernard
*/
#include <map>
#include <chrono>
#include <string>
#include <vector>
#include <fstream>
#include "Server/includes/Utils.hpp"
#include "Server/Monsters/includes/IEnnemy.hpp"
namespace Game {
class ParsingLevel {
public:
ParsingLevel();
void startGame();
bool isEnd() const noexcept;
std::vector<Game::MonsterInfo> getMonster(float time);
int getLevel()const noexcept;
bool setStreamLevel(int level);
private:
bool m_end { false };
std::string m_levelPath;
float m_time;
std::ifstream m_stream;
bool m_isRunning;
int m_currentLevel;
std::multimap<float, Game::MonsterInfo> m_monsters;
};
} | 20.829268 | 62 | 0.638173 | KillianG |
d422f00ec915f9ad2cea868b0585ef64ce277d70 | 9,874 | cpp | C++ | alife/alifetests.cpp | DeanoC/hermit | 5529b1ddcbc0cdae0fa5413aa50c0c7722fb8796 | [
"MIT"
] | 1 | 2019-09-13T13:44:29.000Z | 2019-09-13T13:44:29.000Z | alife/alifetests.cpp | DeanoC/hermit | 5529b1ddcbc0cdae0fa5413aa50c0c7722fb8796 | [
"MIT"
] | null | null | null | alife/alifetests.cpp | DeanoC/hermit | 5529b1ddcbc0cdae0fa5413aa50c0c7722fb8796 | [
"MIT"
] | null | null | null | // License Summary: MIT see LICENSE file
#include "al2o3_platform/platform.h"
#include "alifetests.hpp"
#include "al2o3_memory/memory.h"
#include "world2d.hpp"
#include "al2o3_vfile/vfile.hpp"
#include "render_basics/descriptorset.h"
#include "render_basics/buffer.h"
#include "render_basics/pipeline.h"
#include "render_basics/graphicsencoder.h"
#include "render_basics/rootsignature.h"
#include "render_basics/shader.h"
#include "accel_cuda.hpp"
#include "accel_sycl.hpp"
namespace {
void DestroyRenderable(World2DRender *render);
World2DRender* MakeRenderable(World2D const* world, Render_RendererHandle renderer, Render_ROPLayout const* ropLayout) {
World2DRender* render = (World2DRender*) MEMORY_CALLOC(1, sizeof(World2DRender));
if(!render) return nullptr;
render->renderer = renderer;
uint32_t const totalVertexCount = world->width * world->height;
uint32_t const totalIndexCount = (world->width-1) * (world->height-1) * 3;
uint32_t const indexTypeSize = (totalVertexCount > 0xFFFF) ? 4u : 2u;
// build render objects
// construct static vertex buffer
Render_BufferVertexDesc const vertexDesc {
totalVertexCount,
sizeof(float) * 5,
false
};
render->vertexBuffer = Render_BufferCreateVertex(renderer, &vertexDesc);
if(!Render_BufferHandleIsValid(render->vertexBuffer)) {
DestroyRenderable(render);
return false;
}
uint8_t* vertexData = nullptr;
// MAX 64 KB stack else use the heap
if(totalVertexCount > (0xFFFF / (sizeof(float) * 5))) {
// short term alloc
vertexData = (uint8_t*) MEMORY_MALLOC(totalVertexCount * (sizeof(float) * 5));
} else {
vertexData = (uint8_t*) STACK_ALLOC(totalVertexCount * (sizeof(float) * 5));
}
float * curVertexPtr = (float*)vertexData;
for(uint32_t y = 0; y < world->height-1;++y) {
for(int32_t x = -(int32_t)(world->width/2); x < (int32_t)(world->width/2);++x) {
curVertexPtr[0] = (float)x;
curVertexPtr[1] = 0.0f;
curVertexPtr[2] = (float)y;
curVertexPtr[3] = (float)(x + world->width/2) / (float)(world->width-1);
curVertexPtr[4] = (float)y / (float)(world->height-1);
curVertexPtr += 5;
}
}
Render_BufferUpdateDesc const vertexUpdateDesc {
vertexData,
0,
totalVertexCount * sizeof(float) * 5
};
Render_BufferUpload(render->vertexBuffer, &vertexUpdateDesc);
// no need to free stack allocated ram
if(totalVertexCount > (0xFFFF / (sizeof(float) * 5))) {
MEMORY_FREE(vertexData);
}
// construct the static index buffer
Render_BufferIndexDesc const indexDesc {
totalIndexCount,
indexTypeSize,
false
};
render->indexBuffer = Render_BufferCreateIndex(renderer, &indexDesc);
if(!Render_BufferHandleIsValid(render->indexBuffer)) {
DestroyRenderable(render);
return false;
}
uint8_t* indexData = nullptr;
// MAX 64 KB stack else use the heap
if(totalIndexCount > (0xFFFF / (indexTypeSize*3))) {
// short term alloc
indexData = (uint8_t*) MEMORY_MALLOC(totalIndexCount * indexTypeSize);
} else {
indexData = (uint8_t*) STACK_ALLOC(totalIndexCount * indexTypeSize);
}
uint8_t * curIndexPtr = indexData;
for(uint32_t y = 0; y < world->height-1;++y) {
for(uint32_t x = 0; x < world->width-1;++x) {
switch(indexTypeSize) {
case 2:
((uint16_t*)curIndexPtr)[0] = (y * world->height) + x;
((uint16_t*)curIndexPtr)[1] = ((y+1) * world->height) + x;
((uint16_t*)curIndexPtr)[2] = (y * world->height) + (x+1);
curIndexPtr += 6;
break;
case 4: {
((uint32_t*)curIndexPtr)[0] = (y * world->height) + x;
((uint32_t*)curIndexPtr)[1] = ((y+1) * world->height) + x;
((uint32_t*)curIndexPtr)[2] = (y * world->height) + (x+1);
curIndexPtr += 12;
break;
}
default:
LOGERROR("Invalid index buffer type size");
break;
}
}
}
Render_BufferUpdateDesc const indexUpdateDesc {
indexData,
0,
totalIndexCount * indexTypeSize
};
Render_BufferUpload(render->indexBuffer, &indexUpdateDesc);
// no need to free stack allocated ram
if(totalIndexCount > (0xFFFF / (indexTypeSize*3))) {
MEMORY_FREE(indexData);
}
static Render_BufferUniformDesc const ubDesc{
sizeof(render->uniforms),
true
};
render->uniformBuffer = Render_BufferCreateUniform(render->renderer, &ubDesc);
if (!Render_BufferHandleIsValid(render->uniformBuffer)) {
DestroyRenderable(render);
return nullptr;
}
VFile::ScopedFile vfile = VFile::FromFile("resources/alife/world2dmoe_vertex.hlsl", Os_FM_Read);
if (!vfile) {
DestroyRenderable(render);
return nullptr;
}
VFile::ScopedFile ffile = VFile::FromFile("resources/alife/world2dmoe_fragment.hlsl", Os_FM_Read);
if (!ffile) {
DestroyRenderable(render);
return nullptr;
}
render->shader = Render_CreateShaderFromVFile(render->renderer, vfile, "VS_main", ffile, "FS_main");
if (!Render_ShaderHandleIsValid(render->shader)) {
DestroyRenderable(render);
return nullptr;
}
Render_RootSignatureDesc rootSignatureDesc{};
rootSignatureDesc.shaderCount = 1;
rootSignatureDesc.shaders = &render->shader;
rootSignatureDesc.staticSamplerCount = 0;
render->rootSignature = Render_RootSignatureCreate(render->renderer, &rootSignatureDesc);
if (!Render_RootSignatureHandleIsValid(render->rootSignature)) {
DestroyRenderable(render);
return nullptr;
}
TinyImageFormat colourFormats[] = { ropLayout->colourFormats[0] };
Render_GraphicsPipelineDesc gfxPipeDesc{};
gfxPipeDesc.shader = render->shader;
gfxPipeDesc.rootSignature = render->rootSignature;
gfxPipeDesc.vertexLayout = Render_GetStockVertexLayout(render->renderer, Render_SVL_3D_UV);
gfxPipeDesc.blendState = Render_GetStockBlendState(render->renderer, Render_SBS_OPAQUE);
if(ropLayout->depthFormat == TinyImageFormat_UNDEFINED) {
gfxPipeDesc.depthState = Render_GetStockDepthState(render->renderer, Render_SDS_IGNORE);
} else {
gfxPipeDesc.depthState = Render_GetStockDepthState(render->renderer, Render_SDS_READWRITE_LESS);
}
gfxPipeDesc.rasteriserState = Render_GetStockRasterisationState(render->renderer, Render_SRS_BACKCULL);
gfxPipeDesc.colourRenderTargetCount = 1;
gfxPipeDesc.colourFormats = colourFormats;
gfxPipeDesc.depthStencilFormat = ropLayout->depthFormat;
gfxPipeDesc.sampleCount = 1;
gfxPipeDesc.sampleQuality = 0;
gfxPipeDesc.primitiveTopo = Render_PT_TRI_LIST;
render->pipeline = Render_GraphicsPipelineCreate(render->renderer, &gfxPipeDesc);
if (!Render_PipelineHandleIsValid(render->pipeline)) {
DestroyRenderable(render);
return nullptr;
}
Render_DescriptorSetDesc const setDesc = {
render->rootSignature,
Render_DUF_PER_FRAME,
1
};
render->descriptorSet = Render_DescriptorSetCreate(render->renderer, &setDesc);
if (!Render_DescriptorSetHandleIsValid(render->descriptorSet)) {
DestroyRenderable(render);
return nullptr;
}
Render_DescriptorDesc params[1];
params[0].name = "View";
params[0].type = Render_DT_BUFFER;
params[0].buffer = render->uniformBuffer;
params[0].offset = 0;
params[0].size = sizeof(render->uniforms);
Render_DescriptorPresetFrequencyUpdated(render->descriptorSet, 0, 1, params);
return render;
}
void DestroyRenderable(World2DRender *render) {
if(!render) return;
Render_DescriptorSetDestroy(render->renderer, render->descriptorSet);
Render_PipelineDestroy(render->renderer, render->pipeline);
Render_ShaderDestroy(render->renderer, render->shader);
Render_RootSignatureDestroy(render->renderer, render->rootSignature);
Render_BufferDestroy(render->renderer, render->uniformBuffer);
Render_BufferDestroy(render->renderer, render->indexBuffer);
Render_BufferDestroy(render->renderer, render->vertexBuffer);
MEMORY_FREE(render);
}
void RenderWorld2D(World2D const * world, World2DRender* render, Render_GraphicsEncoderHandle encoder) {
// upload the uniforms
Render_BufferUpdateDesc uniformUpdate = {
&render->uniforms,
0,
sizeof(render->uniforms)
};
Render_BufferUpload(render->uniformBuffer, &uniformUpdate);
Render_GraphicsEncoderBindDescriptorSet(encoder, render->descriptorSet, 0);
Render_GraphicsEncoderBindIndexBuffer(encoder, render->indexBuffer, 0);
Render_GraphicsEncoderBindVertexBuffer(encoder, render->vertexBuffer, 0);
Render_GraphicsEncoderBindPipeline(encoder, render->pipeline);
uint32_t const totalIndexCount = (world->width-1) * (world->height-1) * 3;
Render_GraphicsEncoderDrawIndexed(encoder, totalIndexCount, 0, 0);
}
}; // end anon namespace
ALifeTests* ALifeTests::Create(Render_RendererHandle renderer, Render_ROPLayout const * targetLayout) {
ALifeTests* alt = (ALifeTests*) MEMORY_CALLOC(1, sizeof(ALifeTests));
if(!alt) {
return nullptr;
}
alt->accelCuda = AccelCUDA_Create();
alt->accelSycl = AccelSycl_Create();
alt->world2d = World2D_Create(WT_MOE, 64, 64);
if(!alt->world2d) {
Destroy(alt);
return nullptr;
}
alt->worldRender = MakeRenderable(alt->world2d, renderer, targetLayout);
if(!alt->worldRender){
Destroy(alt);
return nullptr;
}
return alt;
}
void ALifeTests::Destroy(ALifeTests* alt) {
if(!alt) return;
DestroyRenderable(alt->worldRender);
World2D_Destroy(alt->world2d);
AccelSycl_Destroy(alt->accelSycl);
AccelCUDA_Destroy(alt->accelCuda);
MEMORY_FREE(alt);
}
void ALifeTests::update(double deltaMS, Render_View const& view) {
if(worldRender) {
worldRender->uniforms.view.worldToViewMatrix = Math_LookAtMat4F(view.position, view.lookAt, view.upVector);
float const f = 1.0f / tanf(view.perspectiveFOV / 2.0f);
worldRender->uniforms.view.viewToNDCMatrix = {
f / view.perspectiveAspectWoverH, 0.0f, 0.0f, 0.0f,
0.0f, f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f,
0.0f, 0.0f, view.nearOffset, 0.0f
};
worldRender->uniforms.view.worldToNDCMatrix = Math_MultiplyMat4F(worldRender->uniforms.view.worldToViewMatrix, worldRender->uniforms.view.viewToNDCMatrix);
}
}
void ALifeTests::render(Render_GraphicsEncoderHandle encoder) {
if(worldRender) {
RenderWorld2D(world2d, worldRender, encoder);
}
}
| 31.851613 | 157 | 0.741847 | DeanoC |
d424b8f937498c573174f50aa1c4de4b42b5554d | 1,033 | cpp | C++ | arm9/source/_lua/lua.gadget.colorpicker.gradient.cpp | DuffsDevice/winds | 35f1b5fd458c527a6c372f94077e784f6fd960b2 | [
"MIT"
] | 2 | 2017-02-07T18:25:07.000Z | 2021-12-13T18:29:03.000Z | arm9/source/_lua/lua.gadget.colorpicker.gradient.cpp | DuffsDevice/winds | 35f1b5fd458c527a6c372f94077e784f6fd960b2 | [
"MIT"
] | null | null | null | arm9/source/_lua/lua.gadget.colorpicker.gradient.cpp | DuffsDevice/winds | 35f1b5fd458c527a6c372f94077e784f6fd960b2 | [
"MIT"
] | null | null | null | #include <_lua/lua.gadget.colorpicker.gradient.h>
#include <_lua/lua.func.h>
#include <_lua/lua.func.wrap.h>
using namespace _luafunc;
/*##################################
## Lua-Colorpicker ##
##################################*/
_lua_gradientcolorpicker::_lua_gradientcolorpicker( lua_State* L ) :
_lua_gadget( new _gradientColorPicker( optcheck<int>( L , 1 ) , optcheck<int>( L , 2 ) , optcheck<int>( L , 3 ) , optcheck<int>( L , 4 ) , lightcheck<_color>( L , 5 , _color::blue ) , lightcheck<_style>( L , 6 , _style() ) ) )
{}
//! Lua-button
const char _lua_gradientcolorpicker::className[] = "GradientColorPicker";
Lunar<_lua_gradientcolorpicker>::FunctionType _lua_gradientcolorpicker::methods[] = {
LUA_CLASS_FUNC_END
};
Lunar<_lua_gradientcolorpicker>::PropertyType _lua_gradientcolorpicker::properties[] = {
{ "color" , wrap( _lua_gradientcolorpicker , &_gradientColorPicker::getColor ) , wrap( _lua_gradientcolorpicker , &_gradientColorPicker::setColor ) },
LUA_CLASS_ATTR_END
}; | 44.913043 | 228 | 0.662149 | DuffsDevice |
d424c813cf67b2ffe3bd0e0737498c362f26d942 | 1,550 | cpp | C++ | examples/echo-server.cpp | bjtj/oslayer | 92cc41288a4bae8e63a680fe714806e89421df16 | [
"MIT"
] | 1 | 2020-03-08T14:25:24.000Z | 2020-03-08T14:25:24.000Z | examples/echo-server.cpp | bjtj/oslayer | 92cc41288a4bae8e63a680fe714806e89421df16 | [
"MIT"
] | null | null | null | examples/echo-server.cpp | bjtj/oslayer | 92cc41288a4bae8e63a680fe714806e89421df16 | [
"MIT"
] | null | null | null | #include <liboslayer/os.hpp>
#include <liboslayer/Socket.hpp>
#include <liboslayer/Thread.hpp>
#include <liboslayer/AutoRef.hpp>
#include <liboslayer/Text.hpp>
using namespace std;
using namespace osl;
/**
*
*/
class EchoServer : public Thread {
private:
int _port;
bool _verbose;
public:
EchoServer(int port, bool verbose) : _port(port), _verbose(verbose) {
}
virtual ~EchoServer() {
}
virtual void run() {
ServerSocket socket(_port);
socket.setReuseAddr(true);
socket.bind();
socket.listen(50);
if (_verbose) {
printf("[listen...] port : %d\n", _port);
}
while (!interrupted()) {
AutoRef<Socket> client(socket.accept());
char buffer[1024] = {0,};
try {
int len = client->recv(buffer, sizeof(buffer));
if (_verbose) {
printf("RECV: %.*s\n", len, buffer);
}
client->send(buffer, len);
client->close();
} catch (IOException e) {
printf("[ignore] exception - %s\n", e.what());
}
}
socket.close();
}
};
int main(int argc, char *argv[])
{
System::getInstance()->ignoreSigpipe();
int port = 9000;
if (argc > 1) {
port = Text::toInt(argv[1]);
}
printf("[port...] %d\n", port);
EchoServer server(port, true);
server.start();
getchar();
printf("[stop...]");
server.interrupt();
try {
Socket c(InetAddress("127.0.0.1", port));
c.connect();
c.send("x", 1);
c.close();
} catch (IOException e) {
printf("[ignore] exception - %s\n", e.what());
}
server.join();
printf("[bye]\n");
return 0;
}
| 19.871795 | 73 | 0.590323 | bjtj |
d424f265dd71f3f060b972919d0aeaf762458041 | 4,710 | cc | C++ | Fields/QualityScoreCompressor.cc | sfu-compbio/deez | 92cd56befd0c6fbd3355e75ab1747913c11ec716 | [
"BSD-3-Clause"
] | 13 | 2015-04-11T13:30:41.000Z | 2020-06-24T16:58:18.000Z | Fields/QualityScoreCompressor.cc | sfu-compbio/deez | 92cd56befd0c6fbd3355e75ab1747913c11ec716 | [
"BSD-3-Clause"
] | 1 | 2017-09-29T08:56:30.000Z | 2017-09-29T08:56:30.000Z | Fields/QualityScoreCompressor.cc | sfu-compbio/deez | 92cd56befd0c6fbd3355e75ab1747913c11ec716 | [
"BSD-3-Clause"
] | 6 | 2015-07-06T19:30:59.000Z | 2022-03-11T07:22:24.000Z | #include "QualityScore.h"
#include <cmath>
using namespace std;
#include "../Streams/Stream.h"
#include "../Streams/BzipStream.h"
QualityScoreCompressor::QualityScoreCompressor(void):
StringCompressor<QualityCompressionStream>(),
statMode(true),
offset(0)
{
memset(lossy, 0, 128 * sizeof(int));
memset(stat, 0, 128 * sizeof(int));
switch (optQuality) {
case 0:
break;
case 1:
streams[0] = make_shared<SAMCompStream<QualRange>>();
break;
case 2:
streams[0] = make_shared<ArithmeticOrder2CompressionStream<QualRange>>();
break;
default:
throw DZException("Invalid stream specified");
break;
}
const char* qualities[] = { "default", "samcomp", "arithmetic" };
LOG("Using quality mode %s", qualities[optQuality]);
}
size_t QualityScoreCompressor::shrink(char *qual, size_t len, int flag)
{
if (!len || (len == 1 && qual[0] == '*')) {
*qual = 0;
return 0;
}
if (flag & 0x10) for (size_t j = 0; j < len / 2; j++)
swap(qual[j], qual[len - j - 1]);
ssize_t sz = len;
if (sz >= 2) {
sz -= 2;
while (sz && qual[sz] == qual[len - 1])
sz--;
sz += 2;
}
qual[sz] = 0;
assert(sz > 0);
return sz;
}
int QualityScoreCompressor::getOffset()
{
return offset;
}
void QualityScoreCompressor::updateOffset(int *st)
{
if (offset) return;
for (int i = 0; i < 128; i++)
stat[i] += st[i];
}
void QualityScoreCompressor::calculateOffset()
{
if (offset) return;
offset = 64;
for (int i = 33; i < 64; i++) {
if (i < 59 && stat[i]) {
offset = 33;
break;
}
if (stat[i]) {
offset = 59;
break;
}
}
if (optLossy && statMode) {
calculateLossyTable(optLossy);
statMode = false;
}
}
void QualityScoreCompressor::offsetRecord (Record &rc)
{
assert(offset);
char *qual = (char*)rc.getQuality();
lossyTransform(qual, strlen(qual));
while (*qual) {
if (*qual < offset)
throw DZException("Quality scores out of range with L offset %d [%c]", offset, *qual);
*qual = (*qual - offset) + 1;
if (*qual >= QualRange)
throw DZException("Quality scores out of range with R offset %d [%c]", offset, *qual + offset - 1);
qual++;
}
}
void QualityScoreCompressor::outputRecords (const Array<Record> &records, Array<uint8_t> &out, size_t out_offset, size_t k)
{
ZAMAN_START(QualityScoreOutput);
out.add(offset); out_offset++;
Array<uint8_t> buffer(totalSize, MB);
for (size_t i = 0; i < k; i++) {
const char *q = records[i].getQuality();
while (*q)
buffer.add(*q), q++;
buffer.add(0);
totalSize -= (q - records[i].getQuality()) + 1;
}
compressArray(streams.front(), buffer, out, out_offset);
memset(stat, 0, 128 * sizeof(int));
offset = 0;
ZAMAN_END(QualityScoreOutput);
}
double QualityScoreCompressor::phredScore (char c, int offset)
{
return pow(10, (offset - c) / 10.0);
}
bool statSort (const pair<char, int> &a, const pair<char, int> &b)
{
return (a.second > b.second || (a.second == b.second && a.first < b.first));
}
void QualityScoreCompressor::calculateLossyTable (int percentage)
{
if (!offset)
throw DZException("Offset not calculated");
// calculate replacements
for (int c = 0; c < 128; c++)
lossy[c] = c;
// if percentage is 0% then keep original qualities
if (!percentage)
return;
vector<char> alreadyAssigned(128, 0);
// Discard all elements with >30% error
for (char hlimit = offset; 100 * phredScore(hlimit, offset) > 30; hlimit++) {
lossy[hlimit] = offset;
alreadyAssigned[hlimit] = 1;
}
// sort stats by maximum value
pair<char, int> bmm[128];
for (int i = 0; i < 128; i++)
bmm[i] = make_pair(i, stat[i]);
sort(bmm, bmm + 128, statSort);
// obtain replacement table
double p = percentage / 100.0;
for (int i = 0; i < 128 && bmm[i].second; i++) {
if (!alreadyAssigned[bmm[i].first]
&& stat[bmm[i].first] >= stat[bmm[i].first - 1]
&& stat[bmm[i].first] >= stat[bmm[i].first + 1])
{
double er = phredScore(bmm[i].first, offset);
double total = er;
char left = bmm[i].first,
right = bmm[i].first;
for (int c = bmm[i].first - 1; c >= 0; c--) {
total += phredScore(c, offset);
if (alreadyAssigned[c] || total / (bmm[i].first - c + 1) > er + (er * p)) {
left = c + 1;
break;
}
}
total = er;
for (int c = bmm[i].first + 1; c < 128; c++) {
total += phredScore(c, offset);
if (alreadyAssigned[c] || total / (c - bmm[i].first + 1) < er - (er * p)) {
right = c - 1;
break;
}
}
for (char c = left; c <= right; c++) {
lossy[c] = bmm[i].first;
alreadyAssigned[c] = 1;
}
}
}
}
void QualityScoreCompressor::lossyTransform (char *qual, size_t len)
{
if (!optLossy)
return;
if (!statMode) for (size_t i = 0; i < len; i++)
qual[i] = lossy[qual[i]];
}
| 23.432836 | 124 | 0.614013 | sfu-compbio |
d42892cc9e81c75a6ef583d1782ae4ed0e76e04e | 268 | cpp | C++ | C++11/language/class/ideone_e3Ar56.cpp | varunnagpaal/cpp | 1b7e1678d05d93227caea49b5629cadd217553de | [
"MIT"
] | 1 | 2016-12-15T12:56:41.000Z | 2016-12-15T12:56:41.000Z | C++11/language/class/ideone_e3Ar56.cpp | varunnagpaal/cpp | 1b7e1678d05d93227caea49b5629cadd217553de | [
"MIT"
] | null | null | null | C++11/language/class/ideone_e3Ar56.cpp | varunnagpaal/cpp | 1b7e1678d05d93227caea49b5629cadd217553de | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class A
{
private : int i;
public: void funct(){i++; cout<<"i:"<<i<<endl;}
void anFunct(){ cout<<"A "<<endl; }
};
int main()
{
A* ptrA = NULL;
ptrA->anFunct();
ptrA->funct();
return 0;
} | 14.888889 | 51 | 0.514925 | varunnagpaal |
d42ac706b5a8c53c96fa067469d5159dbb64dde7 | 1,068 | cpp | C++ | Stacks-and-Queues/EvaluateExpression.cpp | ssokjin/Interview-Bit | 8714d3d627eb5875f49d205af779b59ca33ab4a3 | [
"MIT"
] | 513 | 2016-08-16T12:52:14.000Z | 2022-03-30T19:32:10.000Z | Stacks-and-Queues/EvaluateExpression.cpp | ssokjin/Interview-Bit | 8714d3d627eb5875f49d205af779b59ca33ab4a3 | [
"MIT"
] | 25 | 2018-02-14T15:25:48.000Z | 2022-03-23T11:52:08.000Z | Stacks-and-Queues/EvaluateExpression.cpp | ssokjin/Interview-Bit | 8714d3d627eb5875f49d205af779b59ca33ab4a3 | [
"MIT"
] | 505 | 2016-09-02T15:04:20.000Z | 2022-03-25T06:36:31.000Z | // https://www.interviewbit.com/problems/evaluate-expression/
int Solution::evalRPN(vector<string> &A) {
// Do not write main() function.
// Do not read input, instead use the arguments to the function.
// Do not print the output, instead return values as specified
// Still have a doubt. Checkout www.interviewbit.com/pages/sample_codes/ for more details
stack<int> st;
for(int i = 0; i < A.size(); i++){
if(A[i] == "+" || A[i] == "-" || A[i] == "*" || A[i] == "/"){
int first = st.top();
st.pop();
int second = st.top();
st.pop();
if(A[i] == "+"){
st.push(second+first);
}
else if(A[i] == "-"){
st.push(second-first);
}
else if(A[i] == "*"){
st.push(second*first);
}
else{
st.push(second/first);
}
}
else{
st.push(atoi(A[i].c_str()));
}
}
return st.top();
}
| 28.105263 | 93 | 0.438202 | ssokjin |
2d72b0993658672e26f10ba381b9c13f6680f985 | 7,758 | cpp | C++ | trunk/win/Source/BT_MenuAction.cpp | dyzmapl/BumpTop | 1329ea41411c7368516b942d19add694af3d602f | [
"Apache-2.0"
] | 460 | 2016-01-13T12:49:34.000Z | 2022-02-20T04:10:40.000Z | trunk/win/Source/BT_MenuAction.cpp | dyzmapl/BumpTop | 1329ea41411c7368516b942d19add694af3d602f | [
"Apache-2.0"
] | 24 | 2016-11-07T04:59:49.000Z | 2022-03-14T06:34:12.000Z | trunk/win/Source/BT_MenuAction.cpp | dyzmapl/BumpTop | 1329ea41411c7368516b942d19add694af3d602f | [
"Apache-2.0"
] | 148 | 2016-01-17T03:16:43.000Z | 2022-03-17T12:20:36.000Z | // Copyright 2012 Google Inc. 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 "BT_Common.h"
#include "BT_BumpObject.h"
#include "BT_FileSystemActor.h"
#include "BT_MarkingMenu.h"
#include "BT_MenuAction.h"
#include "BT_MenuActionCustomizer.h"
#include "BT_OverlayComponent.h"
#include "BT_Selection.h"
#include "BT_SceneManager.h"
#include "BT_Util.h"
#include "BT_WebActor.h"
MenuAction::MenuAction()
{
}
MenuAction::MenuAction( KeyCombo combo, bool isEnabled, QString newLabel,
QString newToolTip, float newAngSpan, float newRadThickness,
float newDegPref, uint selection, ObjectType objTypeCond,
VoidCallback exeAction, MenuActionCustomizer *cust, bool isSubMenu,
bool isCheckBox, BoolCallback myCheckCondition)
{
enabled = isEnabled;
angularSpan = newAngSpan;
radiusThickness = newRadThickness;
degreePreference = newDegPref;
selectionCondition = selection;
executeAction = exeAction;
customizer = cust;
label = newLabel;
toolTip = newToolTip;
hotKey = combo;
objectTypeCondition = objTypeCond;
useObjectTypeCondition = *((uint *) &objectTypeCondition) > 0 ? true : false;
animating = false;
_isSubMenu = isSubMenu;
_isCheckBox = isCheckBox;
checkCondition = myCheckCondition;
// setup the text buffers
if (newDegPref > Ellipsis)
{
_primaryTextBuffer.setMaxBounds(QSize(256, 0));
_primaryTextBuffer.setText(newLabel);
_primaryTextBuffer.pushFlag(TextPixmapBuffer::GradientColor);
_primaryTextBuffer.setGradientColors(QColor(255, 255, 255), QColor(210, 210, 210));
_primaryTextBuffer.update();
_secondaryTextBuffer.setMaxBounds(QSize(256, 0));
_secondaryTextBuffer.setText(getHotkeyString());
_secondaryTextBuffer.pushFlag(TextPixmapBuffer::GradientColor);
_secondaryTextBuffer.setGradientColors(QColor(245, 245, 245), QColor(200, 200, 200));
_secondaryTextBuffer.update();
}
}
MenuAction::~MenuAction()
{
}
bool MenuAction::isSubMenu()
{
return _isSubMenu;
}
bool MenuAction::isCheckBox()
{
return _isCheckBox;
}
bool MenuAction::checkConditionMet() {
if(checkCondition == NULL)
return false;
return checkCondition();
}
void MenuAction::execute()
{
if (customizer)
{
// Let the customizer decide what to do
customizer->execute(this);
}else{
// Execute either the callback or the Customizer's callback
if (executeAction)
{
executeAction();
}
}
dismiss("MarkingMenu_Tooltip");
}
float MenuAction::getAngularSpan() const
{
return angularSpan;
}
QString MenuAction::getLabel() const
{
return label;
}
QString MenuAction::getHotkeyString() const
{
if (hotKey.subKeys.key > 0)
return QString("(%1)").arg(hotKey.toString());
return QString();
}
float MenuAction::getDegreePreference() const
{
return degreePreference;
}
float MenuAction::getRadiusThickness() const
{
return radiusThickness;
}
QString MenuAction::getToolTip() const
{
return toolTip;
}
MenuActionCustomizer *MenuAction::getCustomAction() const
{
return customizer;
}
KeyCombo MenuAction::getHotKey() const
{
return hotKey;
}
bool MenuAction::isEnabled()
{
return enabled;
}
void MenuAction::setEnabled(bool en)
{
enabled = en;
}
void MenuAction::setLabel(QString newLabel)
{
label = newLabel;
if (degreePreference > Ellipsis)
{
_primaryTextBuffer.setText(newLabel);
_primaryTextBuffer.update();
}
}
void MenuAction::setCustomAction(MenuActionCustomizer *cust)
{
customizer = cust;
if (cust)
{
// The customizer should update this class
cust->update(this);
}
}
void MenuAction::setHotKey(KeyCombo &combo)
{
hotKey = combo;
_secondaryTextBuffer.setText(getHotkeyString());
_secondaryTextBuffer.update();
}
void MenuAction::setToolTip(QString tip)
{
toolTip = tip;
}
void MenuAction::setAngularSpan(float val)
{
angularSpan = val;
}
void MenuAction::setRadiusThickness(float val)
{
radiusThickness = val;
}
void MenuAction::setDegreePreference(float val)
{
degreePreference = val;
}
void MenuAction::setExecutionCallback(VoidCallback callback)
{
executeAction = callback;
}
void MenuAction::update()
{
}
VoidCallback MenuAction::getExecuteAction() const
{
return executeAction;
}
bool MenuAction::operator<(const MenuAction &left) const
{
return hotKey.subKeys.key < left.getHotKey().subKeys.key;
}
bool MenuAction::isAnimating() const
{
return animating;
}
void MenuAction::refreshCustomizer()
{
if (customizer)
{
// Notify the customizer that we are registering with it
customizer->update(this);
}
}
#ifdef DXRENDER
void MenuAction::onRelease()
{
_primaryTextBuffer.onRelease();
_secondaryTextBuffer.onRelease();
}
#endif
bool MenuAction::isSelectionValid(uint cond) const
{
vector<BumpObject *> selection = sel->getBumpObjects();
uint selSize = selection.size();
ObjectType objType;
uint tempSel = selectionCondition;
// Exclude all but the type specified
if (selectionCondition & UseOnlyThisType)
{
// Remove this tag for comparison purposes
tempSel &= ~UseOnlyThisType;
if (cond & ~tempSel)
{
return false;
}
}
// Check if condition of selection meets this menu action
if (cond & selectionCondition)
{
if (useObjectTypeCondition)
{
// Try to find an object in the selection that matches the ObjectType condition
for (uint i = 0; i < selSize; i++)
{
objType = selection[i]->getObjectType();
// SPECIAL CASE for expanding virtual folders
if (objType == ObjectType(BumpActor, FileSystem, Virtual) &&
executeAction == Key_ExpandToPile)
continue;
#ifndef BTDEBUG
// hide "Reload page" action for sharing and facebook widget (but leave for web pages)
if (objType == ObjectType(BumpActor, Webpage) &&
executeAction == Key_ReloadWebActor)
{
WebActor* tempWebActor = (WebActor*) selection[i];
if (tempWebActor->isSharingWidget() || tempWebActor->isFacebookWidgetUrl())
return false;
}
#endif
// This object matches the ObjectType specified
if (objType == objectTypeCondition)
{
return true;
}
}
}else{
return true;
}
}
// Condition not Matched
return false;
}
void MenuAction::setAdditionalLabel( QString label )
{
additionalLabel = label;
if (!label.isEmpty())
_secondaryTextBuffer.setText(label);
else
_secondaryTextBuffer.setText(getHotkeyString());
_secondaryTextBuffer.update();
}
QString MenuAction::getAdditionalLabel() const
{
return additionalLabel;
}
TextPixmapBuffer * MenuAction::getPrimaryTextBuffer()
{
return &_primaryTextBuffer;
}
TextPixmapBuffer * MenuAction::getSecondaryTextBuffer()
{
return &_secondaryTextBuffer;
}
void MenuAction::setPrimaryTextFont(const QFont& font)
{
if (degreePreference > Ellipsis)
{
_primaryTextBuffer.setFont(font);
_primaryTextBuffer.update();
}
}
void MenuAction::setSecondaryTextFont(const QFont& font)
{
if (degreePreference > Ellipsis)
{
_secondaryTextBuffer.setFont(font);
_secondaryTextBuffer.update();
}
} | 22.165714 | 91 | 0.705465 | dyzmapl |
2d72c22f457c086fcf9176e0a7caf98191d7c294 | 9,073 | cc | C++ | tests/testapp/testapp_tenant.cc | nawazish-couchbase/kv_engine | 132f1bb04c9212bcac9e401d069aeee5f63ff1cd | [
"MIT",
"BSD-3-Clause"
] | null | null | null | tests/testapp/testapp_tenant.cc | nawazish-couchbase/kv_engine | 132f1bb04c9212bcac9e401d069aeee5f63ff1cd | [
"MIT",
"BSD-3-Clause"
] | null | null | null | tests/testapp/testapp_tenant.cc | nawazish-couchbase/kv_engine | 132f1bb04c9212bcac9e401d069aeee5f63ff1cd | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2021-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#include "testapp.h"
#include "testapp_client_test.h"
#include <cbsasl/password_database.h>
#include <cbsasl/user.h>
class TenantTest : public TestappClientTest {
public:
void SetUp() override {
memcached_cfg["enforce_tenant_limits_enabled"] = true;
reconfigure();
}
void TearDown() override {
memcached_cfg["enforce_tenant_limits_enabled"] = false;
reconfigure();
}
/// get the tenant-specific data for the tenant used in the unit
/// test ({"domain":"local","user":"jones"})
/// @throws std::runtime_error for errors (which would cause the calling
/// test to fail (which is what we expect))
nlohmann::json getTenantStats() {
bool found = false;
nlohmann::json ret;
adminConnection->stats(
[&found, &ret](const auto& key, const auto& value) {
if (key != R"({"domain":"local","user":"jones"})") {
throw std::runtime_error(
"Internal error: Unexpected tenant received: " +
key);
}
ret = nlohmann::json::parse(value);
found = true;
},
R"(tenants {"domain":"local","user":"jones"})");
if (!found) {
throw std::runtime_error(
"Did not find any tenant stats for jones!");
}
return ret;
}
};
INSTANTIATE_TEST_SUITE_P(TransportProtocols,
TenantTest,
::testing::Values(TransportProtocols::McbpPlain),
::testing::PrintToStringParamName());
TEST_P(TenantTest, TenantStats) {
// We should not have any tenants yet
adminConnection->stats(
[](const std::string& key, const std::string& value) -> void {
FAIL() << "We just enabled tenant stats so no one should "
"exist, but received: "
<< std::endl
<< key << " - " << value;
},
"tenants");
adminConnection->createBucket("rbac_test", "", BucketType::Memcached);
auto clone = getConnection().clone();
clone->authenticate("jones", "jonespassword", "PLAIN");
auto json = getTenantStats();
// We've not sent any commands after we authenticated
EXPECT_EQ(0, json["ingress_bytes"].get<int>());
// But we did send the reply to the AUTH so we should have
// sent 1 mcbp response header
EXPECT_EQ(sizeof(cb::mcbp::Header), json["egress_bytes"].get<int>());
EXPECT_EQ(1, json["connections"]["current"].get<int>());
EXPECT_EQ(1, json["connections"]["total"].get<int>());
clone->execute(BinprotGenericCommand{cb::mcbp::ClientOpcode::Noop});
json = getTenantStats();
EXPECT_EQ(sizeof(cb::mcbp::Header), json["ingress_bytes"].get<int>());
EXPECT_EQ(sizeof(cb::mcbp::Header) + sizeof(cb::mcbp::Header),
json["egress_bytes"].get<int>());
EXPECT_EQ(1, json["connections"]["current"].get<int>());
EXPECT_EQ(1, json["connections"]["total"].get<int>());
// Reconnect and verify that we keep the correct # for total connections
clone->reconnect();
clone->authenticate("jones", "jonespassword", "PLAIN");
json = getTenantStats();
EXPECT_EQ(sizeof(cb::mcbp::Header), json["ingress_bytes"].get<int>());
EXPECT_EQ(3 * sizeof(cb::mcbp::Header), json["egress_bytes"].get<int>());
// We can't validate the "current" connection here, reconnect
// could cause us to end up on a different front end thread
// on memcached and we can't really predict the scheduling
// so we could end up getting here _before_ the disconnect
// logic happened on the other thread (we've seen this in
// one CV unit test failure already)
EXPECT_EQ(2, json["connections"]["total"].get<int>());
if (!folly::kIsSanitize) { // NOLINT
// make sure we can rate limit. Hopefully the CV allows for 6000 noop/s
bool error = false;
while (!error) {
auto rsp = clone->execute(
BinprotGenericCommand{cb::mcbp::ClientOpcode::Noop});
if (!rsp.isSuccess()) {
EXPECT_EQ(cb::mcbp::Status::RateLimitedMaxCommands,
rsp.getStatus())
<< rsp.getDataString();
error = true;
}
}
std::this_thread::sleep_for(std::chrono::seconds{1});
auto rsp = clone->execute(
BinprotGenericCommand{cb::mcbp::ClientOpcode::Noop});
ASSERT_TRUE(rsp.isSuccess()) << to_string(rsp.getStatus());
}
// verify that we can't create as many connections that we want
bool done = false;
std::vector<std::unique_ptr<MemcachedConnection>> connections;
while (!done) {
// We should always be able to connect (as we don't know who
// the tenant is so we can't be disconnected for that)
connections.push_back(clone->clone());
// We should always be able to authenticate (we don't want to "break"
// clients by reporting authenticate error for a correct username
// password combination, but that you're out of connections)
connections.back()->authenticate("jones", "jonespassword", "PLAIN");
// But we'll disconnect you upon the first command you try to
// execute
auto rsp = connections.back()->execute(
BinprotGenericCommand(cb::mcbp::ClientOpcode::Noop));
if (!rsp.isSuccess()) {
// Command failed, so it should be rate limited
ASSERT_EQ(cb::mcbp::Status::RateLimitedMaxConnections,
rsp.getStatus());
done = true;
}
}
// Verify that the stats recorded the rate limiting
json = getTenantStats();
const auto& limited = json["rate_limited"];
EXPECT_EQ(1, limited["num_connections"].get<int>());
if (!folly::kIsSanitize) { // NOLINT
EXPECT_EQ(1, limited["num_ops_per_min"].get<int>());
}
// Verify that the number of current connections is correct:
EXPECT_EQ(10, json["connections"]["current"].get<int>());
// Close all of the connections, and verify that the current connection
// counter should drop. Multiple threads are involved so we need to
// run a loop and wait..
connections.clear();
auto timeout = std::chrono::steady_clock::now() + std::chrono::seconds(30);
int current = 0;
do {
json = getTenantStats();
current = json["connections"]["current"].get<int>();
if (current != 1) {
// back off to let the other threads run so we don't busy-wait
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
} while (current != 1 && std::chrono::steady_clock::now() < timeout);
if (current != 1) {
FAIL() << "Timed out waiting for current connections to drop to 1";
}
// verify that we can request all tenants
bool found = false;
adminConnection->stats(
[&found](const std::string& key, const std::string& value) -> void {
EXPECT_EQ("0", key);
EXPECT_NE(std::string::npos,
value.find(
R"("id":{"domain":"local","user":"jones"})"));
found = true;
},
"tenants");
ASSERT_TRUE(found) << "Expected tenant data to be found for jones";
// Verify that I can tune the tenants limits. Lower the max limit to
// 5 connections
auto& db = mcd_env->getPasswordDatabase();
auto user = db.find("jones");
auto limits = user.getLimits();
limits.num_connections = 5;
user.setLimits(limits);
db.upsert(std::move(user));
mcd_env->refreshPasswordDatabase(*adminConnection);
for (uint64_t ii = 1; ii < limits.num_connections; ++ii) {
connections.push_back(clone->clone());
connections.back()->authenticate("jones", "jonespassword", "PLAIN");
auto rsp = connections.back()->execute(
BinprotGenericCommand(cb::mcbp::ClientOpcode::Noop));
ASSERT_TRUE(rsp.isSuccess()) << "We should be able to fill the limit";
}
connections.push_back(clone->clone());
connections.back()->authenticate("jones", "jonespassword", "PLAIN");
auto rsp = connections.back()->execute(
BinprotGenericCommand(cb::mcbp::ClientOpcode::Noop));
ASSERT_EQ(cb::mcbp::Status::RateLimitedMaxConnections, rsp.getStatus())
<< rsp.getDataString();
adminConnection->deleteBucket("rbac_test");
}
| 41.619266 | 80 | 0.59385 | nawazish-couchbase |
2d7884c99a246e3606791552dc1a53326ad46bce | 12,169 | cpp | C++ | src/vision/pixel_histograms.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 3 | 2020-03-05T23:56:14.000Z | 2021-02-17T19:06:50.000Z | src/vision/pixel_histograms.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 1 | 2021-03-07T01:23:47.000Z | 2021-03-07T01:23:47.000Z | src/vision/pixel_histograms.cpp | anuranbaka/Vulcan | 56339f77f6cf64b5fda876445a33e72cd15ce028 | [
"MIT"
] | 1 | 2021-03-03T07:54:16.000Z | 2021-03-03T07:54:16.000Z | /* Copyright (C) 2010-2019, The Regents of The University of Michigan.
All rights reserved.
This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab
under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an
MIT-style License that can be found at "https://github.com/h2ssh/Vulcan".
*/
#include "vision/pixel_histograms.h"
#include "core/image.h"
#include "vision/vision_params.h"
#include <cassert>
#include <iostream>
using namespace vulcan;
using namespace vulcan::vision;
pixel_histogram_method_t convert_string_to_method(const std::string& methodString);
uint16_t calculate_bin_size(uint16_t numBins, uint16_t maxBinValue);
// Histogram comparison metrics
float histogram_intersection(const std::vector<float>& histA, const std::vector<float>& histB);
boost::shared_ptr<PixelHistogram> PixelHistogram::createPixelHistogram(pixel_histogram_method_t method,
const Image& image,
const std::vector<Point<int16_t>>& pixels,
const histogram_params_t& params)
{
boost::shared_ptr<PixelHistogram> histogram;
switch (method) {
case HISTOGRAM_OPPONENT_COLOR:
histogram.reset(new OpponentColorHistogram(params.opponentParams));
break;
case HISTOGRAM_RGB:
histogram.reset(new RGBColorHistogram(params.rgbParams));
break;
case HISTOGRAM_SIMPLE_COLOR_CONSTANCY:
histogram.reset(new SimpleColorConstancyHistogram(params.constancyParams));
break;
case HISTOGRAM_INTENSITY:
std::cerr << "ERROR:Intensity histogram not currently implemented" << std::endl;
assert(false);
break;
default:
std::cerr << "ERROR:Unknown histogram type" << std::endl;
assert(false);
break;
}
histogram->method = method;
histogram->calculateHistogram(image, pixels);
return histogram;
}
boost::shared_ptr<PixelHistogram> PixelHistogram::createPixelHistogram(const std::string& method,
const Image& image,
const std::vector<Point<int16_t>>& pixels,
const histogram_params_t& params)
{
return createPixelHistogram(convert_string_to_method(method), image, pixels, params);
}
boost::shared_ptr<PixelHistogram> PixelHistogram::copyPixelHistogram(pixel_histogram_method_t method,
const std::vector<float>& values,
const std::vector<uint16_t>& dimensions)
{
boost::shared_ptr<PixelHistogram> histogram;
switch (method) {
case HISTOGRAM_OPPONENT_COLOR:
histogram.reset(new OpponentColorHistogram(values, dimensions));
break;
case HISTOGRAM_RGB:
histogram.reset(new RGBColorHistogram(values, dimensions));
break;
case HISTOGRAM_SIMPLE_COLOR_CONSTANCY:
histogram.reset(new SimpleColorConstancyHistogram(values, dimensions));
break;
case HISTOGRAM_INTENSITY:
std::cerr << "ERROR:Intensity histogram not currently implemented" << std::endl;
assert(false);
break;
default:
std::cerr << "ERROR:Unknown histogram type" << std::endl;
assert(false);
break;
}
histogram->method = method;
return histogram;
}
boost::shared_ptr<PixelHistogram> PixelHistogram::copyPixelHistogram(const std::string& method,
const std::vector<float>& values,
const std::vector<uint16_t>& dimensions)
{
return copyPixelHistogram(convert_string_to_method(method), values, dimensions);
}
PixelHistogram::PixelHistogram(const std::vector<uint16_t>& dimensions, const std::vector<float>& values)
: dimensions(dimensions)
, values(values)
{
}
float PixelHistogram::compare(boost::shared_ptr<PixelHistogram> toCompare)
{
assert(this->method == toCompare->method);
return this->calculateHistogramSimilarity(toCompare);
}
// Implementation for RGBColorHistogram
RGBColorHistogram::RGBColorHistogram(const std::vector<float>& values, const std::vector<uint16_t>& dimensions)
: PixelHistogram(dimensions, values)
{
}
RGBColorHistogram::RGBColorHistogram(const rgb_histogram_params_t& params)
{
dimensions.resize(3);
dimensions[0] = params.rBins;
dimensions[1] = params.gBins;
dimensions[2] = params.bBins;
values.resize(params.rBins * params.gBins * params.bBins, 0);
}
void RGBColorHistogram::calculateHistogram(const Image& image, const std::vector<Point<int16_t>>& pixels)
{
int rowStride = dimensions[0];
int sliceStride = dimensions[0] * dimensions[1];
int rBinSize = calculate_bin_size(dimensions[0], 256);
int gBinSize = calculate_bin_size(dimensions[1], 256);
int bBinSize = calculate_bin_size(dimensions[2], 256);
uint8_t rValue = 0;
uint8_t gValue = 0;
uint8_t bValue = 0;
unsigned int row = 0;
unsigned int column = 0;
unsigned int slice = 0;
assert(pixels.size() > 0);
for (auto pixelIt = pixels.begin(), endIt = pixels.end(); pixelIt != endIt; ++pixelIt) {
image.getPixel(pixelIt->x, pixelIt->y, rValue, gValue, bValue);
row = rValue / rBinSize;
column = (gValue / gBinSize) * rowStride;
slice = (bValue / bBinSize) * sliceStride;
if (row + column + slice > values.size()) {
std::cerr << "ERROR:RGBHistogram:Pixel out of bounds:RGB(" << (int)rValue << ',' << (int)gValue << ','
<< (int)bValue << ")->(" << row << ',' << column << ',' << slice << ")\n";
assert(false);
}
++values[row + column + slice];
}
for (auto valueIt = values.begin(), endIt = values.end(); valueIt != endIt; ++valueIt) {
*valueIt /= pixels.size();
}
}
float RGBColorHistogram::calculateHistogramSimilarity(boost::shared_ptr<PixelHistogram> histogram)
{
return histogram_intersection(values, histogram->getValues());
}
// Implementation for OpponentColorHistogram
OpponentColorHistogram::OpponentColorHistogram(const std::vector<float>& values,
const std::vector<uint16_t>& dimensions)
: PixelHistogram(dimensions, values)
{
}
OpponentColorHistogram::OpponentColorHistogram(const opponent_color_histogram_params_t& params)
{
dimensions.resize(3);
dimensions[0] = params.rgBins;
dimensions[1] = params.byBins;
dimensions[2] = params.wbBins;
values.resize((params.rgBins * params.byBins * params.wbBins), 0);
}
void OpponentColorHistogram::calculateHistogram(const Image& image, const std::vector<Point<int16_t>>& pixels)
{
int rowStride = dimensions[0];
int sliceStride = dimensions[0] * dimensions[1];
int rgBinSize = calculate_bin_size(dimensions[0], 256);
int byBinSize = calculate_bin_size(dimensions[1], 256);
int wbBinSize = calculate_bin_size(dimensions[2], 256);
uint8_t rValue = 0;
uint8_t gValue = 0;
uint8_t bValue = 0;
unsigned int row = 0;
unsigned int column = 0;
unsigned int slice = 0;
for (auto pixelIt = pixels.begin(), endIt = pixels.end(); pixelIt != endIt; ++pixelIt) {
image.getPixel(pixelIt->x, pixelIt->y, rValue, gValue, bValue);
row = abs(rValue - gValue) / rgBinSize;
column = abs(2 * static_cast<int>(bValue) - rValue - gValue) / byBinSize;
slice = (static_cast<int>(rValue) + gValue + bValue) / wbBinSize;
std::cout << "vals:" << row << ' ' << column << ' ' << slice << " stride:" << rowStride << ' ' << sliceStride
<< '\n';
column *= rowStride;
slice *= sliceStride;
if (row + column + slice > values.size()) {
std::cerr << "ERROR:OpponentColorHistogram:Pixel out of bounds:RGB(" << (int)rValue << ',' << (int)gValue
<< ',' << (int)bValue << ")->(" << row << ',' << column << ',' << slice << ")\n";
assert(false);
}
++values[row + column + slice];
}
for (auto valueIt = values.begin(), endIt = values.end(); valueIt != endIt; ++valueIt) {
*valueIt /= pixels.size();
}
}
float OpponentColorHistogram::calculateHistogramSimilarity(boost::shared_ptr<PixelHistogram> histogram)
{
return histogram_intersection(values, histogram->getValues());
}
// Implementation for SimpleColorConstancyHistogram
SimpleColorConstancyHistogram::SimpleColorConstancyHistogram(const std::vector<float>& values,
const std::vector<uint16_t>& dimensions)
: PixelHistogram(dimensions, values)
{
}
SimpleColorConstancyHistogram::SimpleColorConstancyHistogram(const simple_color_constancy_histogram_params_t& params)
{
dimensions.resize(2);
dimensions[0] = params.rPrimeBins;
dimensions[1] = params.gPrimeBins;
values.resize((params.rPrimeBins * params.gPrimeBins), 0);
}
void SimpleColorConstancyHistogram::calculateHistogram(const Image& image, const std::vector<Point<int16_t>>& pixels)
{
int rowStride = dimensions[0];
int rBinSize = calculate_bin_size(dimensions[0], 256);
int gBinSize = calculate_bin_size(dimensions[1], 256);
uint8_t rValue = 0;
uint8_t gValue = 0;
uint8_t bValue = 0;
int pixelSum = 0;
int row = 0;
int column = 0;
for (auto pixelIt = pixels.begin(), endIt = pixels.end(); pixelIt != endIt; ++pixelIt) {
image.getPixel(pixelIt->x, pixelIt->y, rValue, gValue, bValue);
pixelSum = rValue + gValue + bValue;
row = (rValue / pixelSum) / rBinSize;
column = (gValue / pixelSum) / gBinSize;
column *= rowStride;
++values[row + column];
}
for (auto valueIt = values.begin(), endIt = values.end(); valueIt != endIt; ++valueIt) {
*valueIt /= pixels.size();
}
}
float SimpleColorConstancyHistogram::calculateHistogramSimilarity(boost::shared_ptr<PixelHistogram> histogram)
{
return histogram_intersection(values, histogram->getValues());
}
// Helpers
pixel_histogram_method_t convert_string_to_method(const std::string& methodString)
{
if (methodString == HISTOGRAM_OPPONENT_COLOR_STRING) {
return HISTOGRAM_OPPONENT_COLOR;
} else if (methodString == HISTOGRAM_RGB_STRING) {
return HISTOGRAM_RGB;
} else if (methodString == HISTOGRAM_SIMPLE_COLOR_CONSTANCY_STRING) {
return HISTOGRAM_SIMPLE_COLOR_CONSTANCY;
} else if (methodString == HISTOGRAM_INTENSITY_STRING) {
return HISTOGRAM_INTENSITY;
} else {
std::cerr << "ERROR: Unknown histogram method: " << methodString << std::endl;
assert(false);
}
return HISTOGRAM_RGB;
}
uint16_t calculate_bin_size(uint16_t numBins, uint16_t maxBinValue)
{
uint16_t binSize = maxBinValue / numBins;
// If the max value and the bin size don't divide evenly, then increase the bin size by
// to account for the extra pixels. NOTE: This is a junky solution, but it'll have to do
// for now
if (maxBinValue % numBins != 0) {
++binSize;
}
return binSize;
}
// Histogram comparison metrics
float histogram_intersection(const std::vector<float>& histA, const std::vector<float>& histB)
{
/*
* This metric comes from "Color Indexing" by Swain and Ballard, 1991
*
* Because the histograms are normalized, the histogram intersection is the
* city-block metric between the histograms. Thus, the intersection becomes:
*
* H(A, B) = 1 - 0.5*sum(abs(histA_i - histB_i))
*/
float totalDiff = 0.0f;
for (size_t n = 0; n < histA.size(); ++n) {
totalDiff += fabs(histA[n] - histB[n]);
}
return 1.0f - totalDiff / 2.0f;
}
| 31.772846 | 117 | 0.635056 | anuranbaka |
2d801bf2929bf1817171cb0d2ad850387d27862b | 4,033 | hpp | C++ | rcff/include/CXKJ/RCF/Filter.hpp | DayBreakZhang/CXKJ_Code | c7caab736313f029324f1c95714f5a94b2589076 | [
"Apache-2.0"
] | null | null | null | rcff/include/CXKJ/RCF/Filter.hpp | DayBreakZhang/CXKJ_Code | c7caab736313f029324f1c95714f5a94b2589076 | [
"Apache-2.0"
] | null | null | null | rcff/include/CXKJ/RCF/Filter.hpp | DayBreakZhang/CXKJ_Code | c7caab736313f029324f1c95714f5a94b2589076 | [
"Apache-2.0"
] | null | null | null |
//******************************************************************************
// RCF - Remote Call Framework
//
// Copyright (c) 2005 - 2019, Delta V Software. All rights reserved.
// http://www.deltavsoft.com
//
// RCF is distributed under dual licenses - closed source or GPL.
// Consult your particular license for conditions of use.
//
// If you have not purchased a commercial license, you are using RCF
// under GPL terms.
//
// Version: 3.1
// Contact: support <at> deltavsoft.com
//
//******************************************************************************
#ifndef INCLUDE_RCF_FILTER_HPP
#define INCLUDE_RCF_FILTER_HPP
#include <string>
#include <vector>
#include <memory>
#include <RCF/Export.hpp>
namespace RCF {
// collect these constants here so we can avoid collisions
static const int RcfFilter_Unknown = 0;
static const int RcfFilter_Identity = 1;
static const int RcfFilter_OpenSsl = 2;
static const int RcfFilter_ZlibCompressionStateless = 3;
static const int RcfFilter_ZlibCompressionStateful = 4;
static const int RcfFilter_SspiNtlm = 5;
static const int RcfFilter_SspiKerberos = 6;
static const int RcfFilter_SspiNegotiate = 7;
static const int RcfFilter_SspiSchannel = 8;
static const int RcfFilter_Xor = 101;
class Filter;
class ByteBuffer;
typedef std::shared_ptr<Filter> FilterPtr;
class RCF_EXPORT Filter
{
public:
Filter();
virtual ~Filter();
virtual void resetState();
// TODO: for generality, should take a vector<ByteBuffer> &
// (applicable if message arrives fragmented through the transport)
// BTW, bytesRequested is meaningful if byteBuffer is empty
virtual void read(
const ByteBuffer &byteBuffer,
std::size_t bytesRequested) = 0;
virtual void write(const std::vector<ByteBuffer> &byteBuffers) = 0;
virtual void onReadCompleted(const ByteBuffer &byteBuffer) = 0;
virtual void onWriteCompleted(std::size_t bytesTransferred) = 0;
virtual int getFilterId() const = 0;
void setPreFilter(Filter &preFilter);
void setPostFilter(Filter &postFilter);
virtual std::size_t getFrameSize()
{
return 0;
}
protected:
Filter &getPreFilter();
Filter &getPostFilter();
Filter *mpPreFilter;
Filter *mpPostFilter;
};
class RCF_EXPORT IdentityFilter : public Filter
{
public:
void read(const ByteBuffer &byteBuffer, std::size_t bytesRequested);
void write(const std::vector<ByteBuffer> &byteBuffers);
void onReadCompleted(const ByteBuffer &byteBuffer);
void onWriteCompleted(std::size_t bytesTransferred);
virtual int getFilterId() const;
};
class RcfServer;
class FilterFactory
{
public:
virtual ~FilterFactory()
{}
virtual FilterPtr createFilter(RcfServer & server) = 0;
virtual int getFilterId() = 0;
};
typedef std::shared_ptr<FilterFactory> FilterFactoryPtr;
RCF_EXPORT void connectFilters(const std::vector<FilterPtr> &filters);
RCF_EXPORT bool filterData(
const std::vector<ByteBuffer> &unfilteredData,
std::vector<ByteBuffer> &filteredData,
const std::vector<FilterPtr> &filters);
RCF_EXPORT bool unfilterData(
const ByteBuffer &filteredByteBuffer,
std::vector<ByteBuffer> &unfilteredByteBuffers,
std::size_t unfilteredDataLen,
const std::vector<FilterPtr> &filters);
RCF_EXPORT bool unfilterData(
const ByteBuffer &filteredByteBuffer,
ByteBuffer &unfilteredByteBuffer,
std::size_t unfilteredDataLen,
const std::vector<FilterPtr> &filters);
} // namespace RCF
#endif // ! INCLUDE_RCF_FILTER_HPP
| 29.437956 | 80 | 0.617654 | DayBreakZhang |
2d8313665656f9a50b9496664c3cecd033d5f6ec | 6,028 | cpp | C++ | custom_conf/etc/calamares/src/calamares/VariantModel.cpp | ix-os/IXOS | 840abf7e022f46073d898fed5adb667bb5cb7166 | [
"CC0-1.0"
] | null | null | null | custom_conf/etc/calamares/src/calamares/VariantModel.cpp | ix-os/IXOS | 840abf7e022f46073d898fed5adb667bb5cb7166 | [
"CC0-1.0"
] | 13 | 2020-07-30T19:55:36.000Z | 2020-12-07T16:57:23.000Z | custom_conf/etc/calamares/src/calamares/VariantModel.cpp | ix-os/IXOS | 840abf7e022f46073d898fed5adb667bb5cb7166 | [
"CC0-1.0"
] | null | null | null | /* === This file is part of Calamares - <https://github.com/calamares> ===
*
* Copyright 2019, Adriaan de Groot <groot@kde.org>
*
* Calamares 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 3 of the License, or
* (at your option) any later version.
*
* Calamares 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 Calamares. If not, see <http://www.gnu.org/licenses/>.
*/
#include "VariantModel.h"
static void
overallLength( const QVariant& item, quintptr& c, quintptr parent, VariantModel::IndexVector* skiplist )
{
if ( skiplist )
{
skiplist->append( parent );
}
parent = c++;
if ( item.canConvert< QVariantList >() )
{
for ( const auto& subitem : item.toList() )
{
overallLength( subitem, c, parent, skiplist );
}
}
else if ( item.canConvert< QVariantMap >() )
{
for ( const auto& subitem : item.toMap() )
{
overallLength( subitem, c, parent, skiplist );
}
}
}
static quintptr
findNth( const VariantModel::IndexVector& skiplist, quintptr value, int n )
{
constexpr const quintptr invalid_index = static_cast< quintptr >( -1 );
if ( n < 0 )
{
return invalid_index;
}
int index = static_cast< int >( value );
while ( ( n >= 0 ) && ( index < skiplist.count() ) )
{
if ( skiplist[ index ] == value )
{
if ( --n < 0 )
{
// It's bigger than 0
return static_cast< quintptr >( index );
}
}
index++;
}
return invalid_index;
}
VariantModel::VariantModel( const QVariant* p )
: m_p( p )
{
reload();
}
VariantModel::~VariantModel() {}
void
VariantModel::reload()
{
constexpr const quintptr invalid_index = static_cast< quintptr >( -1 );
quintptr x = 0;
m_rows.clear(); // Start over
if ( m_rows.capacity() < 64 )
{
m_rows.reserve( 64 ); // Start reasonably-sized
}
overallLength( *m_p, x, invalid_index, &m_rows );
}
int
VariantModel::columnCount( const QModelIndex& ) const
{
return 2;
}
int
VariantModel::rowCount( const QModelIndex& index ) const
{
quintptr p = index.isValid() ? index.internalId() : 0;
return m_rows.count( p );
}
QModelIndex
VariantModel::index( int row, int column, const QModelIndex& parent ) const
{
quintptr p = 0;
if ( parent.isValid() )
{
if ( inRange( parent ) )
{
p = parent.internalId();
}
}
return createIndex( row, column, findNth( m_rows, p, row ) );
}
static inline quintptr
deref( const VariantModel::IndexVector& v, quintptr i )
{
return v[ static_cast< int >( i ) ];
}
QModelIndex
VariantModel::parent( const QModelIndex& index ) const
{
if ( !index.isValid() || !inRange( index ) )
{
return QModelIndex();
}
quintptr p = deref( m_rows, index.internalId() );
if ( p == 0 )
{
return QModelIndex();
}
if ( !inRange( p ) )
{
return QModelIndex();
}
quintptr p_pid = deref( m_rows, p );
int row = 0;
for ( int i = static_cast< int >( p_pid ); i < static_cast< int >( p ); ++i )
{
if ( m_rows[ i ] == p_pid )
{
row++;
}
}
return createIndex( row, index.column(), p );
}
QVariant
VariantModel::data( const QModelIndex& index, int role ) const
{
if ( role != Qt::DisplayRole )
{
return QVariant();
}
if ( !index.isValid() )
{
return QVariant();
}
if ( ( index.column() < 0 ) || ( index.column() > 1 ) )
{
return QVariant();
}
if ( !inRange( index ) )
{
return QVariant();
}
const QVariant thing = underlying( parent( index ) );
if ( !thing.isValid() )
{
return QVariant();
}
if ( thing.canConvert< QVariantMap >() )
{
QVariantMap the_map = thing.toMap();
const auto key = the_map.keys().at( index.row() );
if ( index.column() == 0 )
{
return key;
}
else
{
return the_map[ key ];
}
}
else if ( thing.canConvert< QVariantList >() )
{
if ( index.column() == 0 )
{
return index.row();
}
else
{
QVariantList the_list = thing.toList();
return the_list.at( index.row() );
}
}
else
{
if ( index.column() == 0 )
{
return QVariant();
}
else
{
return thing;
}
}
}
QVariant
VariantModel::headerData( int section, Qt::Orientation orientation, int role ) const
{
if ( role != Qt::DisplayRole )
{
return QVariant();
}
if ( orientation == Qt::Horizontal )
{
if ( section == 0 )
{
return tr( "Key" );
}
else if ( section == 1 )
{
return tr( "Value" );
}
else
{
return QVariant();
}
}
else
{
return QVariant();
}
}
const QVariant
VariantModel::underlying( const QModelIndex& index ) const
{
if ( !index.isValid() )
{
return *m_p;
}
const auto& thing = underlying( parent( index ) );
if ( thing.canConvert< QVariantMap >() )
{
const auto& the_map = thing.toMap();
return the_map[ the_map.keys()[ index.row() ] ];
}
else if ( thing.canConvert< QVariantList >() )
{
return thing.toList()[ index.row() ];
}
else
{
return thing;
}
}
| 21.451957 | 104 | 0.53633 | ix-os |
2d8832ec13c0f3c2d2d0e1ffb37515a27b7042ab | 710 | cpp | C++ | Leetcode Daily Challenge/June-2021/16. Generate Parentheses.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 5 | 2021-08-10T18:47:49.000Z | 2021-08-21T15:42:58.000Z | Leetcode Daily Challenge/June-2021/16. Generate Parentheses.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 2 | 2022-02-25T13:36:46.000Z | 2022-02-25T14:06:44.000Z | Leetcode Daily Challenge/June-2021/16. Generate Parentheses.cpp | Akshad7829/DataStructures-Algorithms | 439822c6a374672d1734e2389d3fce581a35007d | [
"MIT"
] | 1 | 2021-08-11T06:36:42.000Z | 2021-08-11T06:36:42.000Z | /*
Generate Parentheses
====================
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
*/
class Solution
{
public:
void dfs(int n, int o, int c, vector<string> &ans, string stn)
{
if (o == n && c == n)
{
ans.push_back(stn);
return;
}
if (o < n)
dfs(n, o + 1, c, ans, stn + "(");
if (c < o)
dfs(n, o, c + 1, ans, stn + ")");
}
vector<string> generateParenthesis(int n)
{
vector<string> ans;
dfs(n, 0, 0, ans, "");
return ans;
}
};
| 16.511628 | 103 | 0.495775 | Akshad7829 |
2d8a892d31f025bba860efd08d427af16cdeba5f | 7,124 | cpp | C++ | src/qml/qt_native/contractfilterproxy.cpp | user00000001/tesramain | ddd02da923da2f9bc9dfddc1a8b177e1cadfc341 | [
"MIT"
] | 10 | 2018-06-07T13:51:04.000Z | 2020-03-12T18:27:12.000Z | src/qml/qt_native/contractfilterproxy.cpp | user00000001/tesramain | ddd02da923da2f9bc9dfddc1a8b177e1cadfc341 | [
"MIT"
] | null | null | null | src/qml/qt_native/contractfilterproxy.cpp | user00000001/tesramain | ddd02da923da2f9bc9dfddc1a8b177e1cadfc341 | [
"MIT"
] | 6 | 2018-10-23T03:12:28.000Z | 2020-03-14T16:07:54.000Z | #include "contractfilterproxy.h"
#include "contracttablemodel.h"
#include "guiutil.h"
#include "csvmodelwriter.h"
#include "ui_interface.h"
#include <script/standard.h>
#include <base58.h>
#include <wallet.h>
ContractFilterProxy::ContractFilterProxy(QObject *parent) : QSortFilterProxyModel(parent)
{
}
void ContractFilterProxy::sortColumn(QString roleName, Qt::SortOrder order)
{
ContractTableModel::ColumnIndex ci;
if(roleName == "label")
ci = ContractTableModel::Label;
else if(roleName == "address")
ci = ContractTableModel::Address;
else if(roleName == "abi")
ci = ContractTableModel::ABI;
sort(ci,order);
}
void ContractFilterProxy::exportClicked()
{
QString filename = GUIUtil::getSaveFileName(NULL,
tr("Export Contract List"), QString(),
tr("Comma separated file (*.csv)"), NULL);
if (filename.isNull())
return;
CSVModelWriter writer(filename);
// name, column, role
writer.setModel(this);
writer.addColumn("Label", ContractTableModel::Label, Qt::EditRole);
writer.addColumn("Address", ContractTableModel::Address, Qt::EditRole);
writer.addColumn("ABI", ContractTableModel::ABI, Qt::EditRole);
if (writer.write()) {
emit message(tr("Exporting Successful"), tr("File exported."),
CClientUIInterface::MSG_INFORMATION);
}
else {
emit message(tr("Exporting Failed"), tr("There was an error trying to save the contract list to %1. Please try again.").arg(filename),
CClientUIInterface::MSG_ERROR);
}
}
QString ContractFilterProxy::saveContract(int mode, const QString &label, const QString &contract,const QString &abiStr,int row )
{
QString address;
ContractTableModel *sourceModel_ = static_cast<ContractTableModel *> (sourceModel());
switch (mode) {
case 0://new
address = sourceModel_->addRow(
label,
contract,
abiStr);
break;
case 1://edit
sourceModel_->setData(sourceModel_->index(mapToSource(index(row,0)).row(),(int)ContractTableModel::Label),label,Qt::EditRole);
sourceModel_->setData(sourceModel_->index(mapToSource(index(row,0)).row(),(int)ContractTableModel::Address),contract,Qt::EditRole);
sourceModel_->setData(sourceModel_->index(mapToSource(index(row,0)).row(),(int)ContractTableModel::ABI),abiStr,Qt::EditRole);
break;
}
if( (mode == 0) && address.isEmpty())
{
return GetAddressStatus();
}
return "ok";
}
QString ContractFilterProxy::GetAddressStatus()
{
ContractTableModel *sourceModel_ = static_cast<ContractTableModel *> (sourceModel());
switch (sourceModel_->getEditStatus()) {
case ContractTableModel::OK:
return tr("Failed with unknown reason.");
case ContractTableModel::NO_CHANGES:
return tr("No changes were made during edit operation.");
case ContractTableModel::DUPLICATE_ADDRESS:
return tr("The entered address is already in the address book.");
}
}
void ContractFilterProxy::deleteContract(int row)
{
removeRows(row,1);
}
QVariant ContractFilterProxy::getData(QString roleName, int sourceRow)
{
if(roleName == "address"){
QModelIndex index_ = mapToSource(this->index(sourceRow,0));
return index_.data(ContractTableModel::AddressRole).toString();
}
else if(roleName == "label")
{
QModelIndex index_ = mapToSource(this->index(sourceRow,0));
return index_.data(ContractTableModel::LabelRole).toString();
}
else if(roleName == "abi")
{
QModelIndex index_ = mapToSource(this->index(sourceRow,0));
return index_.data(ContractTableModel::ABIRole).toString();
}
}
QString ContractFilterProxy::updateABI(const QString& address)
{
ContractTableModel *sourceModel_ = static_cast<ContractTableModel *>(sourceModel());
return sourceModel_->abiForAddress(address);
}
int ContractFilterProxy::lookupAddress(const QString &address) const
{
ContractTableModel *sourceModel_ = static_cast<ContractTableModel *>(sourceModel());
return sourceModel_->lookupAddress(address);
}
//-----------------addressList----------------
void ContractFilterProxy::on_refresh()
{
m_stringList.clear();
vector<COutput> vecOutputs;
assert(pwalletMain != NULL);
{
// Fill the list with UTXO
LOCK2(cs_main, pwalletMain->cs_wallet);
// Add all available addresses if 0 address ballance for token is enabled
if(m_addressTableModel)
{
// Fill the list with user defined address
for(int row = 0; row < m_addressTableModel->rowCount(); row++)
{
QModelIndex index = m_addressTableModel->index(row, AddressTableModel::Address);
QString strAddress = m_addressTableModel->data(index,Qt::EditRole).toString();
QString type = m_addressTableModel->data(index, AddressTableModel::TypeRole).toString();
if(type == AddressTableModel::Receive)
{
appendAddress(strAddress);
}
}
// Include zero or unconfirmed coins too
pwalletMain->AvailableCoins(vecOutputs, false, NULL, true);
}
else
{
// List only the spendable coins
pwalletMain->AvailableCoins(vecOutputs);
}
for(const COutput& out : vecOutputs) {
CTxDestination address;
const CScript& scriptPubKey = out.tx->vout[out.i].scriptPubKey;
bool fValidAddress = ExtractDestination(scriptPubKey, address);
if (fValidAddress)
{
QString strAddress = QString::fromStdString(CBitcoinAddress(address).ToString());
appendAddress(strAddress);
}
}
}
//TODO: may need to update the current picked address in qml
emit addressListChanged();
}
void ContractFilterProxy::appendAddress(const QString &strAddress)
{
CTxDestination address = CBitcoinAddress(strAddress.toStdString()).Get();
if(!IsValidContractSenderAddress(address))
return;
if(!m_stringList.contains(strAddress) && IsMine(*pwalletMain, address))
{
m_stringList.append(strAddress);
}
}
void ContractFilterProxy::setAddressTableModel(AddressTableModel *addreddTableModel)
{
ContractTableModel *sourceModel_ = static_cast<ContractTableModel *>(sourceModel());
m_addressTableModel = addreddTableModel;
if(m_addressTableModel)
{
disconnect(m_addressTableModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(on_refresh()));
disconnect(m_addressTableModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(on_refresh()));
}
connect(m_addressTableModel, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(on_refresh()));
connect(m_addressTableModel, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(on_refresh()));
on_refresh();
}
| 30.973913 | 142 | 0.654969 | user00000001 |
2d8ca50122c469f7281da9005f2aea00322009e5 | 375 | cc | C++ | source/pkgsrc/devel/gearmand/patches/patch-libgearman-server__log.cc | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | 1 | 2021-11-20T22:46:39.000Z | 2021-11-20T22:46:39.000Z | source/pkgsrc/devel/gearmand/patches/patch-libgearman-server__log.cc | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | null | null | null | source/pkgsrc/devel/gearmand/patches/patch-libgearman-server__log.cc | Scottx86-64/dotfiles-1 | 51004b1e2b032664cce6b553d2052757c286087d | [
"Unlicense"
] | null | null | null | $NetBSD: patch-libgearman-server__log.cc,v 1.1 2013/10/04 07:03:37 fhajny Exp $
alloca.h is a linux-ism
--- libgearman-server/log.cc.orig 2013-05-04 09:34:54.000000000 +0000
+++ libgearman-server/log.cc
@@ -54,7 +54,7 @@
#include <ctime>
#include <pthread.h>
-#ifdef _WIN32
+#if defined(_WIN32) || defined(__NetBSD__)
# include <malloc.h>
#else
# include <alloca.h>
| 23.4375 | 79 | 0.690667 | Scottx86-64 |
2d8d8028a0c63d30214faa2ed6d1d8b008e4e55d | 5,953 | hpp | C++ | include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/Polygon.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/Polygon.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/ProBuilder/Poly2Tri/Polygon.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:22 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Object
#include "System/Object.hpp"
// Including type: UnityEngine.ProBuilder.Poly2Tri.Triangulatable
#include "UnityEngine/ProBuilder/Poly2Tri/Triangulatable.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
// Forward declaring type: IList`1<T>
template<typename T>
class IList_1;
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
// Forward declaring type: IList`1<T>
template<typename T>
class IList_1;
// Forward declaring type: IEnumerable`1<T>
template<typename T>
class IEnumerable_1;
}
// Forward declaring namespace: UnityEngine::ProBuilder::Poly2Tri
namespace UnityEngine::ProBuilder::Poly2Tri {
// Forward declaring type: TriangulationPoint
class TriangulationPoint;
// Forward declaring type: DelaunayTriangle
class DelaunayTriangle;
// Forward declaring type: PolygonPoint
class PolygonPoint;
// Forward declaring type: TriangulationMode
struct TriangulationMode;
// Forward declaring type: TriangulationContext
class TriangulationContext;
}
// Completed forward declares
// Type namespace: UnityEngine.ProBuilder.Poly2Tri
namespace UnityEngine::ProBuilder::Poly2Tri {
// Autogenerated type: UnityEngine.ProBuilder.Poly2Tri.Polygon
class Polygon : public ::Il2CppObject, public UnityEngine::ProBuilder::Poly2Tri::Triangulatable {
public:
// protected System.Collections.Generic.List`1<UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint> _points
// Offset: 0x10
System::Collections::Generic::List_1<UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint*>* points;
// protected System.Collections.Generic.List`1<UnityEngine.ProBuilder.Poly2Tri.TriangulationPoint> _steinerPoints
// Offset: 0x18
System::Collections::Generic::List_1<UnityEngine::ProBuilder::Poly2Tri::TriangulationPoint*>* steinerPoints;
// protected System.Collections.Generic.List`1<UnityEngine.ProBuilder.Poly2Tri.Polygon> _holes
// Offset: 0x20
System::Collections::Generic::List_1<UnityEngine::ProBuilder::Poly2Tri::Polygon*>* holes;
// protected System.Collections.Generic.List`1<UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle> _triangles
// Offset: 0x28
System::Collections::Generic::List_1<UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle*>* triangles;
// public System.Void .ctor(System.Collections.Generic.IList`1<UnityEngine.ProBuilder.Poly2Tri.PolygonPoint> points)
// Offset: 0x19181AC
static Polygon* New_ctor(System::Collections::Generic::IList_1<UnityEngine::ProBuilder::Poly2Tri::PolygonPoint*>* points);
// public System.Void .ctor(System.Collections.Generic.IEnumerable`1<UnityEngine.ProBuilder.Poly2Tri.PolygonPoint> points)
// Offset: 0x1918554
static Polygon* New_ctor(System::Collections::Generic::IEnumerable_1<UnityEngine::ProBuilder::Poly2Tri::PolygonPoint*>* points);
// public System.Void AddHole(UnityEngine.ProBuilder.Poly2Tri.Polygon poly)
// Offset: 0x19185E8
void AddHole(UnityEngine::ProBuilder::Poly2Tri::Polygon* poly);
// public UnityEngine.ProBuilder.Poly2Tri.TriangulationMode get_TriangulationMode()
// Offset: 0x19185E0
// Implemented from: UnityEngine.ProBuilder.Poly2Tri.Triangulatable
// Base method: UnityEngine.ProBuilder.Poly2Tri.TriangulationMode Triangulatable::get_TriangulationMode()
UnityEngine::ProBuilder::Poly2Tri::TriangulationMode get_TriangulationMode();
// public System.Collections.Generic.IList`1<UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle> get_Triangles()
// Offset: 0x191868C
// Implemented from: UnityEngine.ProBuilder.Poly2Tri.Triangulatable
// Base method: System.Collections.Generic.IList`1<UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle> Triangulatable::get_Triangles()
System::Collections::Generic::IList_1<UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle*>* get_Triangles();
// public System.Void AddTriangle(UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle t)
// Offset: 0x1918694
// Implemented from: UnityEngine.ProBuilder.Poly2Tri.Triangulatable
// Base method: System.Void Triangulatable::AddTriangle(UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle t)
void AddTriangle(UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle* t);
// public System.Void AddTriangles(System.Collections.Generic.IEnumerable`1<UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle> list)
// Offset: 0x19186FC
// Implemented from: UnityEngine.ProBuilder.Poly2Tri.Triangulatable
// Base method: System.Void Triangulatable::AddTriangles(System.Collections.Generic.IEnumerable`1<UnityEngine.ProBuilder.Poly2Tri.DelaunayTriangle> list)
void AddTriangles(System::Collections::Generic::IEnumerable_1<UnityEngine::ProBuilder::Poly2Tri::DelaunayTriangle*>* list);
// public System.Void Prepare(UnityEngine.ProBuilder.Poly2Tri.TriangulationContext tcx)
// Offset: 0x1918764
// Implemented from: UnityEngine.ProBuilder.Poly2Tri.Triangulatable
// Base method: System.Void Triangulatable::Prepare(UnityEngine.ProBuilder.Poly2Tri.TriangulationContext tcx)
void Prepare(UnityEngine::ProBuilder::Poly2Tri::TriangulationContext* tcx);
}; // UnityEngine.ProBuilder.Poly2Tri.Polygon
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::Poly2Tri::Polygon*, "UnityEngine.ProBuilder.Poly2Tri", "Polygon");
#pragma pack(pop)
| 55.12037 | 157 | 0.77104 | Futuremappermydud |
2d8e8ef8d0b0dd8e2a485f948d26d76631be74e1 | 7,202 | cpp | C++ | ioserver/src/ioserver/serialport/AsyncSerialPort.cpp | kaliatech/r7-ioserver | 23612ef721a7bf7a8049f3c25fcf46b1fd5b5c62 | [
"MIT"
] | 1 | 2018-08-21T12:05:04.000Z | 2018-08-21T12:05:04.000Z | ioserver/src/ioserver/serialport/AsyncSerialPort.cpp | kaliatech/r7-ioserver | 23612ef721a7bf7a8049f3c25fcf46b1fd5b5c62 | [
"MIT"
] | null | null | null | ioserver/src/ioserver/serialport/AsyncSerialPort.cpp | kaliatech/r7-ioserver | 23612ef721a7bf7a8049f3c25fcf46b1fd5b5c62 | [
"MIT"
] | null | null | null | #include "ioserver/serialport/AsyncSerialPort.h"
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include "ioserver/serialport/AsyncSerialEvent.h"
#include "easyloggingpp/easylogging++.h"
namespace r7 {
AsyncSerialPort::AsyncSerialPort() :
io_service(),
port(io_service),
serialPortOpen(false),
_readDataBuffer(1024),
writeBufferSize(0)
{
onAsyncReadFunctor = boost::bind( &AsyncSerialPort::onAsyncReadComplete,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred);
onAsyncWriteFunctor = boost::bind( &AsyncSerialPort::onAsyncWriteComplete,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred);
}
AsyncSerialPort::~AsyncSerialPort()
{
io_service.stop();
if(isOpen())
{
try {
close();
} catch(...)
{
LOG(ERROR) << "Error closing serial port";
}
}
eventSignal.disconnect_all_slots();
}
void AsyncSerialPort::open( const std::string& devname,
unsigned int baud_rate,
boost::asio::serial_port_base::parity opt_parity,
boost::asio::serial_port_base::character_size opt_csize,
boost::asio::serial_port_base::flow_control opt_flow,
boost::asio::serial_port_base::stop_bits opt_stop)
{
if(isOpen())
{
close();
}
//setErrorStatus(true);//If an exception is thrown, error_ remains true
this->portStr = devname;
port.open(portStr);
port.set_option(boost::asio::serial_port_base::baud_rate(baud_rate));
port.set_option(opt_parity);
port.set_option(opt_csize);
port.set_option(opt_flow);
port.set_option(opt_stop);
//setErrorStatus(false);//If we get here, no error
serialPortOpen=true; //Port is now open
LOG(DEBUG) << "Serial port: " << portStr << " opened.";
}
void AsyncSerialPort::run_io_service()
{
boost::asio::io_service::work work(io_service); //keeps service running even if no operations ...alternatively could queue up 1st read operation maybe
try
{
io_service.run();
LOG(DEBUG) << "SerialPort io_service run is exiting.";
}
catch (...)
{
//would be better to set an error status
LOG(ERROR) << "Unexpected exception while running serial port io_service.";
close(); //alternatively, keep running
}
}
void AsyncSerialPort::stop_io_service() {
io_service.stop() ;
}
bool AsyncSerialPort::isOpen()
{
return serialPortOpen;
}
void AsyncSerialPort::close()
{
serialPortOpen = false;
port.close();
LOG(DEBUG) << "Serial port: " << this->portStr << " closed.";
}
void AsyncSerialPort::write(const std::vector<unsigned char>& data)
{
// if (!port.is_open()) {
// LOG(DEBUG) << "Underlying serial port not open while writing.";
// }
if (!isOpen()) {
LOG(DEBUG) << "Logical serial port not open while writing.";
return;
}
//scope for the lock
{
boost::lock_guard<boost::mutex> l(writeQueueMutex);
writeQueue.insert(writeQueue.end(),data.begin(),data.end());
}
io_service.post(boost::bind(&AsyncSerialPort::doAsyncWrites, this));
}
void AsyncSerialPort::doAsyncWrites()
{
//If a write operation is already in progress, do nothing
if(writeBufferSize==0)
{
boost::lock_guard<boost::mutex> l(writeQueueMutex);
writeBufferSize=writeQueue.size();
writeBuffer.reset(new unsigned char[writeQueue.size()]);
std::copy(writeQueue.begin(), writeQueue.end(), writeBuffer.get());
writeQueue.clear();
boost::asio::async_write( port,
boost::asio::buffer(writeBuffer.get(),writeBufferSize),
onAsyncWriteFunctor);
}
}
void AsyncSerialPort::onAsyncWriteComplete(const boost::system::error_code& error, std::size_t bytes_transferred)
{
if(error)
{
LOG(ERROR) << "Error writing to serial port. " << error.category().name() << "-" << error.message() << "-" << error.value();
if(!isOpen()) return;
//If error occurs we clear the writeBuffer? Perhaps should check bytes_transferred?
LOG(DEBUG) << "Clearing write buffer. Bytes transferred before error: " << bytes_transferred;
boost::lock_guard<boost::mutex> l(writeQueueMutex);
writeBuffer.reset();
writeBufferSize=0;
//TODO: Should probably eventually make this configurable, or responsibility of user of this class. i.e.
// onAsyncError(error)
this->close();
//TODO: Should we check writeQueue and try to automatically reopen/continue?
return;
}
// boost::lock_guard<boost::mutex> l(writeQueueMutex);
// if(writeQueue.empty())
// {
// writeBuffer.reset();
// writeBufferSize=0;
// return;
// }
boost::lock_guard<boost::mutex> l(writeQueueMutex);
writeBuffer.reset();
writeBufferSize=0;
if(!writeQueue.empty())
{
io_service.post(boost::bind(&AsyncSerialPort::doAsyncWrites, this));
}
}
void AsyncSerialPort::read(unsigned int numBytes)
{
if (!isOpen()) return;
io_service.post(boost::bind(&AsyncSerialPort::doAsyncRead, this, numBytes));
}
void AsyncSerialPort::doAsyncRead(unsigned int numBytes)
{
boost::asio::async_read(port,
boost::asio::buffer(_readDataBuffer, numBytes),
onAsyncReadFunctor);
}
void AsyncSerialPort::onAsyncReadComplete(const boost::system::error_code& error, std::size_t bytes_transferred)
{
LOG(DEBUG) << "onAsyncReadComplete";
if(error)
{
//error can be true because the serial port was closed
if(!isOpen()) return;
#ifdef __APPLE__
if(error.value()==45)
{
//Bug on OS X, it might be necessary to repeat the setup
//http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
//doRead();
//return;
}
#endif //__APPLE__
//doClose();
//setErrorStatus(true);
return;
}
std::vector<unsigned char> readData(_readDataBuffer.begin(), _readDataBuffer.begin() + bytes_transferred);
AsyncSerialEvent* evt = new AsyncSerialEvent(this->getSharedPtr(), AsyncSerialEvent::DATA_READ, readData);
//notify listeners with buffer contents
boost::shared_ptr<AsyncSerialEvent> evtPtr = boost::shared_ptr<AsyncSerialEvent>(evt);
eventSignal(evtPtr);
}
}
| 27.48855 | 155 | 0.586087 | kaliatech |
2d8eefd1422724afdc7eb2df7c0199441ad12609 | 4,815 | hpp | C++ | vts-libs/vts/atlas.hpp | melowntech/vts-libs | ffbf889b6603a8f95d3c12a2602232ff9c5d2236 | [
"BSD-2-Clause"
] | 2 | 2020-04-20T01:44:46.000Z | 2021-01-15T06:54:51.000Z | externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/atlas.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 2 | 2020-01-29T16:30:49.000Z | 2020-06-03T15:21:29.000Z | externals/browser/externals/browser/externals/vts-libs/vts-libs/vts/atlas.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 1 | 2019-09-25T05:10:07.000Z | 2019-09-25T05:10:07.000Z | /**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef vtslibs_vts_atlas_hpp
#define vtslibs_vts_atlas_hpp
#include <cstdlib>
#include <memory>
#include <istream>
#include <vector>
#include <boost/any.hpp>
#include <boost/filesystem/path.hpp>
#include "math/geometry_core.hpp"
#include "multifile.hpp"
#include "../storage/streams.hpp"
namespace vtslibs { namespace vts {
struct Mesh;
class Atlas {
public:
typedef std::shared_ptr<Atlas> pointer;
Atlas() {}
virtual ~Atlas() {}
virtual std::size_t size() const = 0;
void serialize(std::ostream &os) const;
void deserialize(std::istream &is
, const boost::filesystem::path &path = "unknown");
/** Returns area of given texture image
*/
double area(std::size_t index) const;
/** Returns dimensions of given texture image
*/
math::Size2 imageSize(std::size_t index) const;
bool valid(std::size_t index) const { return index < size(); }
bool empty() const { return !size(); }
/** Write image at given index to output stream.
*/
void write(std::ostream &os, std::size_t index) const;
/** Write image at given index to output file.
*/
void write(const boost::filesystem::path &file, std::size_t index) const;
static multifile::Table readTable(std::istream &is
, const boost::filesystem::path &path
= "unknown");
static multifile::Table readTable(const storage::IStream::pointer &is);
private:
virtual multifile::Table serialize_impl(std::ostream &os) const = 0;
virtual void deserialize_impl(std::istream &is
, const boost::filesystem::path &path
, const multifile::Table &table) = 0;
virtual math::Size2 imageSize_impl(std::size_t index) const = 0;
virtual void write_impl(std::ostream &os, std::size_t index) const = 0;
};
class RawAtlas : public Atlas {
public:
typedef std::shared_ptr<RawAtlas> pointer;
virtual std::size_t size() const { return images_.size(); }
typedef std::vector<unsigned char> Image;
typedef std::vector<Image> Images;
const Image& get(std::size_t index) const { return images_[index]; }
void add(const Image &image);
void add(const RawAtlas &other);
/** Access internal data.
*/
const Images& get() const { return images_; }
private:
virtual multifile::Table serialize_impl(std::ostream &os) const;
virtual void deserialize_impl(std::istream &is
, const boost::filesystem::path &path
, const multifile::Table &table);
virtual math::Size2 imageSize_impl(std::size_t index) const;
virtual void write_impl(std::ostream &os, std::size_t index) const;
Images images_;
};
/** Inpaint atlas.
*
* Inpaint atlas. Fails if `vts-libs` library code is not compiled in.
*/
Atlas::pointer inpaint(const Atlas &atlas, const Mesh &mesh
, int textureQuality);
inline double Atlas::area(std::size_t index) const
{
auto s(imageSize(index));
return double(s.width) * double(s.height);
}
inline void Atlas::write(std::ostream &os, std::size_t index) const
{
write_impl(os, index);
}
inline multifile::Table Atlas::readTable(const storage::IStream::pointer &is)
{
return readTable(*is, is->name());
}
} } // namespace vtslibs::vts
#endif // vtslibs_vts_atlas_hpp
| 30.283019 | 78 | 0.672274 | melowntech |
2d8ef726149ba88ee9c4c0de10c1d392a78cf441 | 15,598 | cpp | C++ | src/modules/osgAnimation/generated_code/_osgAnimation.main.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 17 | 2015-06-01T12:19:46.000Z | 2022-02-12T02:37:48.000Z | src/modules/osgAnimation/generated_code/_osgAnimation.main.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 7 | 2015-07-04T14:36:49.000Z | 2015-07-23T18:09:49.000Z | src/modules/osgAnimation/generated_code/_osgAnimation.main.cpp | JaneliaSciComp/osgpyplusplus | a5ae3f69c7e9101a32d8cc95fe680dab292f75ac | [
"BSD-3-Clause"
] | 7 | 2015-11-28T17:00:31.000Z | 2020-01-08T07:00:59.000Z | // This file has been generated by Py++.
#include "boost/python.hpp"
#include "__call_policies.pypp.hpp"
#include "__convenience.pypp.hpp"
#include "indexing_suite/value_traits.hpp"
#include "indexing_suite/container_suite.hpp"
#include "indexing_suite/vector.hpp"
#include "indexing_suite/map.hpp"
#include "wrap_osganimation.h"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/action.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/actionanimation.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/actionblendin.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/actionblendout.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/actionlayers.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/actionstripanimation.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/actionvisitor.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/animation.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/animationmanagerbase.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/animationupdatecallback_less__osg_scope_nodecallback__greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/animationupdatecallback_less__osg_scope_stateattributecallback__greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/animationupdatecallbackbase.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/basicanimationmanager.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/bone.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/bonemap.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/bonemapvisitor.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/boneweightlist.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/channel.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/clearactionvisitor.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/compositemotion.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inbackfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inbouncefunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/incircfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/incubicfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inelasticfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inexpofunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inoutbackfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inoutbouncefunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inoutcircfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inoutcubicfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inoutelasticfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inoutexpofunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inoutquadfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inoutquartfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inoutsinefunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inquadfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/inquartfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/insinefunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/keyframe.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/keyframecontainer.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/linearfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/linkvisitor.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/motion.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/outbackfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/outbouncefunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/outcircfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/outcubicfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/outelasticfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/outexpofunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/outquadfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/outquartfunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/outsinefunction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/riggeometry.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/rigtransform.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/rigtransformhardware.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/rigtransformsoftware.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/runaction.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/sampler.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/skeleton.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/stackedmatrixelement.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/stackedquaternionelement.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/stackedrotateaxiselement.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/stackedscaleelement.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/stackedtransform.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/stackedtransformelement.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/stackedtranslateelement.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/statsactionvisitor.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/statshandler.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/target.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/templatetarget_less__float__greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/templatetarget_less__osg_scope_matrixf__greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/templatetarget_less__osg_scope_quat__greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/timeline.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/timelineanimationmanager.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/uniqvertexsettobonesetlist.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/updateactionvisitor.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/updatebone.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/updatematerial.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/updatematrixtransform.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vec3arraypacked.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vec3packed.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vec3packedkeyframecontainer.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vector_less__osg_scope_ref_ptr_less_osganimation_scope_animation_greater___greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vector_less__osg_scope_ref_ptr_less_osganimation_scope_channel_greater___greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vector_less__osg_scope_ref_ptr_less_osganimation_scope_motion_greater___greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vector_less__osganimation_scope_vec3packed__greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vector_less__osganimation_scope_vertexinfluenceset_scope_boneweight__greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vector_less__std_scope_pair_less_unsigned_int_comma__osg_scope_ref_ptr_less_osganimation_scope_action_greater___greater___greater_.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vertexindextoboneweightmap.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vertexinfluence.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vertexinfluencemap.pypp.hpp"
#include "f:/users/cmbruns/git/osgpyplusplus/src/modules/osganimation/generated_code/vertexinfluenceset.pypp.hpp"
namespace bp = boost::python;
BOOST_PYTHON_MODULE(_osgAnimation){
register_vector_less__std_scope_pair_less_unsigned_int_comma__osg_scope_ref_ptr_less_osgAnimation_scope_Action_greater___greater___greater__class();
register_UniqVertexSetToBoneSetList_class();
register_vector_less__osgAnimation_scope_VertexInfluenceSet_scope_BoneWeight__greater__class();
register_vector_less__osgAnimation_scope_Vec3Packed__greater__class();
register_BoneWeightList_class();
register_vector_less__osg_scope_ref_ptr_less_osgAnimation_scope_Motion_greater___greater__class();
register_vector_less__osg_scope_ref_ptr_less_osgAnimation_scope_Channel_greater___greater__class();
register_vector_less__osg_scope_ref_ptr_less_osgAnimation_scope_Animation_greater___greater__class();
register_BoneMap_class();
register_ActionLayers_class();
register_VertexIndexToBoneWeightMap_class();
register_Action_class();
register_ActionAnimation_class();
register_ActionBlendIn_class();
register_ActionBlendOut_class();
register_ActionStripAnimation_class();
register_ActionVisitor_class();
register_Animation_class();
register_AnimationManagerBase_class();
register_AnimationUpdateCallbackBase_class();
register_AnimationUpdateCallback_less__osg_scope_NodeCallback__greater__class();
register_AnimationUpdateCallback_less__osg_scope_StateAttributeCallback__greater__class();
register_BasicAnimationManager_class();
register_Bone_class();
register_BoneMapVisitor_class();
register_Channel_class();
register_ClearActionVisitor_class();
register_Motion_class();
register_CompositeMotion_class();
register_InBackFunction_class();
register_InBounceFunction_class();
register_InCircFunction_class();
register_InCubicFunction_class();
register_InElasticFunction_class();
register_InExpoFunction_class();
register_InOutBackFunction_class();
register_InOutBounceFunction_class();
register_InOutCircFunction_class();
register_InOutCubicFunction_class();
register_InOutElasticFunction_class();
register_InOutExpoFunction_class();
register_InOutQuadFunction_class();
register_InOutQuartFunction_class();
register_InOutSineFunction_class();
register_InQuadFunction_class();
register_InQuartFunction_class();
register_InSineFunction_class();
register_Keyframe_class();
register_KeyframeContainer_class();
register_LinearFunction_class();
register_LinkVisitor_class();
register_OutBackFunction_class();
register_OutBounceFunction_class();
register_OutCircFunction_class();
register_OutCubicFunction_class();
register_OutElasticFunction_class();
register_OutExpoFunction_class();
register_OutQuadFunction_class();
register_OutQuartFunction_class();
register_OutSineFunction_class();
register_RigGeometry_class();
register_RigTransform_class();
register_RigTransformHardware_class();
register_RigTransformSoftware_class();
register_RunAction_class();
register_Sampler_class();
register_Skeleton_class();
register_StackedTransformElement_class();
register_StackedMatrixElement_class();
register_StackedQuaternionElement_class();
register_StackedRotateAxisElement_class();
register_StackedScaleElement_class();
register_StackedTransform_class();
register_StackedTranslateElement_class();
register_UpdateActionVisitor_class();
register_StatsActionVisitor_class();
register_StatsHandler_class();
register_Target_class();
register_Vec3PackedKeyframeContainer_class();
register_TemplateTarget_less__float__greater__class();
register_TemplateTarget_less__osg_scope_Matrixf__greater__class();
register_TemplateTarget_less__osg_scope_Quat__greater__class();
register_Timeline_class();
register_TimelineAnimationManager_class();
register_UpdateMatrixTransform_class();
register_UpdateBone_class();
register_UpdateMaterial_class();
register_Vec3ArrayPacked_class();
register_Vec3Packed_class();
register_VertexInfluence_class();
register_VertexInfluenceMap_class();
register_VertexInfluenceSet_class();
}
| 39.892583 | 225 | 0.834851 | JaneliaSciComp |
2d8f870e71e06486d71d9480bb7ebf2970924670 | 1,137 | cc | C++ | RecoVertex/GhostTrackFitter/src/AnnealingGhostTrackFitter.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoVertex/GhostTrackFitter/src/AnnealingGhostTrackFitter.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoVertex/GhostTrackFitter/src/AnnealingGhostTrackFitter.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include <memory>
#include <vector>
#include "RecoVertex/VertexTools/interface/GeometricAnnealing.h"
#include "RecoVertex/GhostTrackFitter/interface/GhostTrackState.h"
#include "RecoVertex/GhostTrackFitter/interface/GhostTrackPrediction.h"
#include "RecoVertex/GhostTrackFitter/interface/AnnealingGhostTrackFitter.h"
using namespace reco;
AnnealingGhostTrackFitter::AnnealingGhostTrackFitter() : firstStep(true) {
annealing = std::make_unique<GeometricAnnealing>(3.0, 64.0, 0.25);
}
void AnnealingGhostTrackFitter::postFit(const GhostTrackFitter::PredictionUpdater &updater,
const GhostTrackPrediction &pred,
std::vector<GhostTrackState> &states) {
for (std::vector<GhostTrackState>::iterator state = states.begin(); state != states.end(); ++state) {
if (!state->isValid())
continue;
double ndof, chi2;
updater.contribution(pred, *state, ndof, chi2);
if (ndof == 0. || firstStep)
continue;
state->setWeight(annealing->weight(chi2));
}
if (firstStep)
firstStep = false;
else
annealing->anneal();
}
| 29.921053 | 103 | 0.689534 | ckamtsikis |
2d8f94a85b21096904d03f0e92bbd28b27a3fd91 | 2,576 | cc | C++ | compiler/optimizing/instruction_simplifier_x86.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | 20 | 2021-06-24T16:38:42.000Z | 2022-01-20T16:15:57.000Z | compiler/optimizing/instruction_simplifier_x86.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | null | null | null | compiler/optimizing/instruction_simplifier_x86.cc | Paschalis/android-llvm | 317f7fd4b736a0511a2273a2487915c34cf8933e | [
"Apache-2.0"
] | 4 | 2021-11-03T06:01:12.000Z | 2022-02-24T02:57:31.000Z | /* Copyright (C) 2018 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 "instruction_simplifier_x86.h"
#include "instruction_simplifier_x86_shared.h"
#include "code_generator_x86.h"
namespace art {
namespace x86 {
class InstructionSimplifierX86Visitor : public HGraphVisitor {
public:
InstructionSimplifierX86Visitor(HGraph* graph,
CodeGenerator* codegen,
OptimizingCompilerStats* stats)
: HGraphVisitor(graph),
codegen_(down_cast<CodeGeneratorX86*>(codegen)),
stats_(stats) {}
void RecordSimplification() {
MaybeRecordStat(stats_, MethodCompilationStat::kInstructionSimplificationsArch);
}
bool HasAVX2() {
return (codegen_->GetInstructionSetFeatures().HasAVX2());
}
void VisitBasicBlock(HBasicBlock* block) override {
for (HInstructionIterator it(block->GetInstructions()); !it.Done(); it.Advance()) {
HInstruction* instruction = it.Current();
if (instruction->IsInBlock()) {
instruction->Accept(this);
}
}
}
void VisitAnd(HAnd * instruction) override;
void VisitXor(HXor* instruction) override;
private:
CodeGeneratorX86* codegen_;
OptimizingCompilerStats* stats_;
};
void InstructionSimplifierX86Visitor::VisitAnd(HAnd* instruction) {
if (TryCombineAndNot(instruction)) {
RecordSimplification();
} else if (instruction->GetResultType() == DataType::Type::kInt32) {
if (TryGenerateResetLeastSetBit(instruction)) {
RecordSimplification();
}
}
}
void InstructionSimplifierX86Visitor::VisitXor(HXor* instruction) {
if (instruction->GetResultType() == DataType::Type::kInt32) {
if (TryGenerateMaskUptoLeastSetBit(instruction)) {
RecordSimplification();
}
}
}
bool InstructionSimplifierX86::Run() {
InstructionSimplifierX86Visitor visitor(graph_, codegen_, stats_);
if (visitor.HasAVX2()) {
visitor.VisitReversePostOrder();
return true;
}
return false;
}
} // namespace x86
} // namespace art
| 28.94382 | 87 | 0.707298 | Paschalis |
2d903b15ad97b66cf94f5eb39eaa7f7c2c19c569 | 1,617 | cpp | C++ | emulator/src/mame/video/pass.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/mame/video/pass.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/mame/video/pass.cpp | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:David Haywood
/* video/pass.c - see drivers/pass.c for more info */
#include "emu.h"
#include "includes/pass.h"
/* background tilemap stuff */
TILE_GET_INFO_MEMBER(pass_state::get_pass_bg_tile_info)
{
int tileno, fx;
tileno = m_bg_videoram[tile_index] & 0x1fff;
fx = (m_bg_videoram[tile_index] & 0xc000) >> 14;
SET_TILE_INFO_MEMBER(1, tileno, 0, TILE_FLIPYX(fx));
}
WRITE16_MEMBER(pass_state::pass_bg_videoram_w)
{
m_bg_videoram[offset] = data;
m_bg_tilemap->mark_tile_dirty(offset);
}
/* foreground 'sprites' tilemap stuff */
TILE_GET_INFO_MEMBER(pass_state::get_pass_fg_tile_info)
{
int tileno, flip;
tileno = m_fg_videoram[tile_index] & 0x3fff;
flip = (m_fg_videoram[tile_index] & 0xc000) >>14;
SET_TILE_INFO_MEMBER(0, tileno, 0, TILE_FLIPYX(flip));
}
WRITE16_MEMBER(pass_state::pass_fg_videoram_w)
{
m_fg_videoram[offset] = data;
m_fg_tilemap->mark_tile_dirty(offset);
}
/* video update / start */
void pass_state::video_start()
{
m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(pass_state::get_pass_bg_tile_info),this), TILEMAP_SCAN_ROWS, 8, 8, 64, 32);
m_fg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(FUNC(pass_state::get_pass_fg_tile_info),this), TILEMAP_SCAN_ROWS, 4, 4, 128, 64);
m_fg_tilemap->set_transparent_pen(255);
}
uint32_t pass_state::screen_update_pass(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0);
m_fg_tilemap->draw(screen, bitmap, cliprect, 0, 0);
return 0;
}
| 26.080645 | 165 | 0.755102 | rjw57 |
2d92753c43bc99f68c811906ea302bcf19d43cb6 | 3,631 | cpp | C++ | src/chrono_synchrono/communication/dds/SynDDSListener.cpp | lucasw/chrono | e79d8c761c718ecb4c796725cff37026f357da8c | [
"BSD-3-Clause"
] | 1,383 | 2015-02-04T14:17:40.000Z | 2022-03-30T04:58:16.000Z | src/chrono_synchrono/communication/dds/SynDDSListener.cpp | pchaoWT/chrono | fd68d37d1d4ee75230dc1eea78ceff91cca7ac32 | [
"BSD-3-Clause"
] | 245 | 2015-01-11T15:30:51.000Z | 2022-03-30T21:28:54.000Z | src/chrono_synchrono/communication/dds/SynDDSListener.cpp | pchaoWT/chrono | fd68d37d1d4ee75230dc1eea78ceff91cca7ac32 | [
"BSD-3-Clause"
] | 351 | 2015-02-04T14:17:47.000Z | 2022-03-30T04:42:52.000Z | #include "chrono_synchrono/communication/dds/SynDDSListener.h"
#include <fastdds/dds/subscriber/DataReader.hpp>
#include <fastdds/dds/subscriber/SampleInfo.hpp>
using namespace eprosima::fastdds::dds;
using namespace eprosima::fastrtps::rtps;
namespace chrono {
namespace synchrono {
void SynDDSThreadSafeCounter::BlockUntil(int iters) {
std::unique_lock<std::mutex> lock(m_mutex);
while (iters > m_iters)
m_condition_variable.wait(lock);
}
void SynDDSThreadSafeCounter::Increment() {
std::unique_lock<std::mutex> lock(m_mutex);
m_iters++;
m_condition_variable.notify_all();
}
void SynDDSThreadSafeCounter::SetSafe(int iters) {
std::unique_lock<std::mutex> lock(m_mutex);
m_iters = iters;
m_condition_variable.notify_all();
}
int SynDDSThreadSafeCounter::GetSafe() {
std::unique_lock<std::mutex> lock(m_mutex);
int ret_iters = m_iters;
return ret_iters;
}
// -----------------------------------------------------------------------------------
void SynDDSParticipantListener::on_participant_discovery(DomainParticipant* participant,
ParticipantDiscoveryInfo&& info) {
if (info.status == ParticipantDiscoveryInfo::DISCOVERED_PARTICIPANT &&
CheckParticipantName(std::string(info.info.m_participantName))) {
m_participant_names.push_back(std::string(info.info.m_participantName));
m_counter.Increment();
} else if (info.status == ParticipantDiscoveryInfo::REMOVED_PARTICIPANT ||
info.status == ParticipantDiscoveryInfo::DROPPED_PARTICIPANT) {
}
}
bool SynDDSParticipantListener::CheckParticipantName(const std::string& name) {
return name.find(this->comm_prefix) != std::string::npos;
}
// -----------------------------------------------------------------------------------
void SynDDSDataWriterListener::on_publication_matched(DataWriter* writer, const PublicationMatchedStatus& info) {
if (info.current_count_change == 1 || info.current_count_change == -1) {
m_counter.SetSafe(info.total_count);
} else {
std::cout << info.current_count_change
<< " is not a valid value for PublicationMatchedStatus "
"current count change."
<< std::endl;
}
}
// -----------------------------------------------------------------------------------
SynDDSDataReaderListener::SynDDSDataReaderListener(std::function<void(void*)> callback, void* message)
: m_message(message) , m_on_data_available_callback(callback) {}
void SynDDSDataReaderListener::on_data_available(DataReader* reader) {
// std::cout << "Data Available" << std::endl;
SampleInfo info;
if (reader->take_next_sample(m_message, &info) != ReturnCode_t::RETCODE_OK) {
std::cout << "SynDDSDataReaderListener::on_data_available: DataReader failed to read message." << std::endl;
exit(-1);
}
m_on_data_available_callback(m_message);
}
void SynDDSDataReaderListener::on_subscription_matched(DataReader* reader, const SubscriptionMatchedStatus& info) {
if (info.current_count_change == 1 || info.current_count_change == -1) {
m_counter.SetSafe(info.total_count);
} else {
std::cout << info.current_count_change
<< " is not a valid value for SubscriptionMatchedStatus "
"current count change"
<< std::endl;
}
}
void SynDDSDataReaderListener::SetOnDataAvailableCallback(std::function<void(void*)> callback) {
m_on_data_available_callback = callback;
}
} // namespace synchrono
} // namespace chrono | 35.598039 | 116 | 0.646929 | lucasw |
2d969bc84fc0c320b322039f232200d834728a3c | 25,479 | cpp | C++ | src/otbullet/wrapper.cpp | cameni/bullet3 | 2a05f2d3e56589dafb6849655d30f07e62689573 | [
"Zlib"
] | null | null | null | src/otbullet/wrapper.cpp | cameni/bullet3 | 2a05f2d3e56589dafb6849655d30f07e62689573 | [
"Zlib"
] | null | null | null | src/otbullet/wrapper.cpp | cameni/bullet3 | 2a05f2d3e56589dafb6849655d30f07e62689573 | [
"Zlib"
] | 1 | 2020-09-09T08:53:48.000Z | 2020-09-09T08:53:48.000Z | #include "discrete_dynamics_world.h"
#include "multithread_default_collision_configuration.h"
#include <BulletCollision/CollisionShapes/btCompoundShape.h>
#include <BulletCollision/CollisionShapes/btCollisionShape.h>
#include <BulletCollision/CollisionShapes/btConvexHullShape.h>
#include <BulletCollision/CollisionShapes/btSphereShape.h>
#include <BulletCollision/CollisionShapes/btCylinderShape.h>
#include <BulletCollision/CollisionShapes/btCapsuleShape.h>
#include <BulletCollision/CollisionShapes/btConeShape.h>
#include <BulletCollision/CollisionShapes/btBvhTriangleMeshShape.h>
#include <BulletCollision/CollisionShapes/btTriangleMesh.h>
#include <BulletCollision/CollisionDispatch/btGhostObject.h>
#include <BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h>
#include <BulletCollision/BroadphaseCollision/btAxisSweep3.h>
#include <BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolver.h>
#include <BulletDynamics/ConstraintSolver/btPoint2PointConstraint.h>
#include <LinearMath/btIDebugDraw.h>
#include "otbullet.hpp"
#include "physics_cfg.h"
#include <comm/ref_i.h>
#include <comm/commexception.h>
#include <comm/taskmaster.h>
static btBroadphaseInterface* _overlappingPairCache = 0;
static btCollisionDispatcher* _dispatcher = 0;
static btConstraintSolver* _constraintSolver = 0;
static btDefaultCollisionConfiguration* _collisionConfiguration = 0;
static physics * _physics = nullptr;
extern uint gOuterraSimulationFrame;
////////////////////////////////////////////////////////////////////////////////
#ifdef _LIB
extern bool _ext_collider(const void* context,
const double3& center,
float radius,
float lod_dimension,
coid::dynarray<bt::triangle>& data,
coid::dynarray<uint>& trees,
coid::slotalloc<bt::tree_batch>& tree_batches,
uint frame );
extern int _ext_collider_obb(
const void * context,
const double3& center,
const float3x3& basis,
float lod_dimension,
coid::dynarray<bt::triangle>& data,
coid::dynarray<uint>& trees,
coid::slotalloc<bt::tree_batch>& tree_batches,
uint frame,
bool& is_above_tm,
double3& under_contact,
float3& under_normal);
extern float _ext_terrain_ray_intersect(
const void* planet,
const double3& from,
const float3& dir,
const float2& minmaxlen,
float3* norm,
double3* pos);
extern static float _ext_elevation_above_terrain(
const double3& pos,
float maxlen,
float3* norm,
double3* hitpoint);
extern float3 _ext_tree_col(btRigidBody * obj,
bt::tree_collision_contex & ctx,
float time_step,
coid::slotalloc<bt::tree_batch>& tree_baFBtches);
#else
static bool _ext_collider(
const void* planet,
const double3& center,
float radius,
float lod_dimension,
coid::dynarray<bt::triangle>& data,
coid::dynarray<uint>& trees,
coid::slotalloc<bt::tree_batch>& tree_batches,
uint frame )
{
return _physics->terrain_collisions(planet, center, radius, lod_dimension, data, trees, tree_batches, frame);
}
static int _ext_collider_obb(
const void * planet,
const double3& center,
const float3x3& basis,
float lod_dimension,
coid::dynarray<bt::triangle>& data,
coid::dynarray<uint>& trees,
coid::slotalloc<bt::tree_batch>& tree_batches,
uint frame,
bool& is_above_tm,
double3& under_contact,
float3& under_normal,
coid::dynarray<bt::external_broadphase*>& broadphases)
{
return _physics->terrain_collisions_aabb(planet, center, basis, lod_dimension, data, trees,
tree_batches, frame, is_above_tm, under_contact, under_normal, broadphases);
}
static float _ext_terrain_ray_intersect(
const void* planet,
const double3& from,
const float3& dir,
const float2& minmaxlen,
float3* norm,
double3* pos) {
return _physics->terrain_ray_intersect(
planet,
from,
dir,
minmaxlen,
norm,
pos);
}
static void _ext_terrain_ray_intersect_broadphase(
const void* planet,
const double3& from,
const float3& dir,
const float2& minmaxlen,
coid::dynarray32<bt::external_broadphase*>& bps) {
_physics->terrain_ray_intersect_broadphase(
planet,
from,
dir,
minmaxlen,
bps);
}
static float _ext_elevation_above_terrain(
const double3& pos,
float maxlen,
float3* norm,
double3* hitpoint)
{
return _physics->elevation_above_terrain(
pos,
maxlen,
norm,
hitpoint);
}
static float3 _ext_tree_col(btRigidBody * obj,
bt::tree_collision_contex & ctx,
float time_step,
coid::slotalloc<bt::tree_batch>& tree_batches) {
return _physics->tree_collisions(obj, ctx, time_step,tree_batches);
}
static void _ext_add_static_collider(const void * context,btCollisionObject * obj, const double3& cen, const float3x3& basis) {
_physics->add_static_collider(context,obj,cen,basis);
}
#endif
void debug_draw_world() {
if (_physics) {
_physics->debug_draw_world();
}
}
void set_debug_drawer_enabled(btIDebugDraw * debug_draw) {
if (_physics) {
_physics->set_debug_draw_enabled(debug_draw);
}
}
////////////////////////////////////////////////////////////////////////////////
iref<physics> physics::create(double r, void* context, coid::taskmaster* tm)
{
_physics = new physics;
btDefaultCollisionConstructionInfo dccinfo;
dccinfo.m_owns_simplex_and_pd_solver = false;
_collisionConfiguration = new multithread_default_collision_configuration(dccinfo);
_dispatcher = new btCollisionDispatcher(_collisionConfiguration);
btVector3 worldMin(-r,-r,-r);
btVector3 worldMax(r,r,r);
_overlappingPairCache = new bt32BitAxisSweep3(worldMin, worldMax,10000);
_overlappingPairCache->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
_constraintSolver = new btSequentialImpulseConstraintSolver();
ot::discrete_dynamics_world * wrld = new ot::discrete_dynamics_world(
_dispatcher,
_overlappingPairCache,
_constraintSolver,
_collisionConfiguration,
&_ext_collider,
&_ext_tree_col,
&_ext_terrain_ray_intersect,
&_ext_elevation_above_terrain,
context,
tm);
wrld->setGravity(btVector3(0, 0, 0));
wrld->_aabb_intersect = &_ext_collider_obb;
wrld->_terrain_ray_intersect_broadphase = &_ext_terrain_ray_intersect_broadphase;
_physics->_world = wrld;
_physics->_world->setForceUpdateAllAabbs(false);
_physics->_dbg_drawer = nullptr;
// default mode
_physics->_dbg_draw_mode = btIDebugDraw::DBG_DrawContactPoints | btIDebugDraw::DBG_DrawWireframe | btIDebugDraw::DBG_DrawConstraints | btIDebugDraw::DBG_DrawConstraintLimits;
return _physics;
}
iref<physics> physics::get()
{
if (!_physics) {
throw coid::exception("Bullet not initialized yet!");
}
return _physics;
}
////////////////////////////////////////////////////////////////////////////////
void physics::set_simulation_frame(uint frame)
{
gOuterraSimulationFrame = frame;
}
////////////////////////////////////////////////////////////////////////////////
void physics::debug_draw_world() {
if (_dbg_drawer) {
_world->debugDrawWorld();
}
}
////////////////////////////////////////////////////////////////////////////////
void physics::get_broadphase_handles_aabbs(const bt::external_broadphase* broadphase, coid::dynarray<double3>& minmaxes)
{
bt32BitAxisSweep3* bp = nullptr;
uint revision = 0xffffffff;
if (broadphase)
{
bp = broadphase->_broadphase;
revision = broadphase->_revision;
}
else
{
bp = static_cast<bt32BitAxisSweep3*>(_world->getBroadphase());
}
_world->for_each_object_in_broadphase(bp, revision, [&minmaxes](btCollisionObject* co) {
btBroadphaseProxy* bp = co->getBroadphaseHandle();
if (bp && (co->getCollisionFlags() & btCollisionObject::CollisionFlags::CF_DISABLE_VISUALIZE_OBJECT) == 0)
{
minmaxes.push(double3(bp->m_aabbMin[0], bp->m_aabbMin[1], bp->m_aabbMin[2]));
minmaxes.push(double3(bp->m_aabbMax[0], bp->m_aabbMax[1], bp->m_aabbMax[2]));
}
});
}
////////////////////////////////////////////////////////////////////////////////
bt::external_broadphase* physics::create_external_broadphase(const double3& min, const double3& max)
{
return _world->create_external_broadphase(min,max);
}
////////////////////////////////////////////////////////////////////////////////
void physics::delete_external_broadphase(bt::external_broadphase * bp)
{
return _world->delete_external_broadphase(bp);
}
////////////////////////////////////////////////////////////////////////////////
void physics::update_external_broadphase(bt::external_broadphase * bp)
{
return _world->update_terrain_mesh_broadphase(bp);
}
////////////////////////////////////////////////////////////////////////////////
bool physics::add_collision_object_to_external_broadphase(bt::external_broadphase * bp, btCollisionObject * co, unsigned int group, unsigned int mask)
{
if (bp->_broadphase->is_full()) {
return false;
}
btTransform trans = co->getWorldTransform();
btVector3 minAabb;
btVector3 maxAabb;
co->getCollisionShape()->getAabb(trans, minAabb, maxAabb);
int type = co->getCollisionShape()->getShapeType();
co->setBroadphaseHandle(bp->_broadphase->createProxy(
minAabb,
maxAabb,
type,
co,
group,
mask,
0, 0
));
//bp->_colliders.push(sc);
return true;
}
/*
////////////////////////////////////////////////////////////////////////////////
void physics::remove_collision_object_from_external_broadphase(bt::external_broadphase * bp, simple_collider * sc, btCollisionObject * co)
{
for (uints i = 0; i < bp->_colliders.size(); i++) {
if (bp->_colliders[i] == sc) {
bp->_colliders.del(i);
break;
}
}
bp->_broadphase.destroyProxy(co->getBroadphaseHandle(),nullptr);
}*/
////////////////////////////////////////////////////////////////////////////////
void physics::query_volume_sphere(const double3 & pos, float rad, coid::dynarray<btCollisionObject*>& result)
{
#ifdef _DEBUG
bt32BitAxisSweep3 * broad = dynamic_cast<bt32BitAxisSweep3 *>(_world->getBroadphase());
DASSERT(broad != nullptr);
#else
bt32BitAxisSweep3 * broad = static_cast<bt32BitAxisSweep3 *>(_world->getBroadphase());
#endif
_world->query_volume_sphere(broad, pos, rad, [&](btCollisionObject* obj) {
if (obj->getUserPointer())
result.push(obj);
});
coid::dynarray <bt::external_broadphase*> ebps;
_physics->external_broadphases_in_radius(_world->getContext(), pos, rad, gCurrentFrame, ebps);
ebps.for_each([&](bt::external_broadphase* ebp) {
/*if (ebp->_dirty) {
_world->update_terrain_mesh_broadphase(ebp);
}*/
DASSERT(!ebp->_dirty);
_world->query_volume_sphere(ebp->_broadphase, pos, rad, [&](btCollisionObject* obj) {
if (obj->getUserPointer())
result.push(obj);
});
});
}
////////////////////////////////////////////////////////////////////////////////
void physics::query_volume_frustum(const double3 & pos,const float4 * f_planes_norms, uint8 nplanes, bool include_partial, coid::dynarray<btCollisionObject*>& result)
{
#ifdef _DEBUG
bt32BitAxisSweep3* broad = dynamic_cast<bt32BitAxisSweep3*>(_world->getBroadphase());
DASSERT(broad != nullptr);
#else
bt32BitAxisSweep3* broad = static_cast<bt32BitAxisSweep3*>(_world->getBroadphase());
#endif
_world->query_volume_frustum(broad, pos, f_planes_norms, nplanes, include_partial, [&](btCollisionObject* obj) {
result.push(obj);
});
coid::dynarray <bt::external_broadphase*> ebps;
_physics->external_broadphases_in_frustum(_world->getContext(), pos, f_planes_norms, nplanes, gCurrentFrame, ebps);
ebps.for_each([&](bt::external_broadphase* ebp) {
/*if (ebp->_dirty) {
_world->update_terrain_mesh_broadphase(ebp);
}*/
DASSERT(!ebp->_dirty);
_world->query_volume_frustum(ebp->_broadphase, pos, f_planes_norms, nplanes, include_partial, [&](btCollisionObject* obj) {
if (obj->getUserPointer())
result.push(obj);
});
});
}
////////////////////////////////////////////////////////////////////////////////
void physics::wake_up_objects_in_radius(const double3 & pos, float rad) {
#ifdef _DEBUG
bt32BitAxisSweep3 * broad = dynamic_cast<bt32BitAxisSweep3 *>(_world->getBroadphase());
DASSERT(broad != nullptr);
#else
bt32BitAxisSweep3 * broad = static_cast<bt32BitAxisSweep3 *>(_world->getBroadphase());
#endif
_world->query_volume_sphere(broad,pos, rad, [&](btCollisionObject* obj) {
obj->setActivationState(ACTIVE_TAG);
obj->setDeactivationTime(0);
});
}
////////////////////////////////////////////////////////////////////////////////
void physics::wake_up_object(btCollisionObject* obj) {
obj->setActivationState(ACTIVE_TAG);
obj->setDeactivationTime(0);
}
////////////////////////////////////////////////////////////////////////////////
bool physics::is_point_inside_terrain_ocluder(const double3 & pt)
{
return _world->is_point_inside_terrain_occluder(btVector3(pt.x,pt.y,pt.z));
}
void physics::pause_simulation(bool pause)
{
_world->pause_simulation(pause);
}
////////////////////////////////////////////////////////////////////////////////
btTriangleMesh* physics::create_triangle_mesh()
{
btTriangleMesh* result = new btTriangleMesh();
return result;
}
////////////////////////////////////////////////////////////////////////////////
void physics::destroy_triangle_mesh(btTriangleMesh* triangle_mesh)
{
DASSERT(triangle_mesh);
delete triangle_mesh;
}
////////////////////////////////////////////////////////////////////////////////
void physics::add_triangle(btTriangleMesh* mesh, const float v0[3], const float v1[3], const float v2[3])
{
btVector3 btv0(static_cast<double>(v0[0]), static_cast<double>(v0[1]), static_cast<double>(v0[2]));
btVector3 btv1(static_cast<double>(v1[0]), static_cast<double>(v1[1]), static_cast<double>(v1[2]));
btVector3 btv2(static_cast<double>(v2[0]), static_cast<double>(v2[1]), static_cast<double>(v2[2]));
mesh->addTriangle(btv0, btv1, btv2);
}
////////////////////////////////////////////////////////////////////////////////
btCollisionShape* physics::create_shape( bt::EShape sh, const float hvec[3], void* data)
{
switch(sh) {
case bt::SHAPE_CONVEX: return new btConvexHullShape();
case bt::SHAPE_MESH_STATIC: return new btBvhTriangleMeshShape(reinterpret_cast<btTriangleMesh*>(data),false);
case bt::SHAPE_SPHERE: return new btSphereShape(hvec[0]);
case bt::SHAPE_BOX: return new btBoxShape(btVector3(hvec[0], hvec[1], hvec[2]));
case bt::SHAPE_CYLINDER: return new btCylinderShapeZ(btVector3(hvec[0], hvec[1], hvec[2]));
case bt::SHAPE_CAPSULE: {
if (glm::abs(hvec[1] - hvec[2]) < 0.000001f) {
//btCapsuleX
return new btCapsuleShapeX(hvec[1], 2.f*(hvec[0] - hvec[1]));
}
else if(glm::abs(hvec[0] - hvec[2]) < 0.000001f){
//btCapsuleY
return new btCapsuleShape(hvec[0], 2.f*(hvec[1] - hvec[0]));
}
else{
//btCapsuleZ
return new btCapsuleShapeZ(hvec[1], 2.f*(hvec[2] - hvec[1]));
}
}
case bt::SHAPE_CONE: return new btConeShapeZ(hvec[0], hvec[2]);
}
return 0;
}
////////////////////////////////////////////////////////////////////////////////
ifc_fn btCollisionShape * physics::clone_shape(const btCollisionShape * shape)
{
return shape->getClone();
}
////////////////////////////////////////////////////////////////////////////////
void physics::destroy_shape( btCollisionShape*& shape )
{
delete shape;
shape = 0;
}
////////////////////////////////////////////////////////////////////////////////
void physics::add_convex_point( btCollisionShape* shape, const float pt[3] )
{
static_cast<btConvexHullShape*>(shape)->addPoint(btVector3(pt[0], pt[1], pt[2]), false);
}
////////////////////////////////////////////////////////////////////////////////
void physics::close_convex_shape( btCollisionShape* shape )
{
shape->setMargin(0.005);
static_cast<btConvexHullShape*>(shape)->recalcLocalAabb();
}
////////////////////////////////////////////////////////////////////////////////
void physics::set_collision_shape_local_scaling(btCollisionShape * shape, const float3 & scale)
{
shape->setLocalScaling(btVector3(scale[0], scale[1], scale[2]));
}
////////////////////////////////////////////////////////////////////////////////
btCompoundShape* physics::create_compound_shape()
{
btCompoundShape * res = new btCompoundShape();
return res;
}
////////////////////////////////////////////////////////////////////////////////
void physics::add_child_shape( btCompoundShape* group, btCollisionShape* child, const btTransform& tr )
{
group->addChildShape(tr, child);
}
////////////////////////////////////////////////////////////////////////////////
void physics::remove_child_shape(btCompoundShape* group, btCollisionShape* child)
{
group->removeChildShape(child);
}
////////////////////////////////////////////////////////////////////////////////
void physics::update_child( btCompoundShape* group, btCollisionShape * child, const btTransform& tr )
{
int index = -1;
const int num_children = group->getNumChildShapes();
for (int i = 0; i < num_children; i++) {
if (group->getChildShape(i) == child) {
index = i;
break;
}
}
group->updateChildTransform(index, tr, false);
}
////////////////////////////////////////////////////////////////////////////////
void physics::get_child_transform(btCompoundShape * group, btCollisionShape * child, btTransform& tr)
{
int index = -1;
const int num_children = group->getNumChildShapes();
for (int i = 0; i < num_children; i++) {
if (group->getChildShape(i) == child) {
index = i;
break;
}
}
tr = group->getChildTransform(index);
}
////////////////////////////////////////////////////////////////////////////////
void physics::recalc_compound_shape( btCompoundShape* shape )
{
shape->recalculateLocalAabb();
}
////////////////////////////////////////////////////////////////////////////////
void physics::destroy_compound_shape( btCompoundShape*& shape )
{
delete shape;
shape = 0;
}
////////////////////////////////////////////////////////////////////////////////
btCollisionObject* physics::create_collision_object( btCollisionShape* shape, void* usr1, void* usr2 )
{
btCollisionObject* obj = new btCollisionObject;
obj->setCollisionShape(shape);
obj->setUserPointer(usr1);
obj->m_userDataExt = usr2;
return obj;
}
////////////////////////////////////////////////////////////////////////////////
btGhostObject* physics::create_ghost_object(btCollisionShape* shape, void* usr1, void* usr2)
{
btGhostObject* obj = new btGhostObject;
obj->setCollisionShape(shape);
obj->setUserPointer(usr1);
obj->m_userDataExt = usr2;
return obj;
}
////////////////////////////////////////////////////////////////////////////////
void physics::set_collision_info(btCollisionObject* obj, unsigned int group, unsigned int mask)
{
btBroadphaseProxy* bp = obj->getBroadphaseHandle();
if (bp) {
bp->m_collisionFilterGroup = group;
bp->m_collisionFilterMask = mask;
}
}
////////////////////////////////////////////////////////////////////////////////
void physics::destroy_collision_object( btCollisionObject*& obj )
{
if(obj) delete obj;
obj = 0;
}
////////////////////////////////////////////////////////////////////////////////
void physics::destroy_ghost_object(btGhostObject*& obj)
{
if (obj) delete obj;
obj = 0;
}
////////////////////////////////////////////////////////////////////////////////
bool physics::add_collision_object( btCollisionObject* obj, unsigned int group, unsigned int mask, bool inactive )
{
if(inactive)
obj->setActivationState(DISABLE_SIMULATION);
/* if (obj->isStaticObject()) {
float3x3 basis;
double3 cen;
_world->get_obb(obj->getCollisionShape(),obj->getWorldTransform(),cen,basis);
add_static_collider(_world->get_context(),obj,cen,basis);
}
else {
_world->addCollisionObject(obj, group, mask);
}*/
if (!_world->addCollisionObject(obj, group, mask)) {
return false;
}
btGhostObject* ghost = btGhostObject::upcast(obj);
if (ghost) {
obj->setCollisionFlags(obj->getCollisionFlags() | btCollisionObject::CollisionFlags::CF_NO_CONTACT_RESPONSE | btCollisionObject::CollisionFlags::CF_DISABLE_VISUALIZE_OBJECT);
_world->add_terrain_occluder(ghost);
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
void physics::remove_collision_object( btCollisionObject* obj )
{
_world->removeCollisionObject(obj);
btGhostObject* ghost = btGhostObject::upcast(obj);
if (ghost) {
_world->remove_terrain_occluder(ghost);
}
}
////////////////////////////////////////////////////////////////////////////////
void physics::remove_collision_object_external(btCollisionObject* obj)
{
_world->removeCollisionObject_external(obj);
btGhostObject* ghost = btGhostObject::upcast(obj);
if (ghost) {
_world->remove_terrain_occluder(ghost);
}
}
////////////////////////////////////////////////////////////////////////////////
int physics::get_collision_flags(const btCollisionObject * co)
{
return co->getCollisionFlags();
}
////////////////////////////////////////////////////////////////////////////////
void physics::set_collision_flags(btCollisionObject * co, int flags)
{
return co->setCollisionFlags(flags);
}
////////////////////////////////////////////////////////////////////////////////
void physics::force_update_aabbs()
{
_world->updateAabbs();
}
////////////////////////////////////////////////////////////////////////////////
void physics::update_collision_object( btCollisionObject* obj, const btTransform& tr, bool update_aabb )
{
obj->setWorldTransform(tr);
if (update_aabb || obj->getBroadphaseHandle()) {
//_world->updateSingleAabb(obj);
obj->m_otFlags |= bt::OTF_TRANSFORMATION_CHANGED;
}
}
////////////////////////////////////////////////////////////////////////////////
void physics::step_simulation(double step, bt::bullet_stats * stats)
{
_world->set_ot_stats(stats);
_world->stepSimulation(step, 0, step);
}
////////////////////////////////////////////////////////////////////////////////
void physics::ray_test( const double from[3], const double to[3], void* cb, bt::external_broadphase* bp)
{
btVector3 afrom = btVector3(from[0], from[1], from[2]);
btVector3 ato = btVector3(to[0], to[1], to[2]);
if (bp && bp->_dirty) {
DASSERT(0 && "should be already updated");
//_world->update_terrain_mesh_broadphase(bp);
}
_world->rayTest(afrom, ato, *(btCollisionWorld::RayResultCallback*)cb, bp);
}
void physics::set_current_frame(uint frame)
{
gCurrentFrame = frame;
}
////////////////////////////////////////////////////////////////////////////////
bt::ot_world_physics_stats physics::get_stats() {
return ((ot::discrete_dynamics_world*)(_world))->get_stats();
}
////////////////////////////////////////////////////////////////////////////////
bt::ot_world_physics_stats* physics::get_stats_ptr() {
return const_cast<bt::ot_world_physics_stats*>(&((ot::discrete_dynamics_world*)(_world))->get_stats());
}
////////////////////////////////////////////////////////////////////////////////
void physics::set_debug_draw_enabled(btIDebugDraw * debug_drawer) {
_dbg_drawer = debug_drawer;
((ot::discrete_dynamics_world*)_world)->setDebugDrawer(debug_drawer);
if (debug_drawer) {
debug_drawer->setDebugMode(_dbg_draw_mode);
}
}
////////////////////////////////////////////////////////////////////////////////
void physics::set_debug_drawer_mode(int debug_mode) {
_dbg_draw_mode = debug_mode;
if (_dbg_drawer) {
_dbg_drawer->setDebugMode(debug_mode);
}
}
////////////////////////////////////////////////////////////////////////////////
btTypedConstraint* physics::add_constraint_ball_socket(btDynamicsWorld * world, btRigidBody* rb_a, const btVector3& pivot_a, btRigidBody* rb_b, const btVector3& pivot_b, bool disable_collision) {
btPoint2PointConstraint * p2p = new btPoint2PointConstraint(*rb_a,*rb_b,pivot_a,pivot_b);
_physics->_world->addConstraint(p2p,disable_collision);
return p2p;
}
////////////////////////////////////////////////////////////////////////////////
void physics::remove_constraint(btDynamicsWorld * world, btTypedConstraint * constraint) {
_physics->_world->removeConstraint(constraint);
}
| 32.211125 | 195 | 0.580792 | cameni |
2d98d34487dcafe8664fe5d56569c858343bcd9a | 1,282 | cpp | C++ | Source/KBFL/Private/BFL/KBFL_Widgets.cpp | Kyri123/KBFL | 85408de8540b7839474ffc02b414e6235e58d133 | [
"MIT"
] | null | null | null | Source/KBFL/Private/BFL/KBFL_Widgets.cpp | Kyri123/KBFL | 85408de8540b7839474ffc02b414e6235e58d133 | [
"MIT"
] | null | null | null | Source/KBFL/Private/BFL/KBFL_Widgets.cpp | Kyri123/KBFL | 85408de8540b7839474ffc02b414e6235e58d133 | [
"MIT"
] | null | null | null | #include "BFL/KBFL_Widgets.h"
#include <string>
#include "Blueprint/UserWidget.h"
#include "Patching/BlueprintHookHelper.h"
#include "Patching/BlueprintHookManager.h"
void UKBFL_Widgets::BindOnWidget(const TSubclassOf<UUserWidget> WidgetClass, FOnWidgetCreated Binding) {
if (!WidgetClass)
return;
UFunction* ConstructFunction = WidgetClass->FindFunctionByName(TEXT("Construct"));
if (!ConstructFunction || ConstructFunction->IsNative())
{
return;
}
UBlueprintHookManager* HookManager = GEngine->GetEngineSubsystem<UBlueprintHookManager>();
HookManager->HookBlueprintFunction(ConstructFunction, [Binding](FBlueprintHookHelper& HookHelper) {
Binding.ExecuteIfBound(Cast<UUserWidget>(HookHelper.GetContext()));
}, EPredefinedHookOffset::Return);
}
void UKBFL_Widgets::TextToNumbers(float& Float, int& Int, FText Text, bool ShouldClamp, float ClampMin, float ClampMax,
bool ShouldRound)
{
Float = FCString::Atof(*Text.ToString());
if(ShouldRound)
Float = FMath::RoundToFloat(Float);
if(ShouldClamp)
Float = FMath::Clamp(Float, ClampMin, ClampMax);
Int = FMath::RoundToInt(Float);
}
void UKBFL_Widgets::SortFloatArray(TArray<float>& FloatArray)
{
FloatArray.Sort();
}
void UKBFL_Widgets::SortIntArray(TArray<float>& IntArray)
{
IntArray.Sort();
}
| 26.163265 | 119 | 0.769111 | Kyri123 |
2d9a13f3d31907a1c5b9fa94b13756818d2f03df | 3,087 | cpp | C++ | src/dslang-dialect.cpp | ryanvbissell/dslang | 65379ca7bbefff0161d11343b742ac58452d37e7 | [
"BSD-2-Clause"
] | null | null | null | src/dslang-dialect.cpp | ryanvbissell/dslang | 65379ca7bbefff0161d11343b742ac58452d37e7 | [
"BSD-2-Clause"
] | null | null | null | src/dslang-dialect.cpp | ryanvbissell/dslang | 65379ca7bbefff0161d11343b742ac58452d37e7 | [
"BSD-2-Clause"
] | null | null | null | // vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab :
/*
* Copyright (c) 2014-2017, Ryan V. Bissell
* All rights reserved.
*
* SPDX-License-Identifier: BSD-2-Clause
* See the enclosed "LICENSE" file for exact license terms.
*/
#define CX_TRACE_SECTION "dslang"
#include "dslang-dialect.hpp"
#include "dslang-lexer.hpp"
#include "sexpr-literal-bool.hpp"
#include "sexpr-literal-number.hpp"
#include "sexpr-literal-string.hpp"
#include "sexpr-ident.hpp"
#include "sexpr-cons.hpp"
#include "sexpr-quote.hpp"
using namespace DSL::detail;
using DSL::TokenHandler;
// ---------------------------------------------------------------------
CX_CONSTRUCTOR(DSL::Dialect::Dialect, :sc_(nullptr))
// this should be first, so it gets matched last
registerTokenizer(SexprIdent__Match, SexprIdent__Skip, SexprIdent__Parse);
registerTokenizer(SexprQuote__Match, SexprQuote__Skip, SexprQuote__Parse);
registerTokenizer(SexprCons__Match, SexprCons__Skip, SexprCons__Parse);
registerTokenizer(SexprString__Match, SexprString__Skip, SexprString__Parse);
registerTokenizer(SexprNumber__Match, SexprNumber__Skip, SexprNumber__Parse);
registerTokenizer(SexprBool__Match, SexprBool__Skip, SexprBool__Parse);
CX_ENDMETHOD
CX_DESTRUCTOR(DSL::Dialect::~Dialect)
for (auto&& pair : tokenizers_)
delete pair.second;
CX_ENDMETHOD
// TODO, if made private, use DSL::detail::Context* for 'sc'
CX_METHOD(void DSL::Dialect::SetContext, DSL::Scheme* sc)
CX_ASSERT(!sc_); // this shouldn't get called multiple times
// TODO, can remove typecast if above TODO is completed
sc_ = dynamic_cast<Context*>(sc);
CX_ASSERT(sc_); // dynamic cast failed?
CX_ENDMETHOD
CX_CONSTMETHOD(TokenHandler const* DSL::Dialect::GetTokenHandler,
char const* text)
#if 1
// C++17 version:
for (auto&& [match,handler] : tokenizers_)
if (match(text))
CX_RETURN(handler);
#else
// C++11 version:
for (auto&& pair : tokenizers_)
if (pair.first(text))
CX_RETURN(pair.second);
#endif
CX_RETURN(nullptr);
CX_ENDMETHOD
CX_METHOD(void DSL::Dialect::registerTokenizer, TokenMatcher match,
TokenSkipper skip,
TokenParser parse)
TokenHandler const* phandler = new TokenHandler{skip, parse};
// we use a deque so that custom dialects can override
// built-in token handlers, when we iterate for a match
tokenizers_.push_front(std::make_pair(match,phandler));
CX_ENDMETHOD
#if 0
CX_CONSTMETHOD(bool DSL::Dialect::IsCustomToken, char const * const text)
CX_RETURN(false); // class must be overridden for this behavior
CX_ENDMETHOD
CX_CONSTMETHOD(const SexprCUSTOM* DSL::Dialect::ParseCustom, const string& lexeme)
CX_ASSERT(false); // TODO, needs to be fatal, internal error
// This is supposed to be overridden, and never called
// It is not pure-virtual because the class overall is
// designed to be used as the default behavior.
CX_RETURN(nullptr);
CX_ENDMETHOD
#endif
| 25.725 | 82 | 0.695497 | ryanvbissell |
2d9da9e8ea4881618a1565400df9900f16745d78 | 17,746 | cpp | C++ | lib/graphics/src/Font.cpp | MarkRDavison/zeno | cea002e716e624d28130e836bf56e9f2f1d2e484 | [
"MIT"
] | null | null | null | lib/graphics/src/Font.cpp | MarkRDavison/zeno | cea002e716e624d28130e836bf56e9f2f1d2e484 | [
"MIT"
] | null | null | null | lib/graphics/src/Font.cpp | MarkRDavison/zeno | cea002e716e624d28130e836bf56e9f2f1d2e484 | [
"MIT"
] | null | null | null | #include <zeno/Graphics/Font.hpp>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <zeno/Graphics/Image.hpp>
#include <zeno/Graphics/Colour.hpp>
#include <algorithm>
#include <iostream>
#include <cmath>
#define MARGIN 2
#define DIST_MARGIN 4
#define ATLAS_WIDTH 1024
#define SEED_CHARS "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()[]{}?><,./\\\"' :;~|-`=+_"
namespace ze {
struct Point {
Point() : Point(9999, 9999) {
}
Point(int _dx, int _dy) {
dx = _dx;
dy = _dy;
}
int dx, dy;
int DistSq() const { return dx * dx + dy * dy; }
};
struct Grid {
Grid(unsigned _width, unsigned _height, int _starting) :
Width(_width),
Height(_height) {
grid = new Point * [_height];
for (unsigned y = 0; y < _height; ++y) {
grid[y] = new Point[_width];
for (unsigned x = 0; x < _width; ++x) {
grid[y][x].dx = _starting;
grid[y][x].dy = _starting;
}
}
}
~Grid() {
for (unsigned y = 0; y < Height; ++y) {
delete[] grid[y];
}
delete[] grid;
}
const unsigned Width;
const unsigned Height;
Point** grid;
};
Point inside = { 0, 0 };
Point empty = { 9999, 9999 };
Point Get(Grid& g, int x, int y) {
// OPTIMIZATION: you can skip the edge check code if you make your grid
// have a 1-pixel gutter.
if (x >= 0 && y >= 0 && x < static_cast<int>(g.Width) && y < static_cast<int>(g.Height))
return g.grid[y][x];
else
return empty;
}
void Put(Grid& g, int x, int y, const Point& p) {
g.grid[y][x] = p;
}
void Compare(Grid& g, Point& p, int x, int y, int offsetx, int offsety) {
Point other = Get(g, x + offsetx, y + offsety);
other.dx += offsetx;
other.dy += offsety;
if (other.DistSq() < p.DistSq())
p = other;
}
void GenerateSDF(Grid& g) {
// Pass 0
for (int y = 0; y < static_cast<int>(g.Height); y++) {
for (int x = 0; x < static_cast<int>(g.Width); x++) {
Point p = Get(g, x, y);
Compare(g, p, x, y, -1, 0);
Compare(g, p, x, y, 0, -1);
Compare(g, p, x, y, -1, -1);
Compare(g, p, x, y, 1, -1);
Put(g, x, y, p);
}
for (int x = static_cast<int>(g.Width) - 1; x >= 0; x--) {
Point p = Get(g, x, y);
Compare(g, p, x, y, 1, 0);
Put(g, x, y, p);
}
}
// Pass 1
for (int y = static_cast<int>(g.Height) - 1; y >= 0; y--) {
for (int x = static_cast<int>(g.Width) - 1; x >= 0; x--) {
Point p = Get(g, x, y);
Compare(g, p, x, y, 1, 0);
Compare(g, p, x, y, 0, 1);
Compare(g, p, x, y, -1, 1);
Compare(g, p, x, y, 1, 1);
Put(g, x, y, p);
}
for (int x = 0; x < static_cast<int>(g.Width); x++) {
Point p = Get(g, x, y);
Compare(g, p, x, y, -1, 0);
Put(g, x, y, p);
}
}
}
Font::Font(FontType _type /*= FontType::Default*/) :
m_GenerationSize(0),
type(_type) {
FT_Library lib;
FT_Init_FreeType(&lib);
m_Library = lib;
}
Font::Font(const std::string& _filename, unsigned _generationSize, FontType _type /*= FontType::Default*/) :
type(_type) {
FT_Library lib;
FT_Init_FreeType(&lib);
m_Library = lib;
loadFromFile(_filename, _generationSize);
}
Font::~Font() {
if (m_Loaded) {
const FT_Library lib = static_cast<FT_Library>(m_Library);
FT_Done_FreeType(lib);
}
}
bool genChar(Image& _image, char _c, FT_Face _face) {
const FT_UInt glyphIndex = FT_Get_Char_Index(_face, _c);
const FT_Error loadGlyphError = FT_Load_Glyph(_face, glyphIndex, FT_LOAD_RENDER);
if (loadGlyphError != 0) {
// Failed to load glyph
return false;
}
const FT_GlyphSlot glyph = _face->glyph;
Grid grid1(glyph->bitmap.width + 2 * DIST_MARGIN, glyph->bitmap.rows + 2 * DIST_MARGIN, 0);
Grid grid2(glyph->bitmap.width + 2 * DIST_MARGIN, glyph->bitmap.rows + 2 * DIST_MARGIN, 9999);
for (int y = 0; y < static_cast<int>(glyph->bitmap.rows); y++) {
for (int x = 0; x < static_cast<int>(glyph->bitmap.width); x++) {
// TODO: Put a border around the generated image when atlassing ...
if (y >= static_cast<int>(glyph->bitmap.rows) || x >= static_cast<int>(glyph->bitmap.width)) {
Put(grid2, x + DIST_MARGIN, y + DIST_MARGIN, inside);
Put(grid1, x + DIST_MARGIN, y + DIST_MARGIN, empty);
} else {
const float value = static_cast<float>(glyph->bitmap.buffer[y * glyph->bitmap.width + x]) / 255.0f;
// Points inside get marked with a dx/dy of zero.
// Points outside get marked with an infinitely large distance.
if (value < 0.5f) {
Put(grid1, x + DIST_MARGIN, y + DIST_MARGIN, inside);
Put(grid2, x + DIST_MARGIN, y + DIST_MARGIN, empty);
} else {
Put(grid2, x + DIST_MARGIN, y + DIST_MARGIN, inside);
Put(grid1, x + DIST_MARGIN, y + DIST_MARGIN, empty);
}
}
}
}
GenerateSDF(grid1);
GenerateSDF(grid2);
_image.create(grid1.Width, grid1.Height);
for (int y = 0; y < static_cast<int>(grid1.Height); y++) {
for (int x = 0; x < static_cast<int>(grid1.Width); x++) {
// Calculate the actual distance from the dx/dy
const int dist1 = static_cast<int>(sqrt(static_cast<double>(Get(grid1, x, y).DistSq())));
const int dist2 = static_cast<int>(sqrt(static_cast<double>(Get(grid2, x, y).DistSq())));
const int dist = dist1 - dist2;
// Clamp and scale it.
int c = dist * 3 + 128;
if (c < 0) c = 0;
if (c > 255) c = 255;
_image.setPixel(x, y, ze::Colour(static_cast<float>(c) / 255.0f, 0.0f, 0.0f));
}
}
return true;
}
bool Font::loadFontFile(const std::string& _filename, unsigned _generationSize, FontType _type /*= FontType::Default*/) {
m_GlyphData.clear();
m_Loaded = false;
m_GenerationSize = _generationSize;
type = _type;
if (type == FontType::SignedDistanceField) {
return loadFromFileSDF(_filename, _generationSize);
}
return loadFromFileDefault(_filename, _generationSize);
}
bool Font::createFont() {
if (!m_Texture.loadFromImage(m_Image)) {
std::cerr << "Failed to create font atlas texture from image" << std::endl;
return false;
}
m_Loaded = true;
return true;
}
bool Font::loadFromFile(const std::string& _filename, unsigned _generationSize, FontType _type /*= FontType::Default*/) {
if (!loadFontFile(_filename, _generationSize, _type)) {
return false;
}
return createFont();
}
const ze::Texture& Font::getTexture() const {
return m_Texture;
}
void Font::generateText(ze::VertexArray& _vertexArray, const std::string& _text, unsigned _characterSize) {
_vertexArray = ze::VertexArray(_text.size() * 6);
ze::Vector2f penPosition;
const ze::Vector2u textureSize = m_Texture.getSize();
const float charSize = static_cast<float>(_characterSize);
const float ratio = charSize / static_cast<float>(m_GenerationSize);
for (unsigned i = 0; i < _text.size(); ++i) {
const char _c = _text[i];
if (_c == ' ') {
penPosition.x += charSize / 8.0f;
continue;
}
if (m_GlyphData.count(_c) == 0) {
std::cerr << "Cannot use character '" << _c << "' in text." << std::endl;
continue;
}
const Glyph& g = m_GlyphData[_c];
// Kerning, rise etc
const ze::Vector2f charOffset{ 0.0f, static_cast<float>(g.bearingY >> 6) - static_cast<float>(g.h) };
_vertexArray[i * 6 + 0] = ze::Vertex{ ze::Vector3f{
penPosition.x + (charOffset.x) * ratio,
penPosition.y + (charOffset.y) * ratio,
0.0f
}, ze::Colour::White, ze::Vector2f{
static_cast<float>(g.x) / textureSize.x,
1.0f - (static_cast<float>(g.y + g.h) / textureSize.y)
} };
_vertexArray[i * 6 + 1] = ze::Vertex{ ze::Vector3f{
penPosition.x + (charOffset.x + g.w) * ratio,
penPosition.y + (charOffset.y) * ratio,
0.0f
}, ze::Colour::White, ze::Vector2f{
static_cast<float>(g.x + g.w) / textureSize.x,
1.0f - (static_cast<float>(g.y + g.h) / textureSize.y)
} };
_vertexArray[i * 6 + 2] = ze::Vertex{ ze::Vector3f{
penPosition.x + (charOffset.x + g.w) * ratio,
penPosition.y + (charOffset.y + g.h) * ratio,
0.0f
}, ze::Colour::White, ze::Vector2f{
static_cast<float>(g.x + g.w) / textureSize.x,
1.0f - (static_cast<float>(g.y) / textureSize.y)
} };
_vertexArray[i * 6 + 3] = ze::Vertex{ ze::Vector3f{
penPosition.x + (charOffset.x) * ratio,
penPosition.y + (charOffset.y) * ratio,
0.0f
}, ze::Colour::White, ze::Vector2f{
static_cast<float>(g.x) / textureSize.x,
1.0f - (static_cast<float>(g.y + g.h) / textureSize.y)
} };
_vertexArray[i * 6 + 4] = ze::Vertex{ ze::Vector3f{
penPosition.x + (charOffset.x + g.w) * ratio,
penPosition.y + (charOffset.y + g.h) * ratio,
0.0f
}, ze::Colour::White, ze::Vector2f{
static_cast<float>(g.x + g.w) / textureSize.x,
1.0f - (static_cast<float>(g.y) / textureSize.y)
} };
_vertexArray[i * 6 + 5] = ze::Vertex{ ze::Vector3f{
penPosition.x + (charOffset.x) * ratio,
penPosition.y + (charOffset.y + g.h) * ratio,
0.0f
}, ze::Colour::White, ze::Vector2f{
static_cast<float>(g.x) / textureSize.x,
1.0f - (static_cast<float>(g.y) / textureSize.y)
} };
penPosition.x += static_cast<float>(g.w) * ratio;
}
_vertexArray.create();
}
bool Font::loadFromFileSDF(const std::string& _filename, unsigned _generationSize) {
const FT_Library lib = static_cast<FT_Library>(m_Library);
FT_Face face;
const FT_Error newFaceError = FT_New_Face(lib, _filename.c_str(), 0, &face);
if (newFaceError != 0) {
// Failed to create font face
return false;
}
const FT_Error setPixelError = FT_Set_Pixel_Sizes(face, 0, m_GenerationSize);
if (setPixelError != 0) {
// Failed to set pixel size
return false;
}
m_Image.create(ATLAS_WIDTH, ATLAS_WIDTH);
const std::string chars = SEED_CHARS;
unsigned currentX = 0;
unsigned currentY = 0;
unsigned nextY = 0;
for (unsigned i = 0; i < chars.size(); ++i) {
const char c = chars[i];
ze::Image image;
if (!genChar(image, c, face)) {
std::cerr << "Failed to load character '" << c << "'" << std::endl;
continue;
}
if (currentX + image.getSize().x + 2 * MARGIN >= m_Image.getSize().x) {
// Need to go to next row
currentX = 0;
currentY = nextY;
if (currentY + image.getSize().y + 2 * MARGIN >= m_Image.getSize().y) {
m_Image.expandVertically(m_Image.getSize().y);
}
}
for (unsigned y = 0; y < image.getSize().y; ++y) {
for (unsigned x = 0; x < image.getSize().x; ++x) {
m_Image.setPixel(currentX + x + MARGIN, currentY + y + MARGIN, image.getPixel(x, y));
}
}
const auto v1 = face->glyph->metrics.height >> 6;
const auto v2 = face->glyph->metrics.horiBearingY >> 6;
Glyph g;
g.c = c;
g.x = currentX + MARGIN;
g.y = currentY + MARGIN;
g.w = image.getSize().x;
g.h = image.getSize().y;
g.yOff = static_cast<float>(v2) - static_cast<float>(v1);
g.top = face->glyph->bitmap_top;
g.left = face->glyph->bitmap_left;
g.bearingY = face->glyph->metrics.horiBearingY;
g.advanceY = face->glyph->metrics.vertAdvance;
g.heightRatio = static_cast<float>(g.h) / static_cast<float>(m_GenerationSize);
g.widthRatio = static_cast<float>(g.w) / static_cast<float>(m_GenerationSize);
m_GlyphData[c] = g;
nextY = std::max(currentY + image.getSize().y + 2 * MARGIN, nextY);
currentX += image.getSize().x + 2 * MARGIN;
}
return true;
}
bool genCharNonSDF(Image& _image, char _c, FT_Face _face) {
const FT_UInt glyphIndex = FT_Get_Char_Index(_face, _c);
const FT_Error loadGlyphError = FT_Load_Glyph(_face, glyphIndex, FT_LOAD_RENDER);
if (loadGlyphError != 0) {
// Failed to load glyph
return false;
}
const FT_GlyphSlot glyph = _face->glyph;
_image.create(glyph->bitmap.width + 2 * DIST_MARGIN, glyph->bitmap.rows + 2 * DIST_MARGIN, ze::Colour::Transparent);
for (int y = 0; y < static_cast<int>(glyph->bitmap.rows); y++) {
for (int x = 0; x < static_cast<int>(glyph->bitmap.width); x++) {
if (y >= static_cast<int>(glyph->bitmap.rows) || x >= static_cast<int>(glyph->bitmap.width)) {
continue;
}
const float value = static_cast<float>(glyph->bitmap.buffer[y * glyph->bitmap.width + x]) / 255.0f;
_image.setPixel(x + DIST_MARGIN, y + DIST_MARGIN, ze::Colour(value, 0.0f, 0.0f, 1.0f));
}
}
return true;
}
bool Font::loadFromFileDefault(const std::string& _filename, unsigned _generationSize) {
const FT_Library lib = static_cast<FT_Library>(m_Library);
FT_Face face;
const FT_Error newFaceError = FT_New_Face(lib, _filename.c_str(), 0, &face);
if (newFaceError != 0) {
// Failed to create font face
return false;
}
const FT_Error setPixelError = FT_Set_Pixel_Sizes(face, 0, m_GenerationSize);
if (setPixelError != 0) {
// Failed to set pixel size
return false;
}
m_Image.create(ATLAS_WIDTH, ATLAS_WIDTH);
const std::string chars = SEED_CHARS;
unsigned currentX = 0;
unsigned currentY = 0;
unsigned nextY = 0;
for (unsigned i = 0; i < chars.size(); ++i) {
const char c = chars[i];
ze::Image image;
if (!genCharNonSDF(image, c, face)) {
std::cerr << "Failed to load character '" << c << "'" << std::endl;
continue;
}
if (currentX + image.getSize().x + 2 * MARGIN >= m_Image.getSize().x) {
// Need to go to next row
currentX = 0;
currentY = nextY;
if (currentY + image.getSize().y + 2 * MARGIN >= m_Image.getSize().y) {
m_Image.expandVertically(m_Image.getSize().y);
}
}
for (unsigned y = 0; y < image.getSize().y; ++y) {
for (unsigned x = 0; x < image.getSize().x; ++x) {
m_Image.setPixel(currentX + x + MARGIN, currentY + y + MARGIN, image.getPixel(x, y));
}
}
const auto v1 = face->glyph->metrics.height >> 6;
const auto v2 = face->glyph->metrics.horiBearingY >> 6;
Glyph g;
g.c = c;
g.x = currentX + MARGIN;
g.y = currentY + MARGIN;
g.w = image.getSize().x;
g.h = image.getSize().y;
g.yOff = static_cast<float>(v2) - static_cast<float>(v1);
g.top = face->glyph->bitmap_top;
g.left = face->glyph->bitmap_left;
g.bearingY = face->glyph->metrics.horiBearingY;
g.advanceY = face->glyph->metrics.vertAdvance;
g.heightRatio = static_cast<float>(g.h) / static_cast<float>(m_GenerationSize);
g.widthRatio = static_cast<float>(g.w) / static_cast<float>(m_GenerationSize);
m_GlyphData[c] = g;
nextY = std::max(currentY + image.getSize().y + 2 * MARGIN, nextY);
currentX += image.getSize().x + 2 * MARGIN;
}
return true;
}
}
| 35.850505 | 125 | 0.503268 | MarkRDavison |
2d9de769f273f496b186898192937f660c48b656 | 9,383 | cpp | C++ | Tests/Core/TestHashMap.cpp | EgorOrachyov/Berserk | 0fcd3571b5aa0a1e073a2280035d445b2be94cbf | [
"MIT"
] | 43 | 2018-12-21T15:01:20.000Z | 2022-01-12T04:22:38.000Z | Tests/Core/TestHashMap.cpp | EgorOrachyov/Berserk | 0fcd3571b5aa0a1e073a2280035d445b2be94cbf | [
"MIT"
] | 22 | 2018-10-06T14:10:05.000Z | 2021-12-31T17:58:40.000Z | Tests/Core/TestHashMap.cpp | EgorOrachyov/Berserk | 0fcd3571b5aa0a1e073a2280035d445b2be94cbf | [
"MIT"
] | 4 | 2019-04-14T05:59:33.000Z | 2021-05-21T10:34:57.000Z |
/**********************************************************************************/
/* This file is part of Berserk Engine project */
/* https://github.com/EgorOrachyov/Berserk */
/**********************************************************************************/
/* MIT License */
/* */
/* Copyright (c) 2018 - 2021 Egor Orachyov */
/* */
/* 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 <gtest/gtest.h>
#include <PlatformSetup.hpp>
#include <BerserkCore/Strings/String.hpp>
#include <BerserkCore/Templates/HashMap.hpp>
#include <BerserkCore/Debug/Debug.hpp>
#include <chrono>
using namespace Berserk;
BERSERK_DEFINE_FIXTURE(HashMapFixture)
#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
static const char* keys[] = {
BERSERK_TEXT("Asafkjn AKFBsa nalsnfl []turt ,;lasdfkqpowe817289"),
BERSERK_TEXT("Asaoiqwj8923 nflkwn flwenf lc eoi1984783v"),
BERSERK_TEXT("Asancrkj wen r2o345-40=-= -=- 783v"),
BERSERK_TEXT("Asancrkj kqejbwjk bnjq 2n4trp438y2058 vdsfv 132"),
BERSERK_TEXT("Asancrkj kqejlr2n o635216 01263 9"),
BERSERK_TEXT("23 408 182-3 nln f jl 1nl635216 01263 9"),
BERSERK_TEXT("23 4qm lkm3;krmwekmjrp9432u=6b705 m0=i 439yu=0y 35216 01263 9"),
BERSERK_TEXT("23 4qm lkm3;krmwa. f.nrnweljrnlewj prm.....we r.w/e 263 9"),
BERSERK_TEXT("23 4qm lkm3;krmwa. f.nr;qwkjp19283-91 4363 9"),
BERSERK_TEXT("23 4qm lkm3;krmwa. f.nr;qwk-=p-=- =-=-==-=234= 0-=04=23jknjo nonfinroefn ")
};
static const char* keysRemove[] = {
BERSERK_TEXT("23 408 182-3 nln f jl 1nl635216 01263 9"),
BERSERK_TEXT("23 4qm lkm3;krmwekmjrp9432u=6b705 m0=i 439yu=0y 35216 01263 9"),
BERSERK_TEXT("23 4qm lkm3;krmwa. f.nrnweljrnlewj prm.....we r.w/e 263 9"),
BERSERK_TEXT("23 4qm lkm3;krmwa. f.nr;qwkjp19283-91 4363 9"),
BERSERK_TEXT("23 4qm lkm3;krmwa. f.nr;qwk-=p-=- =-=-==-=234= 0-=04=23jknjo nonfinroefn ")
};
static int64 values[] = {
1,
0,
-3425,
123,
214325,
12312413523,
-2134
-11111,
325345,
12312313,
-23402375897490
};
TEST_F(HashMapFixture, Setup) {
ASSERT_EQ(ARRAY_SIZE(keys), ARRAY_SIZE(values));
HashMap<String, int64> map;
for (auto i = 0; i < ARRAY_SIZE(keys); i++) {
map.Add(keys[i], values[i]);
}
EXPECT_EQ(map.GetSize(), ARRAY_SIZE(keys));
for (auto i = 0; i < ARRAY_SIZE(keys); i++) {
EXPECT_TRUE(map.Contains(keys[i]));
}
for (auto i = 0; i < ARRAY_SIZE(keys); i++) {
map.Remove(keys[i]);
}
EXPECT_TRUE(map.IsEmpty());
}
TEST_F(HashMapFixture, Iterator) {
ASSERT_EQ(ARRAY_SIZE(keys), ARRAY_SIZE(values));
HashMap<String, int64> map;
for (auto i = 0; i < ARRAY_SIZE(keys); i++) {
map.Add(keys[i], values[i]);
}
EXPECT_EQ(map.GetSize(), ARRAY_SIZE(keys));
const auto& constMap = map;
for (auto& p: constMap) {
BERSERK_CORE_LOG_INFO(BERSERK_TEXT("\"{0}\":{1}"), p.GetFirst(), p.GetSecond());
}
}
TEST_F(HashMapFixture, RemoveAdd) {
ASSERT_EQ(ARRAY_SIZE(keys), ARRAY_SIZE(values));
HashMap<String, int64> map;
for (auto i = 0; i < ARRAY_SIZE(keys); i++) {
map.Add(keys[i], values[i]);
}
EXPECT_EQ(map.GetSize(), ARRAY_SIZE(keys));
for (auto & i : keysRemove) {
map.Remove(i);
}
EXPECT_EQ(map.GetSize(), ARRAY_SIZE(keys) - ARRAY_SIZE(keysRemove));
for (auto i = 0; i < ARRAY_SIZE(keys); i++) {
map.AddIfNotPresent(keys[i], values[i]);
}
EXPECT_EQ(map.GetSize(), ARRAY_SIZE(keys));
}
TEST_F(HashMapFixture, StringString) {
HashMap<String, String> map;
Array<Pair<String,String>> pairs = {
{ BERSERK_TEXT("Alice"), BERSERK_TEXT("1124-1123-12-75") },
{ BERSERK_TEXT("Bob"), BERSERK_TEXT("1873-4353-00-75") },
{ BERSERK_TEXT("Tom"), BERSERK_TEXT("2357-2367-45-56") },
{ BERSERK_TEXT("Sam"), BERSERK_TEXT("8000-4463-66-59") },
{ BERSERK_TEXT("Joel"), BERSERK_TEXT("4367-3789-11-56") }
};
map.Add(pairs.GetData(), pairs.GetSize());
BERSERK_CORE_LOG_INFO(BERSERK_TEXT("HashMap stats: size={0} range={1} loadfactor={2}"), map.GetSize(), map.GetRange(), map.GetLoadFactor());
Array<String> extractedKeys;
Array<Pair<String,String>> extractedKeyValues;
map.GetKeys(extractedKeys);
map.GetKeyValues(extractedKeyValues);
BERSERK_CORE_LOG_INFO(BERSERK_TEXT("HashMap keys: {0}"), extractedKeys);
BERSERK_CORE_LOG_INFO(BERSERK_TEXT("HashMap key-values: {0}"), extractedKeyValues);
}
TEST_F(HashMapFixture, Value) {
struct V {
V(uint32 i) {
data = i;
}
uint32 data;
};
HashMap<uint32, V> map;
uint32 N = 10;
for (uint32 i = 0; i < N; i++)
map.Add(i, V(i * i + i));
for (auto& p: map)
BERSERK_CORE_LOG_INFO(BERSERK_TEXT("{0}:{1}"), p.GetFirst(), p.GetSecond().data);
for (uint32 i = 0; i < N; i++)
EXPECT_TRUE(map.Contains(i));
for (uint32 i = 0; i < N; i++) {
ASSERT_TRUE(map.GetPtr(i));
EXPECT_EQ(map.GetPtr(i)->data, i * i + i);
}
}
TEST_F(HashMapFixture, Iterating) {
HashMap<String, String> map;
Array<Pair<String,String>> pairs = {
{ BERSERK_TEXT("Alice"), BERSERK_TEXT("1124-1123-12-75") },
{ BERSERK_TEXT("Bob"), BERSERK_TEXT("1873-4353-00-75") },
{ BERSERK_TEXT("Tom"), BERSERK_TEXT("2357-2367-45-56") },
{ BERSERK_TEXT("Sam"), BERSERK_TEXT("8000-4463-66-59") },
{ BERSERK_TEXT("Joel"), BERSERK_TEXT("4367-3789-11-56") }
};
Array<String> toRemove = {
BERSERK_TEXT("Bob"),
BERSERK_TEXT("Joel"),
};
Array<String> toKeep = {
BERSERK_TEXT("Alice"),
BERSERK_TEXT("Tom"),
BERSERK_TEXT("Sam"),
};
map.Add(pairs.GetData(), pairs.GetSize());
auto iter = map.begin();
while (iter != map.end()) {
if (toRemove.Contains<Equals<String>>((*iter).GetFirst()))
iter = map.Remove(iter);
else
++iter;
}
for (auto& keep: toKeep) {
EXPECT_TRUE(map.Contains(keep));
}
EXPECT_EQ(map.GetSize(), toKeep.GetSize());
}
TEST_F(HashMapFixture, Perfomance) {
struct Data {
uint64 v1;
uint64 v2;
uint64 v3;
uint64 v4;
};
Data d{};
size_t start = 0;
size_t count = 1000;
size_t removeStep = 10;
size_t iters = 1000;
using clock = std::chrono::steady_clock;
using nanoseconds = std::chrono::nanoseconds;
HashMap<String, Data> cache;
double total;
double average = 0.0;
auto globalStart = clock::now();
for (size_t iteration = 0; iteration < iters; iteration++) {
auto localStart = clock::now();
for (uint64 i = start; i < start + count; i++) {
auto key = String::Fromu64(i);
cache.AddIfNotPresent(key, d);
}
for (uint64 i = start + (iteration % removeStep); i < start + count; i += removeStep) {
auto key = String::Fromu64(i);
cache.Remove(key);
}
average += (double) std::chrono::duration_cast<nanoseconds>(clock::now() - localStart).count() / 1e6f;
}
total = (double) std::chrono::duration_cast<nanoseconds>(clock::now() - globalStart).count() / 1e6f;
average /= (double) iters;
BERSERK_CORE_LOG_INFO("Total={0} ms Average={1} ms Cache size={2}", total, average, cache.GetSize());
}
BERSERK_GTEST_MAIN | 33.510714 | 144 | 0.553448 | EgorOrachyov |
2d9fc50ce93218efce08ee0e4ed74700e5543f0d | 1,411 | cpp | C++ | lc508_most_frequent_subtree_sum.cpp | hzwr/Basics | cd4d8625636af987efdf36c0bea186928bc9e1a7 | [
"MIT"
] | null | null | null | lc508_most_frequent_subtree_sum.cpp | hzwr/Basics | cd4d8625636af987efdf36c0bea186928bc9e1a7 | [
"MIT"
] | null | null | null | lc508_most_frequent_subtree_sum.cpp | hzwr/Basics | cd4d8625636af987efdf36c0bea186928bc9e1a7 | [
"MIT"
] | null | null | null | /*
Given the root of a binary tree, return the most frequent subtree sum. If there is a tie, return all the values with the highest frequency in any order.
The subtree sum of a node is defined as the sum of all the node values formed by the subtree rooted at that node (including the node itself).
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> findFrequentTreeSum(TreeNode* root) {
GetSum(root);
std::vector<int> sums;
for(auto &sum : m_sumOfSubtrees)
{
if(sum.second == maxCount)
{
sums.emplace_back(sum.first);
}
}
return sums;
}
private:
int maxCount = 0;
std::unordered_map<int, int> m_sumOfSubtrees;
int GetSum(TreeNode *root)
{
if(!root)
{
return 0;
}
int sum = root->val + GetSum(root->left) + GetSum(root->right);
m_sumOfSubtrees[sum]++;
maxCount = max(maxCount, m_sumOfSubtrees[sum]);
return sum;
}
}; | 26.12963 | 152 | 0.564139 | hzwr |
2da246c897b3ca2217934b6209339a722e8c35f6 | 727 | cpp | C++ | code/plugsrc/Bullet/pch.cpp | zaklaus/NEON86 | b1996fb6303cbb72bd0e93298617803f4b017c78 | [
"BSD-3-Clause"
] | 4 | 2021-01-23T15:38:25.000Z | 2021-12-31T15:12:21.000Z | code/plugsrc/Bullet/pch.cpp | zaklaus/NEON86 | b1996fb6303cbb72bd0e93298617803f4b017c78 | [
"BSD-3-Clause"
] | 9 | 2020-05-23T20:49:57.000Z | 2020-10-06T09:01:46.000Z | code/plugsrc/Bullet/pch.cpp | zaklaus/NEON86 | b1996fb6303cbb72bd0e93298617803f4b017c78 | [
"BSD-3-Clause"
] | null | null | null | #include "pch.h"
// When you are using pre-compiled headers, this source file is necessary for compilation to succeed.
#pragma comment(lib, "d3d9/d3dx9.lib")
#ifdef _DEBUG
#pragma comment(lib, "bullet/BulletCollision_Debug.lib")
#pragma comment(lib, "bullet/BulletDynamics_Debug.lib")
#pragma comment(lib, "bullet/BulletInverseDynamics_Debug.lib")
#pragma comment(lib, "bullet/BulletSoftBody_Debug.lib")
#pragma comment(lib, "bullet/LinearMath_Debug.lib")
#else
#pragma comment(lib, "bullet/BulletCollision.lib")
#pragma comment(lib, "bullet/BulletDynamics.lib")
#pragma comment(lib, "bullet/BulletInverseDynamics.lib")
#pragma comment(lib, "bullet/BulletSoftBody.lib")
#pragma comment(lib, "bullet/LinearMath.lib")
#endif
| 34.619048 | 101 | 0.781293 | zaklaus |
2da320f82b21297882073c8090b12588def6b135 | 564 | cpp | C++ | jni/WiEngine_binding/actions/com_wiyun_engine_actions_Follow.cpp | zchajax/WiEngine | ea2fa297f00aa5367bb5b819d6714ac84a8a8e25 | [
"MIT"
] | 39 | 2015-01-23T10:01:31.000Z | 2021-06-10T03:01:18.000Z | jni/WiEngine_binding/actions/com_wiyun_engine_actions_Follow.cpp | luckypen/WiEngine | 7e80641fe15a77a2fc43db90f15dad6aa2c2860a | [
"MIT"
] | 1 | 2015-04-15T08:07:47.000Z | 2015-04-15T08:07:47.000Z | jni/WiEngine_binding/actions/com_wiyun_engine_actions_Follow.cpp | luckypen/WiEngine | 7e80641fe15a77a2fc43db90f15dad6aa2c2860a | [
"MIT"
] | 20 | 2015-01-20T07:36:10.000Z | 2019-09-15T01:02:19.000Z | #include "com_wiyun_engine_actions_Follow.h"
#include "wyFollow.h"
#include "wyNode.h"
extern jfieldID g_fid_BaseObject_mPointer;
JNIEXPORT void JNICALL Java_com_wiyun_engine_actions_Follow_nativeInit
(JNIEnv * env, jobject thiz, jobject node, jint x, jint y, jint width, jint height) {
wyNode* fnode = (wyNode*)env->GetIntField(node, g_fid_BaseObject_mPointer);
wyRect rect = wyr(x, y, width, height);
wyFollow* a = wyFollow::make(fnode, rect);
env->SetIntField(thiz, g_fid_BaseObject_mPointer, (jint)a);
a->retain();
a->lazyRelease();
}
| 35.25 | 88 | 0.741135 | zchajax |
2da7b4ba09b0f21a8261b13e03d8f0dd62c6e8c6 | 2,584 | cpp | C++ | YorozuyaGSLib/source/CCircleZone.cpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | YorozuyaGSLib/source/CCircleZone.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | YorozuyaGSLib/source/CCircleZone.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | #include <CCircleZone.hpp>
START_ATF_NAMESPACE
CCircleZone::CCircleZone()
{
using org_ptr = void (WINAPIV*)(struct CCircleZone*);
(org_ptr(0x14012d660L))(this);
};
void CCircleZone::ctor_CCircleZone()
{
using org_ptr = void (WINAPIV*)(struct CCircleZone*);
(org_ptr(0x14012d660L))(this);
};
bool CCircleZone::Create(struct CMapData* pkMap, char byColor)
{
using org_ptr = bool (WINAPIV*)(struct CCircleZone*, struct CMapData*, char);
return (org_ptr(0x14012da60L))(this, pkMap, byColor);
};
void CCircleZone::Destroy()
{
using org_ptr = void (WINAPIV*)(struct CCircleZone*);
(org_ptr(0x14012db70L))(this);
};
char CCircleZone::GetColor()
{
using org_ptr = char (WINAPIV*)(struct CCircleZone*);
return (org_ptr(0x140034b20L))(this);
};
int CCircleZone::GetPortalInx()
{
using org_ptr = int (WINAPIV*)(struct CCircleZone*);
return (org_ptr(0x140034b00L))(this);
};
char CCircleZone::Goal(struct CMapData* pkMap, float* pfCurPos)
{
using org_ptr = char (WINAPIV*)(struct CCircleZone*, struct CMapData*, float*);
return (org_ptr(0x14012dbe0L))(this, pkMap, pfCurPos);
};
bool CCircleZone::Init(unsigned int uiMapInx, int iPlayerInx, int iNth, uint16_t wInx, struct CMapData* pkMap)
{
using org_ptr = bool (WINAPIV*)(struct CCircleZone*, unsigned int, int, int, uint16_t, struct CMapData*);
return (org_ptr(0x14012d740L))(this, uiMapInx, iPlayerInx, iNth, wInx, pkMap);
};
bool CCircleZone::IsNearPosition(float* pfCurPos)
{
using org_ptr = bool (WINAPIV*)(struct CCircleZone*, float*);
return (org_ptr(0x14012de20L))(this, pfCurPos);
};
void CCircleZone::SendMsgCreate()
{
using org_ptr = void (WINAPIV*)(struct CCircleZone*);
(org_ptr(0x14012dc60L))(this);
};
void CCircleZone::SendMsgGoal()
{
using org_ptr = void (WINAPIV*)(struct CCircleZone*);
(org_ptr(0x14012dda0L))(this);
};
void CCircleZone::SendMsg_FixPosition(int n)
{
using org_ptr = void (WINAPIV*)(struct CCircleZone*, int);
(org_ptr(0x14012dd00L))(this, n);
};
CCircleZone::~CCircleZone()
{
using org_ptr = void (WINAPIV*)(struct CCircleZone*);
(org_ptr(0x14012d6f0L))(this);
};
void CCircleZone::dtor_CCircleZone()
{
using org_ptr = void (WINAPIV*)(struct CCircleZone*);
(org_ptr(0x14012d6f0L))(this);
};
END_ATF_NAMESPACE
| 33.558442 | 114 | 0.62887 | lemkova |
2db006346dcb801fd761a89edb537502a81d53dc | 15,827 | cc | C++ | ns-3-dev/src/internet/model/ipv6-extension-header.cc | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | 11 | 2015-11-24T11:07:28.000Z | 2021-12-23T04:10:29.000Z | ns-3-dev/src/internet/model/ipv6-extension-header.cc | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | null | null | null | ns-3-dev/src/internet/model/ipv6-extension-header.cc | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | 6 | 2016-03-01T06:32:21.000Z | 2022-03-24T19:31:41.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2007-2009 Strasbourg University
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: David Gross <gdavid.devel@gmail.com>
*/
#include "ns3/assert.h"
#include "ns3/log.h"
#include "ns3/header.h"
#include "ipv6-extension-header.h"
namespace ns3
{
NS_LOG_COMPONENT_DEFINE ("Ipv6ExtensionHeader");
NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionHeader);
TypeId Ipv6ExtensionHeader::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::Ipv6ExtensionHeader")
.AddConstructor<Ipv6ExtensionHeader> ()
.SetParent<Header> ()
;
return tid;
}
TypeId Ipv6ExtensionHeader::GetInstanceTypeId () const
{
return GetTypeId ();
}
Ipv6ExtensionHeader::Ipv6ExtensionHeader ()
: m_nextHeader (0),
m_length (0),
m_data (0)
{
}
Ipv6ExtensionHeader::~Ipv6ExtensionHeader ()
{
}
void Ipv6ExtensionHeader::SetNextHeader (uint8_t nextHeader)
{
m_nextHeader = nextHeader;
}
uint8_t Ipv6ExtensionHeader::GetNextHeader () const
{
return m_nextHeader;
}
void Ipv6ExtensionHeader::SetLength (uint16_t length)
{
m_length = (length >> 3) - 1;
}
uint16_t Ipv6ExtensionHeader::GetLength () const
{
return (m_length + 1) << 3;
}
void Ipv6ExtensionHeader::Print (std::ostream &os) const
{
os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " )";
}
uint32_t Ipv6ExtensionHeader::GetSerializedSize () const
{
return 2;
}
void Ipv6ExtensionHeader::Serialize (Buffer::Iterator start) const
{
Buffer::Iterator i = start;
i.WriteU8 (m_nextHeader);
i.WriteU8 (m_length);
i.Write (m_data.PeekData (), m_data.GetSize ());
}
uint32_t Ipv6ExtensionHeader::Deserialize (Buffer::Iterator start)
{
Buffer::Iterator i = start;
m_nextHeader = i.ReadU8 ();
m_length = i.ReadU8 ();
uint32_t dataLength = GetLength () - 2;
uint8_t* data = new uint8_t[dataLength];
i.Read (data, dataLength);
if (dataLength > m_data.GetSize ())
{
m_data.AddAtEnd (dataLength - m_data.GetSize ());
}
else
{
m_data.RemoveAtEnd (m_data.GetSize () - dataLength);
}
i = m_data.Begin ();
i.Write (data, dataLength);
delete[] data;
return GetSerializedSize ();
}
OptionField::OptionField (uint32_t optionsOffset)
: m_optionData (0),
m_optionsOffset (optionsOffset)
{
}
OptionField::~OptionField ()
{
}
uint32_t OptionField::GetSerializedSize () const
{
return m_optionData.GetSize () + CalculatePad ((Ipv6OptionHeader::Alignment) { 8,0});
}
void OptionField::Serialize (Buffer::Iterator start) const
{
start.Write (m_optionData.Begin (), m_optionData.End ());
uint32_t fill = CalculatePad ((Ipv6OptionHeader::Alignment) { 8,0});
NS_LOG_LOGIC ("fill with " << fill << " bytes padding");
switch (fill)
{
case 0: return;
case 1: Ipv6OptionPad1Header ().Serialize (start);
return;
default: Ipv6OptionPadnHeader (fill).Serialize (start);
return;
}
}
uint32_t OptionField::Deserialize (Buffer::Iterator start, uint32_t length)
{
uint8_t* buf = new uint8_t[length];
start.Read (buf, length);
m_optionData = Buffer ();
m_optionData.AddAtEnd (length);
m_optionData.Begin ().Write (buf, length);
delete[] buf;
return length;
}
void OptionField::AddOption (Ipv6OptionHeader const& option)
{
NS_LOG_FUNCTION_NOARGS ();
uint32_t pad = CalculatePad (option.GetAlignment ());
NS_LOG_LOGIC ("need " << pad << " bytes padding");
switch (pad)
{
case 0: break; //no padding needed
case 1: AddOption (Ipv6OptionPad1Header ());
break;
default: AddOption (Ipv6OptionPadnHeader (pad));
break;
}
m_optionData.AddAtEnd (option.GetSerializedSize ());
Buffer::Iterator it = m_optionData.End ();
it.Prev (option.GetSerializedSize ());
option.Serialize (it);
}
uint32_t OptionField::CalculatePad (Ipv6OptionHeader::Alignment alignment) const
{
return (alignment.offset - (m_optionData.GetSize () + m_optionsOffset)) % alignment.factor;
}
uint32_t OptionField::GetOptionsOffset ()
{
return m_optionsOffset;
}
Buffer OptionField::GetOptionBuffer ()
{
return m_optionData;
}
NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionHopByHopHeader);
TypeId Ipv6ExtensionHopByHopHeader::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::Ipv6ExtensionHopByHopHeader")
.AddConstructor<Ipv6ExtensionHopByHopHeader> ()
.SetParent<Ipv6ExtensionHeader> ()
;
return tid;
}
TypeId Ipv6ExtensionHopByHopHeader::GetInstanceTypeId () const
{
return GetTypeId ();
}
Ipv6ExtensionHopByHopHeader::Ipv6ExtensionHopByHopHeader ()
: OptionField (2)
{
}
Ipv6ExtensionHopByHopHeader::~Ipv6ExtensionHopByHopHeader ()
{
}
void Ipv6ExtensionHopByHopHeader::Print (std::ostream &os) const
{
os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " )";
}
uint32_t Ipv6ExtensionHopByHopHeader::GetSerializedSize () const
{
return 2 + OptionField::GetSerializedSize ();
}
void Ipv6ExtensionHopByHopHeader::Serialize (Buffer::Iterator start) const
{
Buffer::Iterator i = start;
i.WriteU8 (GetNextHeader ());
i.WriteU8 ((GetLength () >> 3) - 1);
OptionField::Serialize (i);
}
uint32_t Ipv6ExtensionHopByHopHeader::Deserialize (Buffer::Iterator start)
{
Buffer::Iterator i = start;
SetNextHeader (i.ReadU8 ());
SetLength ((i.ReadU8 () + 1) << 3);
OptionField::Deserialize (i, GetLength () - 2);
return GetSerializedSize ();
}
NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionDestinationHeader);
TypeId Ipv6ExtensionDestinationHeader::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::Ipv6ExtensionDestinationHeader")
.AddConstructor<Ipv6ExtensionDestinationHeader> ()
.SetParent<Ipv6ExtensionHeader> ()
;
return tid;
}
TypeId Ipv6ExtensionDestinationHeader::GetInstanceTypeId () const
{
return GetTypeId ();
}
Ipv6ExtensionDestinationHeader::Ipv6ExtensionDestinationHeader ()
: OptionField (2)
{
}
Ipv6ExtensionDestinationHeader::~Ipv6ExtensionDestinationHeader ()
{
}
void Ipv6ExtensionDestinationHeader::Print (std::ostream &os) const
{
os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength () << " )";
}
uint32_t Ipv6ExtensionDestinationHeader::GetSerializedSize () const
{
return 2 + OptionField::GetSerializedSize ();
}
void Ipv6ExtensionDestinationHeader::Serialize (Buffer::Iterator start) const
{
Buffer::Iterator i = start;
i.WriteU8 (GetNextHeader ());
i.WriteU8 ((GetLength () >> 3) - 1);
OptionField::Serialize (i);
}
uint32_t Ipv6ExtensionDestinationHeader::Deserialize (Buffer::Iterator start)
{
Buffer::Iterator i = start;
SetNextHeader (i.ReadU8 ());
SetLength ((i.ReadU8 () + 1) << 3);
OptionField::Deserialize (i, GetLength () - 2);
return GetSerializedSize ();
}
NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionFragmentHeader);
TypeId Ipv6ExtensionFragmentHeader::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::Ipv6ExtensionFragmentHeader")
.AddConstructor<Ipv6ExtensionFragmentHeader> ()
.SetParent<Ipv6ExtensionHeader> ()
;
return tid;
}
TypeId Ipv6ExtensionFragmentHeader::GetInstanceTypeId () const
{
return GetTypeId ();
}
Ipv6ExtensionFragmentHeader::Ipv6ExtensionFragmentHeader ()
: m_offset (0),
m_identification (0)
{
}
Ipv6ExtensionFragmentHeader::~Ipv6ExtensionFragmentHeader ()
{
}
void Ipv6ExtensionFragmentHeader::SetOffset (uint16_t offset)
{
// Clear the offset, and save the MF bit
m_offset &= 1;
m_offset |= offset & (~7);
}
uint16_t Ipv6ExtensionFragmentHeader::GetOffset () const
{
return m_offset & (~1);
}
void Ipv6ExtensionFragmentHeader::SetMoreFragment (bool moreFragment)
{
m_offset = moreFragment ? m_offset | 1 : m_offset & (~1);
}
bool Ipv6ExtensionFragmentHeader::GetMoreFragment () const
{
return m_offset & 1;
}
void Ipv6ExtensionFragmentHeader::SetIdentification (uint32_t identification)
{
m_identification = identification;
}
uint32_t Ipv6ExtensionFragmentHeader::GetIdentification () const
{
return m_identification;
}
void Ipv6ExtensionFragmentHeader::Print (std::ostream &os) const
{
os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength ()
<< " offset = " << (uint32_t)GetOffset () << " MF = " << (uint32_t)GetMoreFragment () << " identification = " << (uint32_t)m_identification << " )";
}
uint32_t Ipv6ExtensionFragmentHeader::GetSerializedSize () const
{
return 8;
}
void Ipv6ExtensionFragmentHeader::Serialize (Buffer::Iterator start) const
{
Buffer::Iterator i = start;
i.WriteU8 (GetNextHeader ());
i.WriteU8 ((GetLength () >> 3) - 1);
i.WriteHtonU16 (m_offset);
i.WriteHtonU32 (m_identification);
}
uint32_t Ipv6ExtensionFragmentHeader::Deserialize (Buffer::Iterator start)
{
Buffer::Iterator i = start;
SetNextHeader (i.ReadU8 ());
SetLength ((i.ReadU8 () + 1) << 3);
m_offset = i.ReadNtohU16 ();
m_identification = i.ReadNtohU32 ();
return GetSerializedSize ();
}
NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionRoutingHeader);
TypeId Ipv6ExtensionRoutingHeader::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::Ipv6ExtensionRoutingHeader")
.AddConstructor<Ipv6ExtensionRoutingHeader> ()
.SetParent<Ipv6ExtensionHeader> ()
;
return tid;
}
TypeId Ipv6ExtensionRoutingHeader::GetInstanceTypeId () const
{
return GetTypeId ();
}
Ipv6ExtensionRoutingHeader::Ipv6ExtensionRoutingHeader ()
: m_typeRouting (0),
m_segmentsLeft (0)
{
}
Ipv6ExtensionRoutingHeader::~Ipv6ExtensionRoutingHeader ()
{
}
void Ipv6ExtensionRoutingHeader::SetTypeRouting (uint8_t typeRouting)
{
m_typeRouting = typeRouting;
}
uint8_t Ipv6ExtensionRoutingHeader::GetTypeRouting () const
{
return m_typeRouting;
}
void Ipv6ExtensionRoutingHeader::SetSegmentsLeft (uint8_t segmentsLeft)
{
m_segmentsLeft = segmentsLeft;
}
uint8_t Ipv6ExtensionRoutingHeader::GetSegmentsLeft () const
{
return m_segmentsLeft;
}
void Ipv6ExtensionRoutingHeader::Print (std::ostream &os) const
{
os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength ()
<< " typeRouting = " << (uint32_t)m_typeRouting << " segmentsLeft = " << (uint32_t)m_segmentsLeft << " )";
}
uint32_t Ipv6ExtensionRoutingHeader::GetSerializedSize () const
{
return 4;
}
void Ipv6ExtensionRoutingHeader::Serialize (Buffer::Iterator start) const
{
Buffer::Iterator i = start;
i.WriteU8 (GetNextHeader ());
i.WriteU8 ((GetLength () >> 3) - 1);
i.WriteU8 (m_typeRouting);
i.WriteU8 (m_segmentsLeft);
}
uint32_t Ipv6ExtensionRoutingHeader::Deserialize (Buffer::Iterator start)
{
Buffer::Iterator i = start;
SetNextHeader (i.ReadU8 ());
SetLength ((i.ReadU8 () + 1) << 3);
m_typeRouting = i.ReadU8 ();
m_segmentsLeft = i.ReadU8 ();
return GetSerializedSize ();
}
NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionLooseRoutingHeader);
TypeId Ipv6ExtensionLooseRoutingHeader::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::Ipv6ExtensionLooseRoutingHeader")
.AddConstructor<Ipv6ExtensionLooseRoutingHeader> ()
.SetParent<Ipv6ExtensionRoutingHeader> ()
;
return tid;
}
TypeId Ipv6ExtensionLooseRoutingHeader::GetInstanceTypeId () const
{
return GetTypeId ();
}
Ipv6ExtensionLooseRoutingHeader::Ipv6ExtensionLooseRoutingHeader ()
: m_routersAddress (0)
{
}
Ipv6ExtensionLooseRoutingHeader::~Ipv6ExtensionLooseRoutingHeader ()
{
}
void Ipv6ExtensionLooseRoutingHeader::SetNumberAddress (uint8_t n)
{
m_routersAddress.clear ();
m_routersAddress.assign (n, Ipv6Address (""));
}
void Ipv6ExtensionLooseRoutingHeader::SetRoutersAddress (std::vector<Ipv6Address> routersAddress)
{
m_routersAddress = routersAddress;
}
std::vector<Ipv6Address> Ipv6ExtensionLooseRoutingHeader::GetRoutersAddress () const
{
return m_routersAddress;
}
void Ipv6ExtensionLooseRoutingHeader::SetRouterAddress (uint8_t index, Ipv6Address addr)
{
m_routersAddress.at (index) = addr;
}
Ipv6Address Ipv6ExtensionLooseRoutingHeader::GetRouterAddress (uint8_t index) const
{
return m_routersAddress.at (index);
}
void Ipv6ExtensionLooseRoutingHeader::Print (std::ostream &os) const
{
os << "( nextHeader = " << (uint32_t)GetNextHeader () << " length = " << (uint32_t)GetLength ()
<< " typeRouting = " << (uint32_t)GetTypeRouting () << " segmentsLeft = " << (uint32_t)GetSegmentsLeft () << " ";
for (std::vector<Ipv6Address>::const_iterator it = m_routersAddress.begin (); it != m_routersAddress.end (); it++)
{
os << *it << " ";
}
os << " )";
}
uint32_t Ipv6ExtensionLooseRoutingHeader::GetSerializedSize () const
{
return 8 + m_routersAddress.size () * 16;
}
void Ipv6ExtensionLooseRoutingHeader::Serialize (Buffer::Iterator start) const
{
Buffer::Iterator i = start;
uint8_t buff[16];
i.WriteU8 (GetNextHeader ());
i.WriteU8 ((GetLength () >> 3) - 1);
i.WriteU8 (GetTypeRouting ());
i.WriteU8 (GetSegmentsLeft ());
i.WriteU32 (0);
for (VectorIpv6Address_t::const_iterator it = m_routersAddress.begin (); it != m_routersAddress.end (); it++)
{
it->Serialize (buff);
i.Write (buff, 16);
}
}
uint32_t Ipv6ExtensionLooseRoutingHeader::Deserialize (Buffer::Iterator start)
{
Buffer::Iterator i = start;
uint8_t buff[16];
SetNextHeader (i.ReadU8 ());
SetLength ((i.ReadU8 () + 1) << 3);
SetTypeRouting (i.ReadU8 ());
SetSegmentsLeft (i.ReadU8 ());
i.ReadU32 ();
for (std::vector<Ipv6Address>::iterator it = m_routersAddress.begin (); it != m_routersAddress.end (); it++)
{
i.Read (buff, 16);
it->Set (buff);
}
return GetSerializedSize ();
}
NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionESPHeader);
TypeId Ipv6ExtensionESPHeader::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::Ipv6ExtensionESPHeader")
.AddConstructor<Ipv6ExtensionESPHeader> ()
.SetParent<Ipv6ExtensionHeader> ()
;
return tid;
}
TypeId Ipv6ExtensionESPHeader::GetInstanceTypeId () const
{
return GetTypeId ();
}
Ipv6ExtensionESPHeader::Ipv6ExtensionESPHeader ()
{
}
Ipv6ExtensionESPHeader::~Ipv6ExtensionESPHeader ()
{
}
void Ipv6ExtensionESPHeader::Print (std::ostream &os) const
{
/* TODO */
}
uint32_t Ipv6ExtensionESPHeader::GetSerializedSize () const
{
/* TODO */
return 0;
}
void Ipv6ExtensionESPHeader::Serialize (Buffer::Iterator start) const
{
/* TODO */
}
uint32_t Ipv6ExtensionESPHeader::Deserialize (Buffer::Iterator start)
{
/* TODO */
return 0;
}
NS_OBJECT_ENSURE_REGISTERED (Ipv6ExtensionAHHeader);
TypeId Ipv6ExtensionAHHeader::GetTypeId ()
{
static TypeId tid = TypeId ("ns3::Ipv6ExtensionAHHeader")
.AddConstructor<Ipv6ExtensionAHHeader> ()
.SetParent<Ipv6ExtensionHeader> ()
;
return tid;
}
TypeId Ipv6ExtensionAHHeader::GetInstanceTypeId () const
{
return GetTypeId ();
}
Ipv6ExtensionAHHeader::Ipv6ExtensionAHHeader ()
{
}
Ipv6ExtensionAHHeader::~Ipv6ExtensionAHHeader ()
{
}
void Ipv6ExtensionAHHeader::Print (std::ostream &os) const
{
/* TODO */
}
uint32_t Ipv6ExtensionAHHeader::GetSerializedSize () const
{
/* TODO */
return 0;
}
void Ipv6ExtensionAHHeader::Serialize (Buffer::Iterator start) const
{
/* TODO */
}
uint32_t Ipv6ExtensionAHHeader::Deserialize (Buffer::Iterator start)
{
/* TODO */
return 0;
}
} /* namespace ns3 */
| 23.138889 | 153 | 0.716371 | maxvonhippel |
2db1522b87c0c2bfcae509a646be0fea971edd2b | 6,954 | cc | C++ | ui/display/util/display_util.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | ui/display/util/display_util.cc | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | ui/display/util/display_util.cc | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // 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 "ui/display/util/display_util.h"
#include <stddef.h>
#include "base/containers/contains.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "ui/display/util/edid_parser.h"
namespace display {
namespace {
// A list of bogus sizes in mm that should be ignored.
// See crbug.com/136533. The first element maintains the minimum
// size required to be valid size.
const int kInvalidDisplaySizeList[][2] = {
{40, 30},
{50, 40},
{160, 90},
{160, 100},
};
// Used in the GetColorSpaceFromEdid function to collect data on whether the
// color space extracted from an EDID blob passed the sanity checks.
void EmitEdidColorSpaceChecksOutcomeUma(EdidColorSpaceChecksOutcome outcome) {
base::UmaHistogramEnumeration("DrmUtil.GetColorSpaceFromEdid.ChecksOutcome",
outcome);
}
// Returns true if each and all matrix values are within |epsilon| distance.
bool NearlyEqual(const skcms_Matrix3x3& lhs,
const skcms_Matrix3x3& rhs,
float epsilon) {
for (int r = 0; r < 3; r++) {
for (int c = 0; c < 3; c++) {
if (std::abs(lhs.vals[r][c] - rhs.vals[r][c]) > epsilon)
return false;
}
}
return true;
}
} // namespace
bool IsDisplaySizeValid(const gfx::Size& physical_size) {
// Ignore if the reported display is smaller than minimum size.
if (physical_size.width() <= kInvalidDisplaySizeList[0][0] ||
physical_size.height() <= kInvalidDisplaySizeList[0][1]) {
VLOG(1) << "Smaller than minimum display size";
return false;
}
for (size_t i = 1; i < base::size(kInvalidDisplaySizeList); ++i) {
const gfx::Size size(kInvalidDisplaySizeList[i][0],
kInvalidDisplaySizeList[i][1]);
if (physical_size == size) {
VLOG(1) << "Black listed display size detected:" << size.ToString();
return false;
}
}
return true;
}
int64_t GenerateDisplayID(uint16_t manufacturer_id,
uint32_t product_code_hash,
uint8_t output_index) {
return ((static_cast<int64_t>(manufacturer_id) << 40) |
(static_cast<int64_t>(product_code_hash) << 8) | output_index);
}
gfx::ColorSpace GetColorSpaceFromEdid(const display::EdidParser& edid_parser) {
const SkColorSpacePrimaries primaries = edid_parser.primaries();
// Sanity check: primaries should verify By <= Ry <= Gy, Bx <= Rx and Gx <=
// Rx, to guarantee that the R, G and B colors are each in the correct region.
if (!(primaries.fBX <= primaries.fRX && primaries.fGX <= primaries.fRX &&
primaries.fBY <= primaries.fRY && primaries.fRY <= primaries.fGY)) {
EmitEdidColorSpaceChecksOutcomeUma(
EdidColorSpaceChecksOutcome::kErrorBadCoordinates);
return gfx::ColorSpace();
}
// Sanity check: the area spawned by the primaries' triangle is too small,
// i.e. less than half the surface of the triangle spawned by sRGB/BT.709.
constexpr double kBT709PrimariesArea = 0.0954;
const float primaries_area_twice =
(primaries.fRX * primaries.fGY) + (primaries.fBX * primaries.fRY) +
(primaries.fGX * primaries.fBY) - (primaries.fBX * primaries.fGY) -
(primaries.fGX * primaries.fRY) - (primaries.fRX * primaries.fBY);
if (primaries_area_twice < kBT709PrimariesArea) {
EmitEdidColorSpaceChecksOutcomeUma(
EdidColorSpaceChecksOutcome::kErrorPrimariesAreaTooSmall);
return gfx::ColorSpace();
}
// Sanity check: https://crbug.com/809909, the blue primary coordinates should
// not be too far left/upwards of the expected location (namely [0.15, 0.06]
// for sRGB/ BT.709/ Adobe RGB/ DCI-P3, and [0.131, 0.046] for BT.2020).
constexpr float kExpectedBluePrimaryX = 0.15f;
constexpr float kBluePrimaryXDelta = 0.02f;
constexpr float kExpectedBluePrimaryY = 0.06f;
constexpr float kBluePrimaryYDelta = 0.031f;
const bool is_blue_primary_broken =
(std::abs(primaries.fBX - kExpectedBluePrimaryX) > kBluePrimaryXDelta) ||
(std::abs(primaries.fBY - kExpectedBluePrimaryY) > kBluePrimaryYDelta);
if (is_blue_primary_broken) {
EmitEdidColorSpaceChecksOutcomeUma(
EdidColorSpaceChecksOutcome::kErrorBluePrimaryIsBroken);
return gfx::ColorSpace();
}
skcms_Matrix3x3 primaries_matrix;
if (!primaries.toXYZD50(&primaries_matrix)) {
EmitEdidColorSpaceChecksOutcomeUma(
EdidColorSpaceChecksOutcome::kErrorCannotExtractToXYZD50);
return gfx::ColorSpace();
}
// Snap the primaries to those of BT.709/sRGB for performance purposes, see
// crbug.com/1073467. kPrimariesTolerance is an educated guess from various
// ChromeOS panels observations.
auto color_space_primaries = gfx::ColorSpace::PrimaryID::INVALID;
constexpr float kPrimariesTolerance = 0.025;
if (NearlyEqual(primaries_matrix, SkNamedGamut::kSRGB, kPrimariesTolerance))
color_space_primaries = gfx::ColorSpace::PrimaryID::BT709;
const double gamma = edid_parser.gamma();
if (gamma < 1.0) {
EmitEdidColorSpaceChecksOutcomeUma(
EdidColorSpaceChecksOutcome::kErrorBadGamma);
return gfx::ColorSpace();
}
EmitEdidColorSpaceChecksOutcomeUma(EdidColorSpaceChecksOutcome::kSuccess);
auto transfer_id = gfx::ColorSpace::TransferID::INVALID;
if (base::Contains(edid_parser.supported_color_primary_ids(),
gfx::ColorSpace::PrimaryID::BT2020)) {
if (base::Contains(edid_parser.supported_color_transfer_ids(),
gfx::ColorSpace::TransferID::SMPTEST2084)) {
transfer_id = gfx::ColorSpace::TransferID::SMPTEST2084;
} else if (base::Contains(edid_parser.supported_color_transfer_ids(),
gfx::ColorSpace::TransferID::ARIB_STD_B67)) {
transfer_id = gfx::ColorSpace::TransferID::ARIB_STD_B67;
}
} else if (gamma == 2.2f) {
transfer_id = gfx::ColorSpace::TransferID::GAMMA22;
} else if (gamma == 2.4f) {
transfer_id = gfx::ColorSpace::TransferID::GAMMA24;
}
// Prefer to return a name-based ColorSpace to ease subsequent calculations.
if (transfer_id != gfx::ColorSpace::TransferID::INVALID) {
if (color_space_primaries != gfx::ColorSpace::PrimaryID::INVALID)
return gfx::ColorSpace(color_space_primaries, transfer_id);
return gfx::ColorSpace::CreateCustom(primaries_matrix, transfer_id);
}
skcms_TransferFunction transfer = {gamma, 1.f, 0.f, 0.f, 0.f, 0.f, 0.f};
if (color_space_primaries == gfx::ColorSpace::PrimaryID::INVALID)
return gfx::ColorSpace::CreateCustom(primaries_matrix, transfer);
return gfx::ColorSpace(
color_space_primaries, gfx::ColorSpace::TransferID::CUSTOM,
gfx::ColorSpace::MatrixID::RGB, gfx::ColorSpace::RangeID::FULL,
/*custom_primary_matrix=*/nullptr, &transfer);
}
} // namespace display
| 40.430233 | 80 | 0.701323 | Ron423c |
2db1c8adc9af1a112f9cd8505c8dcf865e6ada29 | 3,457 | cpp | C++ | solutions/LeetCode/C++/450.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/450.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/450.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 28 ms submission
static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); return 0; }();
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
TreeNode * prev;
TreeNode * cur = root;
TreeNode * delNode;
while(cur != NULL && cur -> val != key) {
prev = cur;
if(key < cur->val) cur = cur->left;
else if(key > cur->val) cur = cur->right;
}
if(cur == NULL) return root; //Could not find key
if(cur -> right == NULL) {
//Relink
if(cur == root) {
cur = cur->left;
delete root;
return cur;
} else {
if(prev -> right == cur)
prev->right = cur->left;
else
prev->left = cur->left;
delete cur;
return root;
}
} else {
//Find next largest, assign val, delete that one
delNode = cur;
prev = cur;
cur = cur -> right;
while(cur->left != NULL) {
prev = cur;
cur = cur->left;
}
if(prev -> right == cur) {
prev -> right = cur -> right;
} else {
prev -> left = cur -> right;
}
delNode -> val = cur -> val;
delete cur;
}
return root;
}
};
__________________________________________________________________________________________________
sample 12992 kb submission
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* deleteNode(TreeNode* root, int key) {
TreeNode* superRoot = new TreeNode(0);
superRoot->left = root;
TreeNode* parent = superRoot;
TreeNode* current = root;
while (current != NULL && current->val != key){
parent = current;
if (key <= current->val){
current = current->left;
}else{
current = current->right;
}
}
// Not found
if (current==NULL) return superRoot->left;
while (current->left != NULL || current->right != NULL){
TreeNode *origin = current;
if (current->left != NULL){
parent = current;
current = current->left;
while (current->right!=NULL){
parent = current;
current = current->right;
}
}else{
parent = current;
current = current->right;
while (current->left!=NULL){
parent = current;
current = current->left;
}
}
swap(origin->val, current->val);
}
if (parent->left == current)
parent->left = NULL; else
parent->right = NULL;
delete current;
return superRoot->left;
}
};
__________________________________________________________________________________________________
| 32.009259 | 113 | 0.484813 | timxor |
2db308fb672853899abcbe30eb98a423d0cd0b59 | 821 | hpp | C++ | libs/projectile/include/sge/projectile/triangulation/traits/access_element.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/projectile/include/sge/projectile/triangulation/traits/access_element.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/projectile/include/sge/projectile/triangulation/traits/access_element.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// 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 SGE_PROJECTILE_TRIANGULATION_TRAITS_ACCESS_ELEMENT_HPP_INCLUDED
#define SGE_PROJECTILE_TRIANGULATION_TRAITS_ACCESS_ELEMENT_HPP_INCLUDED
#include <sge/projectile/triangulation/default_tag.hpp>
#include <sge/projectile/triangulation/traits/access_element_fwd.hpp>
namespace sge::projectile::triangulation::traits
{
template <typename Vertex>
struct access_element<Vertex, sge::projectile::triangulation::default_tag>
{
static typename Vertex::value_type
execute(Vertex const &_vertex, typename Vertex::size_type const _index)
{
return _vertex.get_unsafe(_index);
}
};
}
#endif
| 29.321429 | 74 | 0.783191 | cpreh |
2dbb822e03a097c3c3e06fbb7aa3635f62d91418 | 6,156 | cpp | C++ | librbr_tests/src/mdp/test_mdp.cpp | kylewray/librbr | ea3dcef7c37b4f177373ac6fec1f4c4566cf7bd8 | [
"MIT"
] | null | null | null | librbr_tests/src/mdp/test_mdp.cpp | kylewray/librbr | ea3dcef7c37b4f177373ac6fec1f4c4566cf7bd8 | [
"MIT"
] | 11 | 2015-04-02T01:32:47.000Z | 2015-04-02T01:32:47.000Z | librbr_tests/src/mdp/test_mdp.cpp | kylewray/librbr | ea3dcef7c37b4f177373ac6fec1f4c4566cf7bd8 | [
"MIT"
] | null | null | null | /**
* The MIT License (MIT)
*
* Copyright (c) 2014 Kyle Hollins Wray, University of Massachusetts
*
* 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 "../../include/perform_tests.h"
#include <iostream>
#include "../../../librbr/include/management/unified_file.h"
#include "../../../librbr/include/mdp/mdp.h"
#include "../../../librbr/include/mdp/mdp_value_iteration.h"
#include "../../../librbr/include/mdp/mdp_policy_iteration.h"
#include "../../../librbr/include/core/core_exception.h"
#include "../../../librbr/include/core/states/state_exception.h"
#include "../../../librbr/include/core/actions/action_exception.h"
#include "../../../librbr/include/core/state_transitions/state_transition_exception.h"
#include "../../../librbr/include/core/rewards/reward_exception.h"
#include "../../../librbr/include/core/policy/policy_exception.h"
int test_mdp()
{
int numSuccesses = 0;
UnifiedFile file;
std::cout << "MDP: Loading 'grid_world_finite_horizon.mdp'...";
if (!file.load("resources/mdp/grid_world_finite_horizon.mdp")) {
std::cout << " Success." << std::endl;
numSuccesses++;
} else {
std::cout << " Failure." << std::endl;
}
std::cout << "MDP: Solving 'grid_world_finite_horizon.mdp' with MDPValueIteration...";
MDP *mdp = nullptr;
MDPValueIteration vi;
PolicyMap *policyMap = nullptr;
try {
mdp = file.get_mdp();
policyMap = vi.solve(mdp);
std::cout << " Success." << std::endl;
numSuccesses++;
} catch (const CoreException &err) {
std::cout << " Failure." << std::endl;
} catch (const StateException &err) {
std::cout << " Failure." << std::endl;
} catch (const ActionException &err) {
std::cout << " Failure." << std::endl;
} catch (const StateTransitionException &err) {
std::cout << " Failure." << std::endl;
} catch (const RewardException &err) {
std::cout << " Failure." << std::endl;
} catch (const PolicyException &err) {
std::cout << " Failure." << std::endl;
}
if (policyMap != nullptr) {
policyMap->save("tmp/test_mdp_value_iteration_finite_horizon.policy_map");
delete policyMap;
}
policyMap = nullptr;
if (mdp != nullptr) {
delete mdp;
}
mdp = nullptr;
std::cout << "MDP: Loading 'grid_world_infinite_horizon.mdp'...";
if (!file.load("resources/mdp/grid_world_infinite_horizon.mdp")) {
std::cout << " Success." << std::endl;
numSuccesses++;
} else {
std::cout << " Failure." << std::endl;
}
std::cout << "MDP: Solving 'grid_world_infinite_horizon.mdp' with MDPValueIteration...";
try {
mdp = file.get_mdp();
policyMap = vi.solve(mdp);
std::cout << " Success." << std::endl;
numSuccesses++;
} catch (const CoreException &err) {
std::cout << " Failure." << std::endl;
} catch (const StateException &err) {
std::cout << " Failure." << std::endl;
} catch (const ActionException &err) {
std::cout << " Failure." << std::endl;
} catch (const StateTransitionException &err) {
std::cout << " Failure." << std::endl;
} catch (const RewardException &err) {
std::cout << " Failure." << std::endl;
} catch (const PolicyException &err) {
std::cout << " Failure." << std::endl;
}
if (policyMap != nullptr) {
policyMap->save("tmp/test_mdp_value_iteration_infinite_horizon.policy_map");
delete policyMap;
}
policyMap = nullptr;
std::cout << "MDP: Solving 'grid_world_infinite_horizon.mdp' with MDPPolicyIteration (Exact)...";
MDPPolicyIteration piExact;
try {
policyMap = piExact.solve(mdp);
std::cout << " Success." << std::endl;
numSuccesses++;
} catch (const CoreException &err) {
std::cout << " Failure." << std::endl;
} catch (const StateException &err) {
std::cout << " Failure." << std::endl;
} catch (const ActionException &err) {
std::cout << " Failure." << std::endl;
} catch (const StateTransitionException &err) {
std::cout << " Failure." << std::endl;
} catch (const RewardException &err) {
std::cout << " Failure." << std::endl;
} catch (const PolicyException &err) {
std::cout << " Failure." << std::endl;
}
if (policyMap != nullptr) {
policyMap->save("tmp/test_mdp_policy_iteration_exact_infinite_horizon.policy_map");
delete policyMap;
}
policyMap = nullptr;
std::cout << "MDP: Solving 'grid_world_infinite_horizon.mdp' with MDPPolicyIteration (Modified with k=5)...";
MDPPolicyIteration piModified(5);
try {
policyMap = piModified.solve(mdp);
std::cout << " Success." << std::endl;
numSuccesses++;
} catch (const CoreException &err) {
std::cout << " Failure." << std::endl;
} catch (const StateException &err) {
std::cout << " Failure." << std::endl;
} catch (const ActionException &err) {
std::cout << " Failure." << std::endl;
} catch (const StateTransitionException &err) {
std::cout << " Failure." << std::endl;
} catch (const RewardException &err) {
std::cout << " Failure." << std::endl;
} catch (const PolicyException &err) {
std::cout << " Failure." << std::endl;
}
if (policyMap != nullptr) {
policyMap->save("tmp/test_mdp_policy_iteration_modified_infinite_horizon.policy_map");
delete policyMap;
}
policyMap = nullptr;
delete mdp;
mdp = nullptr;
return numSuccesses;
}
| 32.919786 | 110 | 0.674789 | kylewray |
2dbcc962496b6eb0e8c389e94cc89cc51f887d8f | 2,156 | cpp | C++ | diffusion/math/Local.cpp | lanetszb/dfvm | c6154ba23c4e145fa6889c04f97b69972163f59c | [
"MIT"
] | null | null | null | diffusion/math/Local.cpp | lanetszb/dfvm | c6154ba23c4e145fa6889c04f97b69972163f59c | [
"MIT"
] | null | null | null | diffusion/math/Local.cpp | lanetszb/dfvm | c6154ba23c4e145fa6889c04f97b69972163f59c | [
"MIT"
] | null | null | null | /* MIT License
*
* Copyright (c) 2020 Aleksandr Zhuravlyov and Zakhar Lanets
*
* 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 "Local.h"
#include "funcs.h"
#include <algorithm>
Local::Local(std::shared_ptr<Props> props, std::shared_ptr<Sgrid> sgrid) :
_props(props),
_sgrid(sgrid),
_alphas(_sgrid->_cellsN, 0) {}
void Local::calcTimeSteps() {
auto time = std::get<double>(_props->_params["time_period"]);
auto timeStep = std::get<double>(_props->_params["time_step"]);
double division = time / timeStep;
double fullStepsN;
auto lastStep = std::modf(division, &fullStepsN);
_timeSteps.clear();
_timeSteps = std::vector<double>(fullStepsN, timeStep);
if (lastStep > 0)
_timeSteps.push_back(lastStep * timeStep);
}
void Local::calcAlphas(Eigen::Ref<Eigen::VectorXd> concs,
const double &timeStep) {
auto poroIni = std::get<double>(_props->_params["poro"]);
for (int i = 0; i < _alphas.size(); i++) {
auto aCoeff = calcAFunc(concs[i], poroIni);
_alphas[i] = aCoeff * _sgrid->_cellV / timeStep;
}
} | 38.5 | 81 | 0.700835 | lanetszb |
2dbcec127f31253160471c3f27a1268d0ba93aa6 | 5,696 | cpp | C++ | src/Level/Enemies/ElysiaFledglingEnemy.cpp | tizian/Cendric2 | 5b0438c73a751bcc0d63c3af839af04ab0fb21a3 | [
"MIT"
] | 279 | 2015-05-06T19:04:07.000Z | 2022-03-21T21:33:38.000Z | src/Level/Enemies/ElysiaFledglingEnemy.cpp | tizian/Cendric2 | 5b0438c73a751bcc0d63c3af839af04ab0fb21a3 | [
"MIT"
] | 222 | 2016-10-26T15:56:25.000Z | 2021-10-03T15:30:18.000Z | src/Level/Enemies/ElysiaFledglingEnemy.cpp | tizian/Cendric2 | 5b0438c73a751bcc0d63c3af839af04ab0fb21a3 | [
"MIT"
] | 49 | 2015-10-01T21:23:03.000Z | 2022-03-19T20:11:31.000Z | #include "Level/Enemies/ElysiaFledglingEnemy.h"
#include "Level/LevelMainCharacter.h"
#include "Level/MOBBehavior/MovingBehaviors/AggressiveFlyingBehavior.h"
#include "Level/MOBBehavior/MovingBehaviors/AllyFlyingBehavior.h"
#include "Level/MOBBehavior/AttackingBehaviors/AggressiveBehavior.h"
#include "Level/MOBBehavior/AttackingBehaviors/AllyBehavior.h"
#include "Registrar.h"
REGISTER_ENEMY(EnemyID::Elysia_Fledgling, ElysiaFledglingEnemy)
void ElysiaFledglingEnemy::insertDefaultLoot(std::map<std::string, int>& loot, int& gold) const {
loot.insert({ "mi_feather", rand() % 3 + 1 });
loot.insert({ "fo_rawchicken", 1 });
if (rand() % 2 == 0)
loot.insert({ "fo_egg", 1 });
}
void ElysiaFledglingEnemy::insertRespawnLoot(std::map<std::string, int>& loot, int& gold) const {
int feathers = rand() % 3;
if (feathers > 0)
loot.insert({ "mi_feather", feathers });
}
ElysiaFledglingEnemy::ElysiaFledglingEnemy(const Level* level, Screen* screen) :
LevelMovableGameObject(level),
Enemy(level, screen) {
}
void ElysiaFledglingEnemy::loadAttributes() {
m_attributes.setHealth(80);
m_attributes.resistanceFire = -10;
m_attributes.resistanceIce = 1000;
m_attributes.resistancePhysical = 200;
m_attributes.calculateAttributes();
}
void ElysiaFledglingEnemy::loadSpells() {
SpellData chopSpell = SpellData::getSpellData(SpellID::Chop);
chopSpell.activeDuration = sf::milliseconds(500);
chopSpell.cooldown = sf::seconds(1);
chopSpell.damage = 5;
chopSpell.damagePerSecond = 6;
chopSpell.duration = sf::seconds(2.f);
chopSpell.boundingBox = sf::FloatRect(10, 0, 30, 30);
chopSpell.fightingTime = sf::milliseconds(3 * 100);
chopSpell.spellOffset = sf::Vector2f(0.f, 0.f);
m_spellManager->addSpell(chopSpell);
SpellData projectile = SpellData::getSpellData(SpellID::TargetingProjectile);
projectile.cooldown = sf::seconds(5);
projectile.activeDuration = sf::seconds(10.f);
projectile.damageType = DamageType::Ice;
projectile.damage = 20;
projectile.damagePerSecond = 5;
projectile.speed = 300;
projectile.duration = sf::seconds(2.f);
projectile.strength = 1;
projectile.castingTime = sf::milliseconds(8 * 100);
projectile.fightingTime = sf::milliseconds(3 * 100);
projectile.spellOffset = sf::Vector2f(0.f, -40.f);
m_spellManager->addSpell(projectile);
m_spellManager->setCurrentSpell(0);
}
MovingBehavior* ElysiaFledglingEnemy::createMovingBehavior(bool asAlly) {
FlyingBehavior* behavior;
if (asAlly) {
behavior = new AllyFlyingBehavior(this);
}
else {
behavior = new AggressiveFlyingBehavior(this);
}
behavior->setApproachingDistance(100.f);
behavior->setMaxVelocityYDown(200.f);
behavior->setMaxVelocityYUp(100.f);
behavior->setMaxVelocityX(100.f);
return behavior;
}
AttackingBehavior* ElysiaFledglingEnemy::createAttackingBehavior(bool asAlly) {
EnemyAttackingBehavior* behavior;
if (asAlly) {
behavior = new AllyBehavior(this);
}
else {
behavior = new AggressiveBehavior(this);
}
behavior->setAggroRange(400.f);
behavior->setAttackInput(std::bind(&ElysiaFledglingEnemy::handleAttackInput, this));
return behavior;
}
void ElysiaFledglingEnemy::handleAttackInput() {
if (m_enemyState != EnemyState::Chasing) return;
if (getCurrentTarget() == nullptr) return;
if (m_enemyAttackingBehavior->distToTarget() < 50.f) {
m_spellManager->setCurrentSpell(0); // chop
m_chasingTime = sf::Time::Zero;
if (isAlly()) {
m_waitingTime = sf::seconds(1);
}
else {
m_waitingTime = sf::seconds(static_cast<float>(rand() % 8 + 3));
}
}
else {
m_spellManager->setCurrentSpell(1); // targeting projectile
}
m_spellManager->executeCurrentSpell(getCurrentTarget());
}
sf::Time ElysiaFledglingEnemy::getConfiguredWaitingTime() const {
return sf::seconds(static_cast<float>(rand() % 3 + 1));
}
sf::Time ElysiaFledglingEnemy::getConfiguredChasingTime() const {
return sf::seconds(static_cast<float>(rand() % 6 + 2));
}
void ElysiaFledglingEnemy::loadAnimation(int skinNr) {
setBoundingBox(sf::FloatRect(0.f, 0.f, 60.f, 54.f));
setSpriteOffset(sf::Vector2f(-5.f, -50.f));
int width = 70;
int height = 110;
const sf::Texture* tex = g_resourceManager->getTexture(getSpritePath());
Animation* flyingAnimation = new Animation();
flyingAnimation->setSpriteSheet(tex);
for (int i = 0; i < 4; ++i) {
flyingAnimation->addFrame(sf::IntRect(i * width, 0, width, height));
}
addAnimation(GameObjectState::Flying, flyingAnimation);
Animation* idleAnimation = new Animation();
idleAnimation->setSpriteSheet(tex);
for(int i = 0; i < 4; ++i) {
idleAnimation->addFrame(sf::IntRect(i * width, 0, width, height));
}
addAnimation(GameObjectState::Idle, idleAnimation);
Animation* fightingAnimation = new Animation();
fightingAnimation->setSpriteSheet(tex);
for (int i = 4; i < 7; ++i) {
fightingAnimation->addFrame(sf::IntRect(i * width, 0, width, height));
}
addAnimation(GameObjectState::Fighting, fightingAnimation);
Animation* castingAnimation = new Animation();
castingAnimation->setSpriteSheet(tex);
for (int i = 0; i < 8; ++i) {
castingAnimation->addFrame(sf::IntRect(i * width, height, width, height));
}
addAnimation(GameObjectState::Casting, castingAnimation);
Animation* deadAnimation = new Animation();
deadAnimation->setSpriteSheet(tex);
deadAnimation->addFrame(sf::IntRect(7 * width, 0, width, height));
addAnimation(GameObjectState::Dead, deadAnimation);
// initial values
setState(GameObjectState::Idle);
playCurrentAnimation(true);
}
std::string ElysiaFledglingEnemy::getSpritePath() const {
return "res/texture/enemies/spritesheet_enemy_elysiafledgling.png";
}
std::string ElysiaFledglingEnemy::getDeathSoundPath() const {
return "res/sound/mob/seagull_death.ogg";
}
| 31.644444 | 97 | 0.744206 | tizian |
2dc34cfc58fa45d3a274066306f22561ecf89ca8 | 700 | cc | C++ | cpp/accelerated_c++/chapter10/letter_grade.cc | zhouzhiqi/book_and_code | 3ffadd6cb721af280a00c1e1f97d509ab4b210ab | [
"Apache-2.0"
] | null | null | null | cpp/accelerated_c++/chapter10/letter_grade.cc | zhouzhiqi/book_and_code | 3ffadd6cb721af280a00c1e1f97d509ab4b210ab | [
"Apache-2.0"
] | null | null | null | cpp/accelerated_c++/chapter10/letter_grade.cc | zhouzhiqi/book_and_code | 3ffadd6cb721af280a00c1e1f97d509ab4b210ab | [
"Apache-2.0"
] | null | null | null | #include <cstddef>
#include <string>
using std::string;
string letter_grade(double grade)
{
// range posts for numeric grades
static const double numbers[] = {
97, 94, 90, 87, 84, 80, 77, 74, 70, 60, 0
};
// names for the letter grades
static const char* const letters[] = {
"A+", "A", "A-", "B+", "B", "B-", "C+", "C", "C-", "D", "F"
};
// compute the number of grades given the size of the array
// and the size of a single element
static const size_t ngrades = sizeof(numbers)/sizeof(*numbers);
// given a numeric grade, find and return the associated letter grade
for (size_t i = 0; i < ngrades; ++i) {
if (grade >= numbers[i])
return letters[i];
}
return "?\?\?";
}
| 22.580645 | 70 | 0.62 | zhouzhiqi |
2dc5379c6c43357a0652fbdb3e263471fbfac99d | 624 | cpp | C++ | pds2/vpls/lista_problematica/main.cpp | pganaclara/ufmg | 2325803427a7b4d5d150574bfd80243274cab527 | [
"MIT"
] | null | null | null | pds2/vpls/lista_problematica/main.cpp | pganaclara/ufmg | 2325803427a7b4d5d150574bfd80243274cab527 | [
"MIT"
] | null | null | null | pds2/vpls/lista_problematica/main.cpp | pganaclara/ufmg | 2325803427a7b4d5d150574bfd80243274cab527 | [
"MIT"
] | null | null | null | #include <iostream>
#include "List.hpp"
int main(){
int N, K;
std::cin >> N >> K;
List *L = new List();
for (int i = N; i >= 0; i--){
L->insert(i); //insere um a um os elementos [N, 0]
}
L->print();
std::cout << L->_size << std::endl;
for (int j = 0; j < K; j++){
L->removeFirst(); // remove os primeiros elementos k vezes
}
L->print();
std::cout << L->_size << std::endl;
for (int k = 0; k <= N; k+=2) {
L->remove(k); // começa retirando o 0 e vai de 2 em 2, tirando os pares
}
L->print();
std::cout << L->_size << std::endl;
L->clearList();
delete L;
return 0;
} | 18.352941 | 75 | 0.516026 | pganaclara |
2dc8c4e85c9b4854b8e91180134a453bb3e3cfed | 13,357 | cpp | C++ | src/Driver.cpp | mostynb/tundra | 4feb8c9309f2bdad6d3ef1ad8a522f5726b5f9c1 | [
"MIT"
] | null | null | null | src/Driver.cpp | mostynb/tundra | 4feb8c9309f2bdad6d3ef1ad8a522f5726b5f9c1 | [
"MIT"
] | null | null | null | src/Driver.cpp | mostynb/tundra | 4feb8c9309f2bdad6d3ef1ad8a522f5726b5f9c1 | [
"MIT"
] | null | null | null | #include "Driver.hpp"
#include "BinaryWriter.hpp"
#include "Buffer.hpp"
#include "BuildQueue.hpp"
#include "Common.hpp"
#include "DagData.hpp"
#include "DagGenerator.hpp"
#include "DagDerivedCompiler.hpp"
#include "FileInfo.hpp"
#include "MemAllocLinear.hpp"
#include "MemoryMappedFile.hpp"
#include "RuntimeNode.hpp"
#include "ScanData.hpp"
#include "Scanner.hpp"
#include "SortedArrayUtil.hpp"
#include "AllBuiltNodes.hpp"
#include "Stats.hpp"
#include "HashTable.hpp"
#include "Hash.hpp"
#include "Profiler.hpp"
#include "NodeResultPrinting.hpp"
#include "FileSign.hpp"
#include "PathUtil.hpp"
#include "CacheClient.hpp"
#include "LeafInputSignature.hpp"
#include "LoadFrozenData.hpp"
#include "FindNodesByName.hpp"
#include "FileSystem.hpp"
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include "stdarg.h"
TundraStats g_Stats;
static const char *s_BuildFile;
static const char *s_DagFileName;
bool LoadOrBuildDag(Driver *self, const char *dag_fn);
void DriverInitializeTundraFilePaths(DriverOptions *driverOptions)
{
s_BuildFile = "tundra.lua";
s_DagFileName = driverOptions->m_DAGFileName;
}
// Set default options.
void DriverOptionsInit(DriverOptions *self)
{
self->m_ShowHelp = false;
self->m_ShowTargets = false;
self->m_DebugMessages = false;
self->m_Verbose = false;
self->m_SpammyVerbose = false;
self->m_DisplayStats = false;
self->m_SilenceIfPossible = false;
self->m_DontReusePreviousResults = false;
self->m_DebugSigning = false;
self->m_ContinueOnFailure = false;
self->m_StandardInputCanary = false;
self->m_JustPrintLeafInputSignature = nullptr;
self->m_IdentificationColor = 0;
self->m_ThreadCount = GetCpuCount();
self->m_WorkingDir = nullptr;
self->m_DAGFileName = ".tundra2.dag";
self->m_ProfileOutput = nullptr;
self->m_IncludesOutput = nullptr;
self->m_VisualMaxNodes = 1000;
self->m_DagFileNameJson = nullptr;
#if defined(TUNDRA_WIN32)
self->m_RunUnprotected = true;
#endif
self->m_Inspect = false;
}
void DriverShowTargets(Driver *self)
{
const Frozen::Dag *dag = self->m_DagData;
printf("\nNamed nodes and aliases:\n");
printf("----------------------------------------------------------------\n");
int32_t count = dag->m_NamedNodes.GetCount();
const char **temp = (const char **)alloca(sizeof(const char *) * count);
for (int i = 0; i < count; ++i)
{
temp[i] = dag->m_NamedNodes[i].m_Name.Get();
}
std::sort(temp, temp + count, [](const char *a, const char *b) { return strcmp(a, b) < 0; });
for (int i = 0; i < count; ++i)
{
printf(" - %s\n", temp[i]);
}
}
void DriverReportStartup(Driver *self, const char **targets, int target_count)
{
MemAllocLinearScope allocScope(&self->m_Allocator);
JsonWriter msg;
JsonWriteInit(&msg, &self->m_Allocator);
JsonWriteStartObject(&msg);
JsonWriteKeyName(&msg, "msg");
JsonWriteValueString(&msg, "init");
JsonWriteKeyName(&msg, "dagFile");
JsonWriteValueString(&msg, self->m_Options.m_DAGFileName);
JsonWriteKeyName(&msg, "targets");
JsonWriteStartArray(&msg);
for (int i = 0; i < target_count; ++i)
JsonWriteValueString(&msg, targets[i]);
JsonWriteEndArray(&msg);
JsonWriteEndObject(&msg);
LogStructured(&msg);
}
bool DriverInitData(Driver *self)
{
if (!LoadOrBuildDag(self, s_DagFileName))
return false;
ProfilerScope prof_scope("DriverInitData", 0);
// do not produce/overwrite structured log output or state file,
// if we're only reporting something and not doing an actual build
if (self->m_Options.m_IncludesOutput == nullptr && !self->m_Options.m_ShowHelp && !self->m_Options.m_ShowTargets)
{
SetStructuredLogFileName(self->m_DagData->m_StructuredLogFileName);
const char* stateFile = self->m_DagData->m_StateFileName.Get();
if (GetFileInfo(stateFile).Exists() && !RenameFile(stateFile, self->m_DagData->m_StateFileNameMapped.Get()))
Croak("Unable to rename state file '%s' => '%s'", stateFile, self->m_DagData->m_StateFileNameMapped.Get());
LoadFrozenData<Frozen::AllBuiltNodes>(self->m_DagData->m_StateFileNameMapped, &self->m_StateFile, &self->m_AllBuiltNodes);
}
else
{
LoadFrozenData<Frozen::AllBuiltNodes>(self->m_DagData->m_StateFileName, &self->m_StateFile, &self->m_AllBuiltNodes);
}
DigestCacheInit(&self->m_DigestCache, MB(128), self->m_DagData->m_DigestCacheFileName);
LoadFrozenData<Frozen::ScanData>(self->m_DagData->m_ScanCacheFileName, &self->m_ScanFile, &self->m_ScanData);
ScanCacheSetCache(&self->m_ScanCache, self->m_ScanData);
return true;
}
void DriverSelectNodes(const Frozen::Dag *dag, const char **targets, int target_count, Buffer<int32_t> *out_nodes, MemAllocHeap *heap)
{
if (target_count > 0)
{
FindNodesByName(
dag,
out_nodes, heap,
targets, target_count, dag->m_NamedNodes);
}
else
{
BufferAppend(out_nodes, heap, dag->m_DefaultNodes.GetArray(), dag->m_DefaultNodes.GetCount());
}
std::sort(out_nodes->begin(), out_nodes->end());
int32_t *new_end = std::unique(out_nodes->begin(), out_nodes->end());
out_nodes->m_Size = new_end - out_nodes->begin();
Log(kDebug, "Node selection finished with %d nodes to build", (int)out_nodes->m_Size);
}
bool DriverPrepareNodes(Driver *self)
{
ProfilerScope prof_scope("Tundra PrepareNodes", 0);
const Frozen::Dag *dag = self->m_DagData;
const Frozen::DagNode *dag_nodes = dag->m_DagNodes;
const HashDigest *dag_node_guids = dag->m_NodeGuids;
// Allocate space for nodes
RuntimeNode *out_nodes = BufferAllocZero(&self->m_RuntimeNodes, &self->m_Heap, dag->m_NodeCount);
int node_count = dag->m_NodeCount;
// Initialize node state
for (int i = 0; i < node_count; ++i)
{
const Frozen::DagNode *dag_node = dag_nodes + i;
out_nodes[i].m_DagNode = dag_node;
out_nodes[i].m_DagNodeIndex = i;
#if ENABLED(CHECKED_BUILD)
out_nodes[i].m_DebugAnnotation = dag_node->m_Annotation.Get();
#endif
}
// Find frozen node state from previous build, if present.
if (const Frozen::AllBuiltNodes *all_built_nodes = self->m_AllBuiltNodes)
{
const Frozen::BuiltNode *built_nodes = all_built_nodes->m_BuiltNodes;
const HashDigest *state_guids = all_built_nodes->m_NodeGuids;
const int state_guid_count = all_built_nodes->m_NodeCount;
for (int i = 0; i < node_count; ++i)
{
const HashDigest *src_guid = dag_node_guids + i;
if (const HashDigest *old_guid = BinarySearch(state_guids, state_guid_count, *src_guid))
{
int state_index = int(old_guid - state_guids);
out_nodes[i].m_BuiltNode = built_nodes + state_index;
}
}
}
return true;
}
bool DriverInit(Driver *self, const DriverOptions *options)
{
memset(self, 0, sizeof(Driver));
HeapInit(&self->m_Heap);
LinearAllocInit(&self->m_Allocator, &self->m_Heap, MB(64), "Driver Linear Allocator");
LinearAllocSetOwner(&self->m_Allocator, ThreadCurrent());
InitNodeResultPrinting(options);
MmapFileInit(&self->m_DagFile);
MmapFileInit(&self->m_StateFile);
MmapFileInit(&self->m_ScanFile);
self->m_DagData = nullptr;
self->m_AllBuiltNodes = nullptr;
self->m_ScanData = nullptr;
BufferInit(&self->m_RuntimeNodes);
self->m_Options = *options;
// This linear allocator is only accessed when the state cache is locked.
LinearAllocInit(&self->m_ScanCacheAllocator, &self->m_Heap, MB(64), "scan cache");
ScanCacheInit(&self->m_ScanCache, &self->m_Heap, &self->m_ScanCacheAllocator);
// This linear allocator is only accessed when the state cache is locked.
LinearAllocInit(&self->m_StatCacheAllocator, &self->m_Heap, MB(64), "stat cache");
StatCacheInit(&self->m_StatCache, &self->m_StatCacheAllocator, &self->m_Heap);
FileSystemInit(s_DagFileName);
return true;
}
void DriverDestroy(Driver *self)
{
FileSystemDestroy();
DigestCacheDestroy(&self->m_DigestCache);
StatCacheDestroy(&self->m_StatCache);
ScanCacheDestroy(&self->m_ScanCache);
for (auto &node: self->m_RuntimeNodes)
{
if (node.m_CurrentLeafInputSignature != nullptr)
DestroyLeafInputSignatureData(&self->m_Heap, node.m_CurrentLeafInputSignature);
if (HashSetIsInitialized(&node.m_ImplicitInputs))
HashSetDestroy(&node.m_ImplicitInputs);
if (node.m_DynamicallyDiscoveredOutputFiles != nullptr)
{
node.m_DynamicallyDiscoveredOutputFiles->Destroy();
HeapFree(&self->m_Heap, node.m_DynamicallyDiscoveredOutputFiles);
}
}
BufferDestroy(&self->m_RuntimeNodes, &self->m_Heap);
MmapFileDestroy(&self->m_ScanFile);
MmapFileDestroy(&self->m_StateFile);
MmapFileDestroy(&self->m_DagFile);
LinearAllocDestroy(&self->m_ScanCacheAllocator);
LinearAllocDestroy(&self->m_StatCacheAllocator);
LinearAllocDestroy(&self->m_Allocator, true);
HeapDestroy(&self->m_Heap);
}
BuildResult::Enum DriverBuild(Driver *self, int* out_finished_node_count, char* out_frontend_rerun_reason, const char** argv, int argc)
{
const Frozen::Dag *dag = self->m_DagData;
// Initialize build queue
Mutex debug_signing_mutex;
BuildQueueConfig queue_config;
queue_config.m_DriverOptions = &self->m_Options;
queue_config.m_Flags = 0;
queue_config.m_Heap = &self->m_Heap;
queue_config.m_LinearAllocator = &self->m_Allocator;
queue_config.m_Dag = self->m_DagData;
queue_config.m_DagNodes = self->m_DagData->m_DagNodes;
queue_config.m_DagDerived = self->m_DagDerivedData;
queue_config.m_ScanCache = &self->m_ScanCache;
queue_config.m_StatCache = &self->m_StatCache;
queue_config.m_DigestCache = &self->m_DigestCache;
queue_config.m_ShaDigestExtensionCount = dag->m_ShaExtensionHashes.GetCount();
queue_config.m_ShaDigestExtensions = dag->m_ShaExtensionHashes.GetArray();
queue_config.m_SharedResources = dag->m_SharedResources.GetArray();
queue_config.m_SharedResourcesCount = dag->m_SharedResources.GetCount();
BufferInit(&queue_config.m_RequestedNodes);
GetCachingBehaviourSettingsFromEnvironment(&queue_config.m_AttemptCacheReads, &queue_config.m_AttemptCacheWrites);
DagRuntimeDataInit(&queue_config.m_DagRuntimeData, self->m_DagData, &self->m_Heap);
if (self->m_Options.m_Verbose)
{
queue_config.m_Flags |= BuildQueueConfig::kFlagEchoCommandLines;
}
if (self->m_Options.m_DebugSigning)
{
MutexInit(&debug_signing_mutex);
queue_config.m_FileSigningLogMutex = &debug_signing_mutex;
queue_config.m_FileSigningLog = fopen("signing-debug.txt", "w");
}
else
{
queue_config.m_FileSigningLogMutex = nullptr;
queue_config.m_FileSigningLog = nullptr;
}
BuildResult::Enum build_result = BuildResult::kOk;
// Prepare list of nodes to build/clean/rebuild
if (!DriverPrepareNodes(self))
{
Log(kError, "couldn't set up list of targets to build");
build_result = BuildResult::kBuildError;
goto leave;
}
BuildQueue build_queue;
BuildQueueInit(&build_queue, &queue_config,(const char**)argv, argc);
build_queue.m_Config.m_RuntimeNodes = self->m_RuntimeNodes.m_Storage;
build_queue.m_Config.m_TotalRuntimeNodeCount = (int)self->m_RuntimeNodes.m_Size;
if (self->m_Options.m_JustPrintLeafInputSignature)
{
PrintLeafInputSignature(&build_queue, self->m_Options.m_JustPrintLeafInputSignature);
goto leave;
}
build_result = BuildQueueBuild(&build_queue, &self->m_Allocator);
if (self->m_Options.m_DebugSigning)
{
fclose((FILE *)queue_config.m_FileSigningLog);
MutexDestroy(&debug_signing_mutex);
}
if (build_result == BuildResult::kRequireFrontendRerun)
{
BuildQueueGetFrontendRerunReason(&build_queue, out_frontend_rerun_reason);
}
*out_finished_node_count = build_queue.m_FinishedNodeCount;
leave:
// Shut down build queue
BuildQueueDestroy(&build_queue);
DagRuntimeDataDestroy(&queue_config.m_DagRuntimeData);
return build_result;
}
// Save scan cache
bool DriverSaveScanCache(Driver *self)
{
ScanCache *scan_cache = &self->m_ScanCache;
if (!ScanCacheDirty(scan_cache))
return true;
// This will be invalidated.
self->m_ScanData = nullptr;
bool success = ScanCacheSave(scan_cache, self->m_DagData->m_ScanCacheFileNameTmp, &self->m_Heap);
// Unmap the file so we can overwrite it (on Windows.)
MmapFileDestroy(&self->m_ScanFile);
if (success)
{
success = RenameFile(self->m_DagData->m_ScanCacheFileNameTmp, self->m_DagData->m_ScanCacheFileName);
}
else
{
remove(self->m_DagData->m_ScanCacheFileNameTmp);
}
return success;
}
// Save digest cache
bool DriverSaveDigestCache(Driver *self)
{
// This will be invalidated.
return DigestCacheSave(&self->m_DigestCache, &self->m_Heap, self->m_DagData->m_DigestCacheFileName, self->m_DagData->m_DigestCacheFileNameTmp);
}
| 31.428235 | 147 | 0.69604 | mostynb |
2dcad7a307eb3c0502ecaf364023a49632193515 | 380 | cpp | C++ | audio.cpp | ervaibhavkumar/QtFrogger | 3f7d6e55bd153edf400bdd8bb9961f34bb32fb4d | [
"CC0-1.0"
] | null | null | null | audio.cpp | ervaibhavkumar/QtFrogger | 3f7d6e55bd153edf400bdd8bb9961f34bb32fb4d | [
"CC0-1.0"
] | null | null | null | audio.cpp | ervaibhavkumar/QtFrogger | 3f7d6e55bd153edf400bdd8bb9961f34bb32fb4d | [
"CC0-1.0"
] | null | null | null | #include "audio.h"
#include <QMediaPlayer>
namespace Audio {
void playSound(QString type) {
QMediaPlayer *media = new QMediaPlayer();
if (type == "die") {
media->setMedia(QUrl("qrc:/audio/die.mp3"));
}
else {
Q_ASSERT(type == "success");
media->setMedia(QUrl("qrc:/audio/success.mp3"));
}
media->play();
}
}
| 19 | 57 | 0.55 | ervaibhavkumar |
2dcafe851ec47db261d0aa8074237a2c73494f54 | 6,872 | cc | C++ | storage/browser/test/mock_quota_client.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | storage/browser/test/mock_quota_client.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | storage/browser/test/mock_quota_client.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // 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 "storage/browser/test/mock_quota_client.h"
#include <memory>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/location.h"
#include "base/memory/singleton.h"
#include "base/task/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "storage/browser/quota/quota_client_type.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "url/origin.h"
namespace storage {
MockQuotaClient::MockQuotaClient(
scoped_refptr<QuotaManagerProxy> quota_manager_proxy,
base::span<const MockStorageKeyData> mock_data,
QuotaClientType client_type)
: quota_manager_proxy_(std::move(quota_manager_proxy)),
client_type_(client_type) {
for (const MockStorageKeyData& mock_storage_key_data : mock_data) {
storage_key_data_[{blink::StorageKey::CreateFromStringForTesting(
mock_storage_key_data.origin),
mock_storage_key_data.type}] =
mock_storage_key_data.usage;
}
}
MockQuotaClient::~MockQuotaClient() = default;
void MockQuotaClient::AddStorageKeyAndNotify(
const blink::StorageKey& storage_key,
blink::mojom::StorageType storage_type,
int64_t size) {
DCHECK(storage_key_data_.find({storage_key, storage_type}) ==
storage_key_data_.end());
DCHECK_GE(size, 0);
storage_key_data_[{storage_key, storage_type}] = size;
quota_manager_proxy_->NotifyStorageModified(
client_type_, storage_key, storage_type, size, IncrementMockTime());
}
void MockQuotaClient::ModifyStorageKeyAndNotify(
const blink::StorageKey& storage_key,
blink::mojom::StorageType storage_type,
int64_t delta) {
auto it = storage_key_data_.find({storage_key, storage_type});
DCHECK(it != storage_key_data_.end());
it->second += delta;
DCHECK_GE(it->second, 0);
// TODO(tzik): Check quota to prevent usage exceed
quota_manager_proxy_->NotifyStorageModified(
client_type_, storage_key, storage_type, delta, IncrementMockTime());
}
void MockQuotaClient::TouchAllStorageKeysAndNotify() {
for (const auto& storage_key_type : storage_key_data_) {
quota_manager_proxy_->NotifyStorageModified(
client_type_, storage_key_type.first.first,
storage_key_type.first.second, 0, IncrementMockTime());
}
}
void MockQuotaClient::AddStorageKeyToErrorSet(
const blink::StorageKey& storage_key,
blink::mojom::StorageType type) {
error_storage_keys_.insert(std::make_pair(storage_key, type));
}
base::Time MockQuotaClient::IncrementMockTime() {
++mock_time_counter_;
return base::Time::FromDoubleT(mock_time_counter_ * 10.0);
}
void MockQuotaClient::GetStorageKeyUsage(const blink::StorageKey& storage_key,
blink::mojom::StorageType type,
GetStorageKeyUsageCallback callback) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&MockQuotaClient::RunGetStorageKeyUsage,
weak_factory_.GetWeakPtr(), storage_key, type,
std::move(callback)));
}
void MockQuotaClient::GetStorageKeysForType(
blink::mojom::StorageType type,
GetStorageKeysForTypeCallback callback) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(&MockQuotaClient::RunGetStorageKeysForType,
weak_factory_.GetWeakPtr(), type, std::move(callback)));
}
void MockQuotaClient::GetStorageKeysForHost(
blink::mojom::StorageType type,
const std::string& host,
GetStorageKeysForHostCallback callback) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&MockQuotaClient::RunGetStorageKeysForHost,
weak_factory_.GetWeakPtr(), type, host,
std::move(callback)));
}
void MockQuotaClient::DeleteStorageKeyData(
const blink::StorageKey& storage_key,
blink::mojom::StorageType type,
DeleteStorageKeyDataCallback callback) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&MockQuotaClient::RunDeleteStorageKeyData,
weak_factory_.GetWeakPtr(), storage_key, type,
std::move(callback)));
}
void MockQuotaClient::PerformStorageCleanup(
blink::mojom::StorageType type,
PerformStorageCleanupCallback callback) {
std::move(callback).Run();
}
void MockQuotaClient::RunGetStorageKeyUsage(
const blink::StorageKey& storage_key,
blink::mojom::StorageType type,
GetStorageKeyUsageCallback callback) {
auto it = storage_key_data_.find(std::make_pair(storage_key, type));
if (it == storage_key_data_.end()) {
std::move(callback).Run(0);
} else {
std::move(callback).Run(it->second);
}
}
void MockQuotaClient::RunGetStorageKeysForType(
blink::mojom::StorageType type,
GetStorageKeysForTypeCallback callback) {
std::vector<blink::StorageKey> storage_keys;
for (const auto& storage_key_type_usage : storage_key_data_) {
if (type == storage_key_type_usage.first.second)
storage_keys.push_back(storage_key_type_usage.first.first);
}
std::move(callback).Run(std::move(storage_keys));
}
void MockQuotaClient::RunGetStorageKeysForHost(
blink::mojom::StorageType type,
const std::string& host,
GetStorageKeysForHostCallback callback) {
std::vector<blink::StorageKey> storage_keys;
for (const auto& storage_key_type_usage : storage_key_data_) {
if (type == storage_key_type_usage.first.second &&
host == storage_key_type_usage.first.first.origin().host()) {
storage_keys.push_back(storage_key_type_usage.first.first);
}
}
std::move(callback).Run(std::move(storage_keys));
}
void MockQuotaClient::RunDeleteStorageKeyData(
const blink::StorageKey& storage_key,
blink::mojom::StorageType storage_type,
DeleteStorageKeyDataCallback callback) {
auto error_it =
error_storage_keys_.find(std::make_pair(storage_key, storage_type));
if (error_it != error_storage_keys_.end()) {
std::move(callback).Run(
blink::mojom::QuotaStatusCode::kErrorInvalidModification);
return;
}
auto it = storage_key_data_.find(std::make_pair(storage_key, storage_type));
if (it != storage_key_data_.end()) {
int64_t delta = it->second;
quota_manager_proxy_->NotifyStorageModified(
client_type_, blink::StorageKey(storage_key), storage_type, -delta,
base::Time::Now());
storage_key_data_.erase(it);
}
std::move(callback).Run(blink::mojom::QuotaStatusCode::kOk);
}
} // namespace storage
| 36.168421 | 79 | 0.715367 | zealoussnow |
2dcbb809c0c13f7f2bf3af6a3dcc69f39feed4d1 | 1,387 | cpp | C++ | IPSC2014/C.cpp | CodingYue/acm-icpc | 667596efae998f5480819870714c37e9af0740eb | [
"Unlicense"
] | 1 | 2015-11-03T09:31:07.000Z | 2015-11-03T09:31:07.000Z | IPSC2014/C.cpp | CodingYue/acm-icpc | 667596efae998f5480819870714c37e9af0740eb | [
"Unlicense"
] | null | null | null | IPSC2014/C.cpp | CodingYue/acm-icpc | 667596efae998f5480819870714c37e9af0740eb | [
"Unlicense"
] | null | null | null | // File Name: C.cpp
// Author: YangYue
// Created Time: Sun Jun 15 19:16:28 2014
//headers
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <ctime>
#include <string>
#include <queue>
#include <set>
#include <map>
#include <iostream>
#include <vector>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<double,double> PDD;
typedef pair<LL, LL>PLL;
typedef pair<LL,int>PLI;
#define lch(n) ((n<<1))
#define rch(n) ((n<<1)+1)
#define lowbit(i) (i&-i)
#define sqr(x) ((x)*(x))
#define fi first
#define se second
#define MP make_pair
#define PB push_back
const int MaxN = 100005;
const double eps = 1e-8;
const double DINF = 1e100;
const int INF = 1000000006;
const LL LINF = 1000000000000000005ll;
int n;
int a[MaxN];
int main()
{
freopen("in","r",stdin);
int cases; scanf("%d", &cases);
while (cases--) {
set<int> cnt;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", a + i);
}
vector<int> res;
/*
for (int i = 0; i < n; ++i) printf("%d ", cnt[a[i]]);
puts("");
*/
for (int i = 0; i < n; ++i) {
if (!cnt.count(a[i])) {
cnt.insert(a[i]);
res.push_back(a[i]);
}
}
for (int i = 0; i < res.size(); ++i)
printf("%d%c", res[i], i == res.size() - 1 ? '\n' : ' ');
}
return 0;
}
// hehe ~
| 17.782051 | 60 | 0.596972 | CodingYue |
2dcc39ddcbf74c75fc4be9bda0f4b577eee7e6ae | 1,535 | cpp | C++ | UVA/UVA297.cpp | avillega/CompetitiveProgramming | f12c1a07417f8fc154ac5297889ca756b49f0f35 | [
"Apache-2.0"
] | null | null | null | UVA/UVA297.cpp | avillega/CompetitiveProgramming | f12c1a07417f8fc154ac5297889ca756b49f0f35 | [
"Apache-2.0"
] | null | null | null | UVA/UVA297.cpp | avillega/CompetitiveProgramming | f12c1a07417f8fc154ac5297889ca756b49f0f35 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);
#define f(i, s, n) for(int i = s; i < n ; i++)
typedef vector< vector<bool> > picture; //false is e and true is f
void create(string &a, picture &pic, int iniF, int iniC, int finF, int finC, int &index){
if(a[index] == 'p'){
index++;
create(a, pic, iniF, (iniC+finC)/2, (iniF+finF)/2, finC, index);
create(a, pic, iniF, iniC, (iniF+finF)/2, (iniC+finC)/2, index );
create(a, pic,(iniF+finF)/2 ,iniC, finF, (iniC+finC)/2, index);
create(a, pic, (iniF+finF)/2, (iniC+finC)/2 , finF, finC, index);
return;
}else if(a[index]=='e'){
index++;
}else{
index++;
f(i, iniF, finF){
f(j, iniC, finC){
pic[i][j]=true;
}
}
return;
}
}
int main(){_
string a, b;
int T, blacks, index;
cin >> T;
while(T--){
cin >> a;
cin >> b;
blacks = 0;
index = 0;
picture pic1(32, vector<bool>(32, false)), pic2(32, vector<bool>(32, false));
create(a, pic1, 0,0, 32,32, index);
index = 0;
create(b, pic2, 0,0, 32,32, index);
f(i, 0, 32){
f(j, 0, 32){
if(pic1[i][j] || pic2[i][j]) blacks++;
}
}
cout << "There are " << blacks << " black pixels.\n";
}
return 0;
} | 27.410714 | 90 | 0.448208 | avillega |
2dcdfaabd785c1c93e398ae8d4d63ebf08131cb4 | 1,147 | cpp | C++ | src/ofp/mpexperimenter.cpp | byllyfish/oftr | ac1e4ef09388376ea6fa7b460b6abe2ab3471624 | [
"MIT"
] | 1 | 2019-06-14T13:57:28.000Z | 2019-06-14T13:57:28.000Z | src/ofp/mpexperimenter.cpp | byllyfish/oftr | ac1e4ef09388376ea6fa7b460b6abe2ab3471624 | [
"MIT"
] | 20 | 2017-02-20T04:49:10.000Z | 2019-07-09T05:32:54.000Z | src/ofp/mpexperimenter.cpp | byllyfish/oftr | ac1e4ef09388376ea6fa7b460b6abe2ab3471624 | [
"MIT"
] | 1 | 2019-07-16T00:21:42.000Z | 2019-07-16T00:21:42.000Z | // Copyright (c) 2015-2018 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#include "ofp/mpexperimenter.h"
#include "ofp/multipartrequest.h"
#include "ofp/writable.h"
using namespace ofp;
const MPExperimenter *MPExperimenter::cast(const MultipartRequest *req) {
return req->body_cast<MPExperimenter>();
}
ByteRange MPExperimenter::expData() const {
// N.B. obtain length of multipart section from MultipartRequest header.
// (Request and Reply both have same format.)
const MultipartRequest *req = MultipartRequest::msg_cast(this);
assert(req);
assert(req->requestBodySize() >= sizeof(MPExperimenter));
return SafeByteRange(this, req->requestBodySize(), sizeof(MPExperimenter));
}
bool MPExperimenter::validateInput(Validation *context) const {
if (context->lengthRemaining() < sizeof(MPExperimenter)) {
context->lengthRemainingIsInvalid(BytePtr(this), sizeof(MPExperimenter));
return false;
}
return true;
}
void MPExperimenterBuilder::write(Writable *channel) {
channel->write(&msg_, sizeof(msg_));
channel->write(data_.data(), data_.size());
channel->flush();
}
| 30.184211 | 77 | 0.741064 | byllyfish |
2dd438bd4ac615f2f06e4a3e6d76d8da5f358021 | 14,897 | cpp | C++ | source/lunatic/particle.cpp | Hypexion/HamSandwich | e5adb6b45d822cbef1be1a52d0ce51513dc24bc8 | [
"MIT"
] | 24 | 2019-05-12T12:03:21.000Z | 2022-03-30T01:05:46.000Z | source/lunatic/particle.cpp | Hypexion/HamSandwich | e5adb6b45d822cbef1be1a52d0ce51513dc24bc8 | [
"MIT"
] | 6 | 2019-05-12T11:54:54.000Z | 2022-02-26T11:47:20.000Z | source/lunatic/particle.cpp | Hypexion/HamSandwich | e5adb6b45d822cbef1be1a52d0ce51513dc24bc8 | [
"MIT"
] | 12 | 2019-05-12T13:48:57.000Z | 2022-02-25T15:25:24.000Z | #include "particle.h"
#include "bullet.h"
#include "monster.h"
Particle **particleList;
int maxParticles;
static int snowCount = 0; // explicit int
Particle::Particle(void)
{
this->life = 0;
}
Particle::~Particle(void)
{
}
void Particle::Go(byte type, int x, int y, int z, byte angle, byte force)
{
byte fforce;
if (force == 0)
return;
this->type = type;
size = 2;
fforce = force / 4;
if (fforce == 0)
fforce = 1;
this->x = x + MGL_randoml(32 << FIXSHIFT)-(16 << FIXSHIFT);
this->y = y + MGL_randoml(32 << FIXSHIFT)-(16 << FIXSHIFT);
this->z = z;
this->dx = Cosine(angle) * MGL_random(fforce);
this->dy = Sine(angle) * MGL_random(fforce);
this->dz = MGL_random(fforce * 2) << FIXSHIFT;
this->life = MGL_random(force) + 10;
}
void Particle::GoLightning(int x, int y, int x2, int y2)
{
this->type = PART_LIGHTNING;
this->x = x;
this->y = y;
this->dx = x2;
this->dy = y2;
this->life = 4;
this->color = 64;
this->size = (abs((x2 - x) >> FIXSHIFT) + abs((y2 - y) >> FIXSHIFT)) / 8;
}
void Particle::GoRandom(byte type, int x, int y, int z, byte force)
{
this->type = type;
size = 2;
if (force == 0)
return;
this->x = x + MGL_randoml(32 << FIXSHIFT)-(16 << FIXSHIFT);
this->y = y + MGL_randoml(32 << FIXSHIFT)-(16 << FIXSHIFT);
this->z = z;
this->dx = (MGL_random(force) - force / 2) << FIXSHIFT;
this->dy = (MGL_random(force) - force / 2) << FIXSHIFT;
this->dz = MGL_random(force * 2) << FIXSHIFT;
this->life = MGL_random(force) + 20;
}
void Particle::Update(Map *map)
{
byte mapx, mapy;
byte v;
byte c1;
char brt;
if (life > 0)
{
if (type != PART_LIGHTNING)
{
dz -= FIXAMT;
x += dx;
y += dy;
z += dz;
if (z < 0)
{
z = 0;
dz = -dz / 2;
}
}
life--;
switch (type) {
case PART_COUNTESS:
dz += FIXAMT; // no gravity
break;
case PART_SMOKE:
dz += FIXAMT; // no gravity
z += FIXAMT;
size = (6 - life / 8);
dx += MGL_random(65535) - FIXAMT / 2;
dy += MGL_random(65535) - FIXAMT / 2;
Dampen(&dx, FIXAMT / 8);
Dampen(&dy, FIXAMT / 8);
break;
case PART_STINKY:
dz += FIXAMT; // no gravity
z += FIXAMT + FIXAMT / 2;
size = ((life / 2)&3);
if (size == 3)
size = 1;
dx += MGL_random(65535) - FIXAMT / 2;
dy += MGL_random(65535) - FIXAMT / 2;
Dampen(&dx, FIXAMT / 8);
Dampen(&dy, FIXAMT / 8);
break;
case PART_BOOM:
dz += FIXAMT;
z += FIXAMT;
size = 7 - life;
break;
case PART_HAMMER:
v = life;
if (v > 31 - 8)
v = 31 - 8;
color = 128 + v;
if (life > 20)
size = 2;
else if (life < 10)
size = 0;
else
size = 1;
break;
case PART_GLASS:
if (life > 20)
size = 2;
else if (life < 10)
size = 0;
else
size = 1;
break;
case PART_DIRT:
v = life;
if (v > 31 - 8)
v = 31 - 8;
color = 64 + v;
if (life > 20)
size = 2;
else if (life < 10)
size = 0;
else
size = 1;
break;
case PART_SNOW2:
v = life * 2;
if (v > 31)
v = 31;
if (v < 31 - 16)
v = 31 - 16;
color = v;
if (life > 20)
size = 2;
else if (life < 10)
size = 0;
else
size = 1;
break;
case PART_WATER:
v = life;
if (v > 31)
v = 31;
if (v < 8)
v = 8;
color = 96 + v;
if (life > 20)
size = 2;
else if (life < 10)
size = 0;
else
size = 1;
break;
case PART_SLIME:
v = life;
if (v > 31 - 8)
v = 31 - 8;
color = 32 + 4 + v;
if (life > 10)
size = 2;
else if (life < 5)
size = 0;
else
size = 1;
break;
case PART_SNOW:
dx += MGL_random(65535) - FIXAMT / 2;
dy += MGL_random(65535) - FIXAMT / 2;
Dampen(&dx, FIXAMT / 8);
Dampen(&dy, FIXAMT / 8);
dz += FIXAMT - 256; // not as much gravity as other things
color = 31;
if (z == 0)
{
dx = 0;
dy = 0;
dz = 0;
if (life < 50)
size = 1;
if (life < 25)
size = 0;
color = life / 2;
if (color < 26)
color = 26;
if (color > 31)
color = 31;
snowCount++;
}
else
life++; // can't die while airborne
break;
case PART_LIGHTNING:
// get dimmer with each frame
color /= 2;
break;
}
if (x < 0 || y < 0 || x >= ((map->width * TILE_WIDTH) << FIXSHIFT) || y >= ((map->height * TILE_HEIGHT) << FIXSHIFT))
{
life = 0;
return;
}
if (type == PART_SMOKE || type == PART_BOOM || type == PART_STINKY)
{
mapx = (x / TILE_WIDTH) >> FIXSHIFT;
mapy = (y / TILE_HEIGHT) >> FIXSHIFT;
color = 64 + map->map[mapx + mapy * map->width].templight;
}
else if (type == PART_LIGHTNING || type == PART_GLASS)
{
// nothing to do
}
else
{
mapx = (x / TILE_WIDTH) >> FIXSHIFT;
mapy = (y / TILE_HEIGHT) >> FIXSHIFT;
// brighten it appropriately
brt = map->map[mapx + mapy * map->width].templight;
c1 = (color & (~31)); // c1 is the color range
color += brt;
if (color > c1 + 31 || color < c1)
{
if (brt > 0)
color = c1 + 31;
else
color = c1;
}
}
}
}
bool Particle::Alive(void)
{
return (life > 0);
}
// --------------------------------------------------------------------------
void InitParticles(int max)
{
int i;
maxParticles = max;
particleList = (Particle **) malloc(sizeof (Particle *) * maxParticles);
for (i = 0; i < maxParticles; i++)
particleList[i] = new Particle();
}
void ExitParticles(void)
{
int i;
for (i = 0; i < maxParticles; i++)
delete particleList[i];
free(particleList);
}
void UpdateParticles(Map *map)
{
int i;
snowCount = 0;
for (i = 0; i < maxParticles; i++)
particleList[i]->Update(map);
}
void RenderParticle(int x, int y, byte *scrn, byte color, byte size)
{
byte c1, c2;
if (x < 0 || x > 639 || y < 0 || y > 479)
return;
switch (size) {
case 2: // big particle
if (x < 2 || x > 637 || y < 2 || y > 477)
return;
if ((color & 31) > 1)
c1 = color - 2; // only do this if subtracting 2 keeps it in the same color group
else
c1 = color;
if ((c1 & 31) > 1)
c2 = c1 - 2; // only do this if subtracting 4 keeps it in the same color group
else
c2 = c1;
scrn += (x + (y - 2)*640);
*scrn = c2;
scrn += 639;
*scrn++ = c1;
*scrn++ = color;
*scrn = c1;
scrn += 637;
*scrn++ = c2;
*scrn++ = c1;
*scrn++ = color;
*scrn++ = c1;
*scrn = c2;
scrn += 637;
*scrn++ = c1;
*scrn++ = color;
*scrn = c1;
*(scrn + 639) = c2;
break;
case 1: // normal particle
if (x < 1 || x > 638 || y < 1 || y > 478)
return;
if (color & 31)
c1 = color - 1; // only do this if subtracting 1 keeps it in the same color group
else
c1 = color;
scrn += (x + (y - 1)*640);
*scrn = c1;
scrn += 639;
*scrn++ = c1;
*scrn++ = color;
*scrn = c1;
scrn += 639;
*scrn = c1;
break;
case 0: // tiny particle (1 pixel)
scrn[x + y * 640] = color;
break;
}
}
// this was going to be local to renderlightningparticle, but that would've seriously
// chomped up the stack, since that function's recursive.
byte ctab[] = {8, 3, 2, 3, 8,
3, 2, 1, 2, 3,
2, 1, 0, 1, 2,
3, 2, 1, 2, 3,
8, 3, 2, 3, 8};
void RenderLightningParticle(int x1, int y1, int x2, int y2, int range, byte bright, byte *scrn)
{
int midx, midy;
byte *ctptr;
byte b, brt;
// base case: draw the (x1,y1) pixel
if ((x1 - x2 < 2 && x1 - x2>-2) && (y1 - y2 < 2 && y1 - y2>-2))
{
if (x1 >= 0 && x1 < 635 && y1 >= 0 && y1 < 475)
{
scrn += (x1 + y1 * 640);
ctptr = &ctab[0];
for (midy = y1; midy < y1 + 5; midy++)
{
for (midx = x1; midx < x1 + 5; midx++)
{
b = *scrn;
brt = bright >> (*ctptr);
if (((b + brt)&(~31)) != (b & (~31)))
*scrn = (b & (~31)) + 31;
else
*scrn = b + brt;
ctptr++;
scrn++;
}
scrn += 640 - 5;
}
}
}
else // recursive case, find a (midx,midy) between the other two points
{
if (range < 1)
range = 1;
if (x1 < x2)
midx = x1 + (x2 - x1) / 2;
else
midx = x2 + (x1 - x2) / 2;
midx += MGL_random(range) - range / 2;
if (y1 < y2)
midy = y1 + (y2 - y1) / 2;
else
midy = y2 + (y1 - y2) / 2;
midy += MGL_random(range) - range / 2;
RenderLightningParticle(x1, y1, midx, midy, range * 3 / 4, bright, scrn);
RenderLightningParticle(midx, midy, x2, y2, range * 3 / 4, bright, scrn);
}
}
void RenderParticles(void)
{
int i;
for (i = 0; i < maxParticles; i++)
{
if (particleList[i]->Alive())
{
if (particleList[i]->type == PART_SMOKE)
RenderSmoke(particleList[i]->x >> FIXSHIFT, particleList[i]->y >> FIXSHIFT,
particleList[i]->z >> FIXSHIFT, (char) (particleList[i]->color),
particleList[i]->size);
else if (particleList[i]->type == PART_BOOM)
RenderBoom(particleList[i]->x >> FIXSHIFT, particleList[i]->y >> FIXSHIFT,
particleList[i]->z >> FIXSHIFT, (char) (particleList[i]->color),
particleList[i]->size);
else if (particleList[i]->type == PART_LIGHTNING)
LightningDraw(particleList[i]->x >> FIXSHIFT, particleList[i]->y >> FIXSHIFT,
particleList[i]->dx >> FIXSHIFT, particleList[i]->dy >> FIXSHIFT,
particleList[i]->color, (char) particleList[i]->size);
else if (particleList[i]->type == PART_STINKY)
RenderStinky(particleList[i]->x >> FIXSHIFT, particleList[i]->y >> FIXSHIFT,
particleList[i]->z >> FIXSHIFT, (char) (particleList[i]->color),
particleList[i]->size);
else if (particleList[i]->type == PART_COUNTESS)
SprDraw(particleList[i]->x >> FIXSHIFT, particleList[i]->y >> FIXSHIFT,
particleList[i]->z >> FIXSHIFT,
255, particleList[i]->life * 4 - 8,
GetMonsterSprite(MONS_COUNTESS, ANIM_IDLE, 0, 0), DISPLAY_DRAWME | DISPLAY_GLOW);
else
ParticleDraw(particleList[i]->x >> FIXSHIFT, particleList[i]->y >> FIXSHIFT,
particleList[i]->z >> FIXSHIFT, particleList[i]->color, particleList[i]->size,
DISPLAY_DRAWME | DISPLAY_PARTICLE);
}
}
}
void BlowSmoke(int x, int y, int z, int dz)
{
int i;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->x = x;
particleList[i]->y = y;
particleList[i]->z = z;
particleList[i]->dx = 0;
particleList[i]->dy = 0;
particleList[i]->dz = dz;
particleList[i]->life = 6 * 4 - MGL_random(8);
particleList[i]->size = 6;
particleList[i]->color = 64;
particleList[i]->type = PART_SMOKE;
break;
}
}
}
void StinkySteam(int x, int y, int z, int dz)
{
int i;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->x = x;
particleList[i]->y = y;
particleList[i]->z = z;
particleList[i]->dx = 0;
particleList[i]->dy = 0;
particleList[i]->dz = dz;
particleList[i]->life = 6 * 4 - MGL_random(8);
particleList[i]->size = 0;
particleList[i]->color = 64;
particleList[i]->type = PART_STINKY;
break;
}
}
}
void CountessGlow(int x, int y)
{
int i;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->x = x;
particleList[i]->y = y;
particleList[i]->z = 0;
particleList[i]->dx = 0;
particleList[i]->dy = 0;
particleList[i]->dz = 0;
particleList[i]->life = 4;
particleList[i]->size = 0;
particleList[i]->color = 64;
particleList[i]->type = PART_COUNTESS;
break;
}
}
}
void BlowUpGuy(int x, int y, int x2, int y2, int z, byte amt)
{
int i;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->x = (x + MGL_randoml(x2 - x)) << FIXSHIFT;
particleList[i]->y = (y + MGL_randoml(y2 - y)) << FIXSHIFT;
particleList[i]->z = z;
particleList[i]->dx = 0;
particleList[i]->dy = 0;
particleList[i]->dz = 0;
particleList[i]->life = 7;
particleList[i]->size = 0;
particleList[i]->color = 64;
particleList[i]->type = PART_BOOM;
MakeSound(SND_BOMBBOOM, particleList[i]->x, particleList[i]->y, SND_CUTOFF, 1800);
if (!(--amt))
break;
}
}
}
void GlassShatter(int x, int y, int x2, int y2, int z, byte amt)
{
int i;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->x = (x + MGL_randoml(x2 - x)) << FIXSHIFT;
particleList[i]->y = (y + MGL_randoml(y2 - y)) << FIXSHIFT;
particleList[i]->z = z;
particleList[i]->GoRandom(PART_GLASS, (x + MGL_randoml(x2 - x)) << FIXSHIFT, (y + MGL_randoml(y2 - y)) << FIXSHIFT,
MGL_randoml(10 * FIXAMT), 20);
particleList[i]->color = MGL_random(8)*32 + 16;
if (!(--amt))
break;
}
}
}
void SpurtParticles(byte type, bool left, int x, int y, int z, byte angle, byte force)
{
int i, amt;
byte ang2;
amt = force;
x += Cosine(angle)*10;
y += Sine(angle)*10;
if (left)
ang2 = angle + 64;
else
ang2 = angle + 128 + 64;
x += Cosine(ang2)*20;
y += Sine(ang2)*20;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->Go(type, x, y, z, angle, force);
if (!--amt)
break;
}
}
}
void ExplodeParticles(byte type, int x, int y, int z, byte force)
{
int i, amt;
amt = force;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->GoRandom(type, x, y, z, force);
if (!--amt)
break;
}
}
}
void ExplodeParticles2(byte type, int x, int y, int z, byte num, byte force)
{
int i;
if (num == 0)
return;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->GoRandom(type, x, y, z, force);
if (!--num)
break;
}
}
}
void MakeItSnow(Map *map)
{
int i;
int cx, cy;
// only 25% of particles may be snowflakes
if (MGL_random(100) > 30 || snowCount > maxParticles / 4)
return;
GetCamera(&cx, &cy);
cx -= 320;
cy -= 240;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->x = (MGL_random(640) + cx) << FIXSHIFT;
particleList[i]->y = (MGL_random(480) + cy) << FIXSHIFT;
particleList[i]->z = (300 + MGL_random(300)) << FIXSHIFT;
particleList[i]->dx = 0;
particleList[i]->dy = 0;
particleList[i]->dz = 0;
particleList[i]->size = 2;
particleList[i]->life = 50 + MGL_random(50);
particleList[i]->type = PART_SNOW;
particleList[i]->color = 31;
break;
}
}
}
void SpecialSnow(int x, int y)
{
int i;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->x = x;
particleList[i]->y = y;
particleList[i]->z = (10 + MGL_random(20)) << FIXSHIFT;
particleList[i]->dx = 0;
particleList[i]->dy = 0;
particleList[i]->dz = 0;
particleList[i]->size = 2;
particleList[i]->life = 20 + MGL_random(30);
particleList[i]->type = PART_SNOW;
break;
}
}
}
void LightningBolt(int x, int y, int x2, int y2)
{
int i;
for (i = 0; i < maxParticles; i++)
{
if (!particleList[i]->Alive())
{
particleList[i]->GoLightning(x, y, x2, y2);
break;
}
}
}
| 21.434532 | 119 | 0.548567 | Hypexion |
2dd5956f1281b44b6251988cafa62733607262c6 | 27,468 | cc | C++ | src/k2htpdtorsvrparser.cc | ggtakec/k2htp_dtor | 0fe184f32bb71fedd91fc8dc910fe143d13287ca | [
"MIT"
] | 10 | 2016-12-09T01:44:50.000Z | 2020-01-29T06:05:45.000Z | src/k2htpdtorsvrparser.cc | ggtakec/k2htp_dtor | 0fe184f32bb71fedd91fc8dc910fe143d13287ca | [
"MIT"
] | 2 | 2018-12-26T23:55:38.000Z | 2018-12-27T09:35:56.000Z | src/k2htpdtorsvrparser.cc | ggtakec/k2htp_dtor | 0fe184f32bb71fedd91fc8dc910fe143d13287ca | [
"MIT"
] | 5 | 2016-12-09T01:48:51.000Z | 2020-12-18T05:11:14.000Z | /*
* k2htpdtor for K2HASH TRANSACTION PLUGIN.
*
* Copyright 2015 Yahoo Japan Corporation.
*
* K2HASH TRANSACTION PLUGIN is programmable I/F for processing
* transaction data from modifying K2HASH data.
*
* For the full copyright and license information, please view
* the license file that was distributed with this source code.
*
* AUTHOR: Takeshi Nakatani
* CREATE: Wed Nov 04 2015
* REVISION:
*
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <k2hash/k2hutil.h>
#include <k2hash/k2hdbg.h>
#include <chmpx/chmutil.h>
#include <chmpx/chmconfutil.h>
#include <fstream>
#include "k2htpdtorsvrparser.h"
#include "k2htpdtorfile.h"
using namespace std;
//---------------------------------------------------------
// Symbols
//---------------------------------------------------------
#define INI_INCLUDE_STR "INCLUDE"
#define INI_KV_SEP_CHAR '='
#define INI_VALUE_AREA_CHAR '\"'
#define INI_COMMENT_CHAR '#'
#define INI_SEC_START_CHAR '['
#define INI_SEC_END_CHAR ']'
// section key words
#define INI_K2HDTORSVR_MAIN_STR "K2HTPDTORSVR"
#define INI_K2HDTORSVR_MAIN_SEC_STR "[" INI_K2HDTORSVR_MAIN_STR "]"
// key words in section
#define INI_K2HDTORSVR_OUTPUTFILE_STR "OUTPUTFILE"
#define INI_K2HDTORSVR_PLUGIN_STR "PLUGIN"
#define INI_K2HDTORSVR_K2HTYPE_STR "K2HTYPE"
#define INI_K2HDTORSVR_K2HFILE_STR "K2HFILE"
#define INI_K2HDTORSVR_K2HFULLMAP_STR "K2HFULLMAP"
#define INI_K2HDTORSVR_K2HINIT_STR "K2HINIT"
#define INI_K2HDTORSVR_K2HMASKBIT_STR "K2HMASKBIT"
#define INI_K2HDTORSVR_K2HCMASKBIT_STR "K2HCMASKBIT"
#define INI_K2HDTORSVR_K2HMAXELE_STR "K2HMAXELE"
#define INI_K2HDTORSVR_K2HPAGESIZE_STR "K2HPAGESIZE"
#define INI_K2HDTORSVR_K2HDTORSVR_TRANS_STR "K2HDTORSVR_TRANS"
#define INI_K2HDTORSVR_DTORTHREADCNT_STR "DTORTHREADCNT"
// value words
#define INI_K2HDTORSVR_MEM1_VAL_STR "M"
#define INI_K2HDTORSVR_MEM2_VAL_STR "MEM"
#define INI_K2HDTORSVR_MEM3_VAL_STR "MEMORY"
#define INI_K2HDTORSVR_FILE1_VAL_STR "F"
#define INI_K2HDTORSVR_FILE2_VAL_STR "FILE"
#define INI_K2HDTORSVR_TEMP1_VAL_STR "T"
#define INI_K2HDTORSVR_TEMP2_VAL_STR "TEMP"
#define INI_K2HDTORSVR_TEMP3_VAL_STR "TEMPORARY"
#define INI_K2HDTORSVR_YES1_VAL_STR "Y"
#define INI_K2HDTORSVR_YES2_VAL_STR "YES"
#define INI_K2HDTORSVR_NO1_VAL_STR "N"
#define INI_K2HDTORSVR_NO2_VAL_STR "NO"
#define INI_K2HDTORSVR_ON_VAL_STR "ON"
#define INI_K2HDTORSVR_OFF_VAL_STR "OFF"
// Environment
#define DTORSVR_CONFFILE_ENV_NAME "DTORSVRCONFFILE"
#define DTORSVR_JSONCONF_ENV_NAME "DTORSVRJSONCONF"
//---------------------------------------------------------
// Utilities
//---------------------------------------------------------
static bool read_ini_file_contents(const char* path, strlst_t& lines, strlst_t& files)
{
if(ISEMPTYSTR(path)){
ERR_K2HPRN("path is empty.");
return false;
}
// check file path
string realpath;
if(!cvt_path_real_path(path, realpath)){
ERR_K2HPRN("Could not convert realpath from file(%s)", path);
return false;
}
// is already listed
for(strlst_t::const_iterator iter = files.begin(); iter != files.end(); ++iter){
if(realpath == (*iter)){
ERR_K2HPRN("file(%s:%s) is already loaded.", path, realpath.c_str());
return false;
}
}
files.push_back(realpath);
// load
ifstream cfgstream(realpath.c_str(), ios::in);
if(!cfgstream.good()){
ERR_K2HPRN("Could not open(read only) file(%s:%s)", path, realpath.c_str());
return false;
}
string line;
int lineno;
for(lineno = 1; cfgstream.good() && getline(cfgstream, line); lineno++){
line = trim(line);
if(0 == line.length()){
continue;
}
if(INI_COMMENT_CHAR == line[0]){
continue;
}
// check only include
string::size_type pos;
if(string::npos != (pos = line.find(INI_INCLUDE_STR))){
string value = trim(line.substr(pos + 1));
string key = trim(line.substr(0, pos));
if(key == INI_INCLUDE_STR){
// found include, do reentrant
if(!read_ini_file_contents(value.c_str(), lines, files)){
ERR_K2HPRN("Failed to load include file(%s)", value.c_str());
cfgstream.close();
return false;
}
continue;
}
}
// add
lines.push_back(line);
}
cfgstream.close();
return true;
}
static void parse_ini_line(const string& line, string& key, string& value)
{
string::size_type pos;
if(string::npos != (pos = line.find(INI_KV_SEP_CHAR))){
key = trim(line.substr(0, pos));
value = trim(line.substr(pos + 1));
}else{
key = trim(line);
value = "";
}
if(!extract_conf_value(key) || !extract_conf_value(value)){
key.clear();
value.clear();
}else{
key = upper(key); // key convert to upper
}
}
inline void initialize_k2htpdtorsvr_info(PK2HTPDTORSVRINFO pInfo)
{
if(!pInfo){
return;
}
pInfo->conffile = "";
pInfo->output_file = "";
pInfo->plugin_param = "";
pInfo->is_k2hash = false;
pInfo->k2hash_type_mem = false;
pInfo->k2hash_type_tmp = false;
pInfo->k2hash_file = "";
pInfo->k2hash_fullmap = false;
pInfo->k2hash_init = false;
pInfo->k2hash_mask_bitcnt = K2HShm::DEFAULT_MASK_BITCOUNT;
pInfo->k2hash_cmask_bitcnt = K2HShm::DEFAULT_COLLISION_MASK_BITCOUNT;
pInfo->k2hash_max_element_cnt = K2HShm::DEFAULT_MAX_ELEMENT_CNT;
pInfo->k2hash_pagesize = K2HShm::MIN_PAGE_SIZE;
pInfo->trans_ini_file = "";
pInfo->trans_dtor_threads = K2HTransManager::DEFAULT_THREAD_POOL;
}
static bool ParseK2htpdtorsvrIniFile(const char* conffile, PK2HTPDTORSVRINFO pInfo)
{
if(ISEMPTYSTR(conffile) || !pInfo){
ERR_K2HPRN("parameters are wrong.");
return false;
}
// read conf file
strlst_t lines;
strlst_t files;
if(!read_ini_file_contents(conffile, lines, files)){
ERR_K2HPRN("Failed to load configuration ini file(%s)", conffile);
return false;
}
// initialize
initialize_k2htpdtorsvr_info(pInfo);
// Parse & Check
bool set_main_sec = false;
for(strlst_t::const_iterator iter = lines.begin(); iter != lines.end(); ){
if((*iter) == INI_K2HDTORSVR_MAIN_SEC_STR){
// main section
if(set_main_sec){
ERR_K2HPRN("main section(%s) is already set.", INI_K2HDTORSVR_MAIN_SEC_STR);
return false;
}
set_main_sec = true;
// loop for main section
for(++iter; iter != lines.end(); ++iter){
if(INI_SEC_START_CHAR == (*iter)[0] && INI_SEC_END_CHAR == (*iter)[iter->length() - 1]){
// another section start, so break this loop
break;
}
// parse key(to upper) & value
string key;
string value;
parse_ini_line((*iter), key, value);
// compare key word
if(INI_K2HDTORSVR_OUTPUTFILE_STR == key){
// output file path
pInfo->output_file = value;
}else if(INI_K2HDTORSVR_PLUGIN_STR == key){
// plugin path
pInfo->plugin_param = value;
}else if(INI_K2HDTORSVR_K2HTYPE_STR == key){
// k2hash type
pInfo->is_k2hash = true;
value = upper(value);
if(INI_K2HDTORSVR_MEM1_VAL_STR == value || INI_K2HDTORSVR_MEM2_VAL_STR == value || INI_K2HDTORSVR_MEM3_VAL_STR == value){
pInfo->k2hash_type_mem = true;
pInfo->k2hash_type_tmp = false;
}else if(INI_K2HDTORSVR_TEMP1_VAL_STR == value || INI_K2HDTORSVR_TEMP2_VAL_STR == value || INI_K2HDTORSVR_TEMP3_VAL_STR == value){
pInfo->k2hash_type_mem = false;
pInfo->k2hash_type_tmp = true;
}else if(INI_K2HDTORSVR_FILE1_VAL_STR == value || INI_K2HDTORSVR_FILE2_VAL_STR == value){
pInfo->k2hash_type_mem = false;
pInfo->k2hash_type_tmp = false;
}else{
WAN_K2HPRN("keyword(%s)'s value(%s) in main section(%s) is unknown value, so skip it.", key.c_str(), value.c_str(), INI_K2HDTORSVR_MAIN_SEC_STR);
}
}else if(INI_K2HDTORSVR_K2HFILE_STR == key){
// k2hash file
pInfo->is_k2hash = true;
pInfo->k2hash_type_mem = false;
pInfo->k2hash_file = value;
}else if(INI_K2HDTORSVR_K2HFULLMAP_STR == key){
// k2hash fullmap
pInfo->is_k2hash = true;
value = upper(value);
if(INI_K2HDTORSVR_YES1_VAL_STR == value || INI_K2HDTORSVR_YES2_VAL_STR == value || INI_K2HDTORSVR_ON_VAL_STR == value){
pInfo->k2hash_fullmap = true;
}else if(INI_K2HDTORSVR_NO1_VAL_STR == value || INI_K2HDTORSVR_NO2_VAL_STR == value || INI_K2HDTORSVR_OFF_VAL_STR == value){
pInfo->k2hash_fullmap = false;
}else{
WAN_K2HPRN("keyword(%s)'s value(%s) in main section(%s) is unknown value, so skip it.", key.c_str(), value.c_str(), INI_K2HDTORSVR_MAIN_SEC_STR);
}
}else if(INI_K2HDTORSVR_K2HINIT_STR == key){
// k2hash init
pInfo->is_k2hash = true;
value = upper(value);
if(INI_K2HDTORSVR_YES1_VAL_STR == value || INI_K2HDTORSVR_YES2_VAL_STR == value || INI_K2HDTORSVR_ON_VAL_STR == value){
pInfo->k2hash_init = true;
}else if(INI_K2HDTORSVR_NO1_VAL_STR == value || INI_K2HDTORSVR_NO2_VAL_STR == value || INI_K2HDTORSVR_OFF_VAL_STR == value){
pInfo->k2hash_init = false;
}else{
WAN_K2HPRN("keyword(%s)'s value(%s) in main section(%s) is unknown value, so skip it.", key.c_str(), value.c_str(), INI_K2HDTORSVR_MAIN_SEC_STR);
}
}else if(INI_K2HDTORSVR_K2HMASKBIT_STR == key){
// k2hash MaskBitCnt
pInfo->k2hash_mask_bitcnt = atoi(value.c_str());
}else if(INI_K2HDTORSVR_K2HCMASKBIT_STR == key){
// k2hash CMaskBitCnt
pInfo->k2hash_cmask_bitcnt = atoi(value.c_str());
}else if(INI_K2HDTORSVR_K2HMAXELE_STR == key){
// k2hash MaxElementCnt
pInfo->k2hash_max_element_cnt = atoi(value.c_str());
}else if(INI_K2HDTORSVR_K2HPAGESIZE_STR == key){
// k2hash PageSize
pInfo->k2hash_pagesize = static_cast<size_t>(atoll(value.c_str()));
}else if(INI_K2HDTORSVR_K2HDTORSVR_TRANS_STR == key){
// transfer
pInfo->trans_ini_file = "";
if(!value.empty() && right_check_json_string(value.c_str())){
// json string
pInfo->trans_ini_file = value;
}else{
// not json string, thus it is a file
if(!cvt_path_real_path(value.c_str(), pInfo->trans_ini_file)){
WAN_K2HPRN("keyword(%s) has value(%s) in main section(%s), but does not file exist.", key.c_str(), value.c_str(), INI_K2HDTORSVR_MAIN_SEC_STR);
}
}
}else if(INI_K2HDTORSVR_DTORTHREADCNT_STR == key){
// dtor thread pool count
pInfo->trans_dtor_threads = atoi(value.c_str());
}
}
}else{
++iter;
}
}
// check values
if(pInfo->output_file.empty() && pInfo->plugin_param.empty() && !pInfo->is_k2hash){
ERR_K2HPRN("configuration file has no plugin and no k2hash output.");
return false;
}
if(pInfo->is_k2hash){
if(!(pInfo->k2hash_type_mem) && !(pInfo->k2hash_type_tmp) && pInfo->k2hash_file.empty()){
ERR_K2HPRN("configuration file specify k2hash output, but no k2hash type.");
return false;
}
if(pInfo->k2hash_type_mem){
if(pInfo->k2hash_type_tmp || !pInfo->k2hash_file.empty()){
ERR_K2HPRN("configuration file specify k2hash memory output, but k2hash type conflict with temporary or file.");
return false;
}
if(!pInfo->k2hash_fullmap){
ERR_K2HPRN("configuration file specify k2hash memory output, but k2hash does not full mapping.");
return false;
}
if(!pInfo->k2hash_init){
ERR_K2HPRN("configuration file specify k2hash memory output, but k2hash does not initialize.");
return false;
}
}
if(pInfo->k2hash_type_tmp){
if(!pInfo->k2hash_fullmap){
ERR_K2HPRN("configuration file specify k2hash temporary output, but k2hash does not full mapping.");
return false;
}
if(!pInfo->k2hash_init){
ERR_K2HPRN("configuration file specify k2hash temporary output, but k2hash does not initialize.");
return false;
}
}
if(!pInfo->trans_ini_file.empty()){
if(pInfo->trans_dtor_threads < K2HTransManager::DEFAULT_THREAD_POOL){
ERR_K2HPRN("configuration file specify transfer setting, but trans(dtor) thread count(%d) is wrong.", pInfo->trans_dtor_threads);
return false;
}
}
}
return true;
}
static bool ParseK2htpdtorsvrYamlContents(yaml_parser_t& yparser, PK2HTPDTORSVRINFO pInfo)
{
// Must start yaml mapping event.
yaml_event_t yevent;
if(!yaml_parser_parse(&yparser, &yevent)){
ERR_K2HPRN("Could not parse event. errno = %d", errno);
return false;
}
if(YAML_MAPPING_START_EVENT != yevent.type){
ERR_K2HPRN("Parsed event type is not start mapping(%d)", yevent.type);
yaml_event_delete(&yevent);
return false;
}
yaml_event_delete(&yevent);
// Loading
string key("");
bool result = true;
for(bool is_loop = true; is_loop && result; ){
// get event
if(!yaml_parser_parse(&yparser, &yevent)){
ERR_K2HPRN("Could not parse event. errno = %d", errno);
result = false;
continue;
}
// check event
if(YAML_MAPPING_END_EVENT == yevent.type){
// End of mapping event
is_loop = false;
}else if(YAML_SCALAR_EVENT == yevent.type){
// Load key & value
if(key.empty()){
key = reinterpret_cast<const char*>(yevent.data.scalar.value);
}else if(0 != strlen(reinterpret_cast<const char*>(yevent.data.scalar.value))){
//
// Compare key and set value
//
if(0 == strcasecmp(INI_K2HDTORSVR_OUTPUTFILE_STR, key.c_str())){
// output file path
pInfo->output_file = reinterpret_cast<const char*>(yevent.data.scalar.value);
}else if(0 == strcasecmp(INI_K2HDTORSVR_PLUGIN_STR, key.c_str())){
// plugin path
pInfo->plugin_param = reinterpret_cast<const char*>(yevent.data.scalar.value);
}else if(0 == strcasecmp(INI_K2HDTORSVR_K2HTYPE_STR, key.c_str())){
// k2hash type
const char* pvalue = reinterpret_cast<const char*>(yevent.data.scalar.value);
pInfo->is_k2hash = true;
if(0 == strcasecmp(INI_K2HDTORSVR_MEM1_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_MEM2_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_MEM3_VAL_STR, pvalue)){
pInfo->k2hash_type_mem = true;
pInfo->k2hash_type_tmp = false;
}else if(0 == strcasecmp(INI_K2HDTORSVR_TEMP1_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_TEMP2_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_TEMP3_VAL_STR, pvalue)){
pInfo->k2hash_type_mem = false;
pInfo->k2hash_type_tmp = true;
}else if(0 == strcasecmp(INI_K2HDTORSVR_FILE1_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_FILE2_VAL_STR, pvalue)){
pInfo->k2hash_type_mem = false;
pInfo->k2hash_type_tmp = false;
}else{
WAN_K2HPRN("keyword(%s)'s value(%s) in main section(%s) is unknown value, so skip it.", key.c_str(), pvalue, INI_K2HDTORSVR_MAIN_SEC_STR);
}
}else if(0 == strcasecmp(INI_K2HDTORSVR_K2HFILE_STR, key.c_str())){
// k2hash file
pInfo->is_k2hash = true;
pInfo->k2hash_type_mem = false;
pInfo->k2hash_file = reinterpret_cast<const char*>(yevent.data.scalar.value);
}else if(0 == strcasecmp(INI_K2HDTORSVR_K2HFULLMAP_STR, key.c_str())){
// k2hash fullmap
const char* pvalue = reinterpret_cast<const char*>(yevent.data.scalar.value);
pInfo->is_k2hash = true;
if(0 == strcasecmp(INI_K2HDTORSVR_YES1_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_YES2_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_ON_VAL_STR, pvalue)){
pInfo->k2hash_fullmap = true;
}else if(0 == strcasecmp(INI_K2HDTORSVR_NO1_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_NO2_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_OFF_VAL_STR, pvalue)){
pInfo->k2hash_fullmap = false;
}else{
WAN_K2HPRN("keyword(%s)'s value(%s) in main section(%s) is unknown value, so skip it.", key.c_str(), pvalue, INI_K2HDTORSVR_MAIN_SEC_STR);
}
}else if(0 == strcasecmp(INI_K2HDTORSVR_K2HINIT_STR, key.c_str())){
// k2hash init
const char* pvalue = reinterpret_cast<const char*>(yevent.data.scalar.value);
pInfo->is_k2hash = true;
if(0 == strcasecmp(INI_K2HDTORSVR_YES1_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_YES2_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_ON_VAL_STR, pvalue)){
pInfo->k2hash_init = true;
}else if(0 == strcasecmp(INI_K2HDTORSVR_NO1_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_NO2_VAL_STR, pvalue) || 0 == strcasecmp(INI_K2HDTORSVR_OFF_VAL_STR, pvalue)){
pInfo->k2hash_init = false;
}else{
WAN_K2HPRN("keyword(%s)'s value(%s) in main section(%s) is unknown value, so skip it.", key.c_str(), pvalue, INI_K2HDTORSVR_MAIN_SEC_STR);
}
}else if(0 == strcasecmp(INI_K2HDTORSVR_K2HMASKBIT_STR, key.c_str())){
// k2hash MaskBitCnt
pInfo->k2hash_mask_bitcnt = atoi(reinterpret_cast<const char*>(yevent.data.scalar.value));
}else if(0 == strcasecmp(INI_K2HDTORSVR_K2HCMASKBIT_STR, key.c_str())){
// k2hash CMaskBitCnt
pInfo->k2hash_cmask_bitcnt = atoi(reinterpret_cast<const char*>(yevent.data.scalar.value));
}else if(0 == strcasecmp(INI_K2HDTORSVR_K2HMAXELE_STR, key.c_str())){
// k2hash MaxElementCnt
pInfo->k2hash_max_element_cnt = atoi(reinterpret_cast<const char*>(yevent.data.scalar.value));
}else if(0 == strcasecmp(INI_K2HDTORSVR_K2HPAGESIZE_STR, key.c_str())){
// k2hash PageSize
pInfo->k2hash_pagesize = static_cast<size_t>(atoll(reinterpret_cast<const char*>(yevent.data.scalar.value)));
}else if(0 == strcasecmp(INI_K2HDTORSVR_K2HDTORSVR_TRANS_STR, key.c_str())){
// transfer
pInfo->trans_ini_file = "";
if(yevent.data.scalar.value && right_check_json_string(reinterpret_cast<const char*>(yevent.data.scalar.value))){
// json string
pInfo->trans_ini_file = reinterpret_cast<const char*>(yevent.data.scalar.value);
}else{
// not json string, thus it is a file
if(!cvt_path_real_path(reinterpret_cast<const char*>(yevent.data.scalar.value), pInfo->trans_ini_file)){
WAN_K2HPRN("keyword(%s) has value(%s) in main section(%s), but does not file exist.", key.c_str(), reinterpret_cast<const char*>(yevent.data.scalar.value), INI_K2HDTORSVR_MAIN_SEC_STR);
}
}
}else if(0 == strcasecmp(INI_K2HDTORSVR_DTORTHREADCNT_STR, key.c_str())){
// dtor thread pool count
pInfo->trans_dtor_threads = atoi(reinterpret_cast<const char*>(yevent.data.scalar.value));
}else{
// unknown key name.
MSG_K2HPRN("Unknown key(%s), so skip this line.", key.c_str());
}
key.clear();
}else{
WAN_K2HPRN("The value is empty for %s key, so skip this line.", key.c_str());
}
}else{
// [TODO] Now not support alias(anchor) event
//
ERR_K2HPRN("Found unexpected yaml event(%d) in %s section.", yevent.type, INI_K2HDTORSVR_MAIN_STR);
result = false;
}
// delete event
if(is_loop){
is_loop = yevent.type != YAML_STREAM_END_EVENT;
}
yaml_event_delete(&yevent);
}
return result;
}
static bool ParseK2htpdtorsvrYamlTopLevel(yaml_parser_t& yparser, PK2HTPDTORSVRINFO pInfo)
{
CHMYamlDataStack other_stack;
bool is_set_main = false;
bool result = true;
for(bool is_loop = true, in_stream = false, in_document = false, in_toplevel = false; is_loop && result; ){
// get event
yaml_event_t yevent;
if(!yaml_parser_parse(&yparser, &yevent)){
ERR_K2HPRN("Could not parse event. errno = %d", errno);
result = false;
continue;
}
// check event
switch(yevent.type){
case YAML_NO_EVENT:
MSG_K2HPRN("There is no yaml event in loop");
break;
case YAML_STREAM_START_EVENT:
if(!other_stack.empty()){
MSG_K2HPRN("Found start yaml stream event in skipping event loop");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(in_stream){
MSG_K2HPRN("Already start yaml stream event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else{
MSG_K2HPRN("Start yaml stream event in loop");
in_stream = true;
}
break;
case YAML_STREAM_END_EVENT:
if(!other_stack.empty()){
MSG_K2HPRN("Found stop yaml stream event in skipping event loop");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(!in_stream){
MSG_K2HPRN("Already stop yaml stream event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else{
MSG_K2HPRN("Stop yaml stream event in loop");
in_stream = false;
}
break;
case YAML_DOCUMENT_START_EVENT:
if(!other_stack.empty()){
MSG_K2HPRN("Found start yaml document event in skipping event loop");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(!in_stream){
MSG_K2HPRN("Found start yaml document event before yaml stream event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(in_document){
MSG_K2HPRN("Already start yaml document event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else{
MSG_K2HPRN("Start yaml document event in loop");
in_document = true;
}
break;
case YAML_DOCUMENT_END_EVENT:
if(!other_stack.empty()){
MSG_K2HPRN("Found stop yaml document event in skipping event loop");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(!in_document){
MSG_K2HPRN("Already stop yaml document event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else{
MSG_K2HPRN("Stop yaml document event in loop");
in_document = false;
}
break;
case YAML_MAPPING_START_EVENT:
if(!other_stack.empty()){
MSG_K2HPRN("Found start yaml mapping event in skipping event loop");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(!in_stream){
MSG_K2HPRN("Found start yaml mapping event before yaml stream event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(!in_document){
MSG_K2HPRN("Found start yaml mapping event before yaml document event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(in_toplevel){
MSG_K2HPRN("Already start yaml mapping event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else{
MSG_K2HPRN("Start yaml mapping event in loop");
in_toplevel = true;
}
break;
case YAML_MAPPING_END_EVENT:
if(!other_stack.empty()){
MSG_K2HPRN("Found stop yaml mapping event in skipping event loop");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(!in_toplevel){
MSG_K2HPRN("Already stop yaml mapping event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else{
MSG_K2HPRN("Stop yaml mapping event in loop");
in_toplevel = false;
}
break;
case YAML_SEQUENCE_START_EVENT:
// always stacking
//
if(!other_stack.empty()){
MSG_K2HPRN("Found start yaml sequence event in skipping event loop");
if(!other_stack.add(yevent.type)){
result = false;
}
}else{
MSG_K2HPRN("Found start yaml sequence event before top level event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}
break;
case YAML_SEQUENCE_END_EVENT:
// always stacking
//
if(!other_stack.empty()){
MSG_K2HPRN("Found stop yaml sequence event in skipping event loop");
if(!other_stack.add(yevent.type)){
result = false;
}
}else{
MSG_K2HPRN("Found stop yaml sequence event before top level event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}
break;
case YAML_SCALAR_EVENT:
if(!other_stack.empty()){
MSG_K2HPRN("Got yaml scalar event in skipping event loop");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(!in_stream){
MSG_K2HPRN("Got yaml scalar event before yaml stream event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(!in_document){
MSG_K2HPRN("Got yaml scalar event before yaml document event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else if(!in_toplevel){
MSG_K2HPRN("Got yaml scalar event before yaml mapping event in loop, Thus stacks this event.");
if(!other_stack.add(yevent.type)){
result = false;
}
}else{
// Found Top Level Keywords, start to loading
if(0 == strcasecmp(INI_K2HDTORSVR_MAIN_STR, reinterpret_cast<const char*>(yevent.data.scalar.value))){
if(is_set_main){
MSG_K2HPRN("Got yaml scalar event in loop, but already loading %s. Thus stacks this event.", INI_K2HDTORSVR_MAIN_STR);
if(!other_stack.add(yevent.type)){
result = false;
}
}else{
// Load K2HTPDTORSVR section
if(!ParseK2htpdtorsvrYamlContents(yparser, pInfo)){
ERR_K2HPRN("Something error occured in loading %s section.", INI_K2HDTORSVR_MAIN_STR);
result = false;
}
}
}else{
MSG_K2HPRN("Got yaml scalar event in loop, but unknown keyword(%s) for me. Thus stacks this event.", reinterpret_cast<const char*>(yevent.data.scalar.value));
if(!other_stack.add(yevent.type)){
result = false;
}
}
}
break;
case YAML_ALIAS_EVENT:
// [TODO]
// Now we do not supports alias(anchor) event.
//
MSG_K2HPRN("Got yaml alias(anchor) event in loop, but we does not support this event. Thus skip this event.");
break;
}
// delete event
is_loop = yevent.type != YAML_STREAM_END_EVENT;
yaml_event_delete(&yevent);
}
return result;
}
static bool ParseK2htpdtorsvrYaml(const char* config, PK2HTPDTORSVRINFO pInfo, bool is_json_string)
{
// initialize yaml parser
yaml_parser_t yparser;
if(!yaml_parser_initialize(&yparser)){
ERR_K2HPRN("Failed to initialize yaml parser");
return false;
}
FILE* fp = NULL;
if(!is_json_string){
// open configuration file
if(NULL == (fp = fopen(config, "r"))){
ERR_K2HPRN("Could not open configuration file(%s). errno = %d", config, errno);
// cppcheck-suppress unmatchedSuppression
// cppcheck-suppress resourceLeak
return false;
}
// set file to parser
yaml_parser_set_input_file(&yparser, fp);
}else{ // JSON_STR
// set string to parser
yaml_parser_set_input_string(&yparser, reinterpret_cast<const unsigned char*>(config), strlen(config));
}
// Do parsing
bool result = ParseK2htpdtorsvrYamlTopLevel(yparser, pInfo);
yaml_parser_delete(&yparser);
if(fp){
fclose(fp);
}
return result;
}
bool ParseK2htpdtorsvrConfiguration(const char* config, PK2HTPDTORSVRINFO pInfo)
{
// get configuration type without environment
string normalize_config("");
CHMCONFTYPE conftype = check_chmconf_type_ex(config, DTORSVR_CONFFILE_ENV_NAME, DTORSVR_JSONCONF_ENV_NAME, &normalize_config);
if(CHMCONF_TYPE_UNKNOWN == conftype || CHMCONF_TYPE_NULL == conftype){
ERR_K2HPRN("configuration file or json string is wrong.");
return false;
}
bool result;
if(CHMCONF_TYPE_INI_FILE == conftype){
result = ParseK2htpdtorsvrIniFile(normalize_config.c_str(), pInfo);
}else{
result = ParseK2htpdtorsvrYaml(normalize_config.c_str(), pInfo, (CHMCONF_TYPE_JSON_STRING == conftype));
}
// configuration file
pInfo->conffile = normalize_config;
return result;
}
/*
* VIM modelines
*
* vim:set ts=4 fenc=utf-8:
*/
| 33.661765 | 192 | 0.681957 | ggtakec |
2dd75dc1523557f4a9c0a2abf2a52d94d27691a7 | 3,689 | cpp | C++ | hr/medium/minimum_area.cpp | gnom1gnom/cpp-algorithms | e460c0d1720acf0e0548452dfba05651e4868120 | [
"Unlicense"
] | null | null | null | hr/medium/minimum_area.cpp | gnom1gnom/cpp-algorithms | e460c0d1720acf0e0548452dfba05651e4868120 | [
"Unlicense"
] | null | null | null | hr/medium/minimum_area.cpp | gnom1gnom/cpp-algorithms | e460c0d1720acf0e0548452dfba05651e4868120 | [
"Unlicense"
] | null | null | null | /*
* Complete the 'minArea' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
* 1. INTEGER_ARRAY x
* 2. INTEGER_ARRAY y
* 3. INTEGER k
*/
#include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
long minArea(vector<int> x, vector<int> y, int k)
{
// szukamy lewej dolnej krawędzi
// szukamy prawej górnej krawedzi
vector<pair<int, int>> vect;
for (int i = 0; i < x.size(); i++)
{
vect.push_back(make_pair(x[i], y[i]));
}
sort(vect.begin(), vect.end());
pair<int, int> lowerBig = vect.front();
pair<int, int> upperBig = vect.back();
long bokBig = ((upperBig.first - lowerBig.first) > (upperBig.second - lowerBig.second)) ? (upperBig.first - lowerBig.first) : (upperBig.second - lowerBig.second);
cout << "large square: " << pow(bokBig + 2, 2) << endl;
vector<pair<int, int>> vect_small;
int nextIndex = vect.size() / 2;
// odejmujemy punk lower albo upper
size_t lowerInd{0}, upperInd{vect.size() - 1};
for (int i = vect.size(); i > k && upperInd > lowerInd; i--)
{
// kwadrat mniejszy o punkt z dołu
pair<int, int> lower1 = vect[lowerInd];
pair<int, int> upper1 = vect[upperInd - 1];
long bok1 = ((upper1.first - lower1.first) > (upper1.second - lower1.second)) ? (upper1.first - lower1.first) : (upper1.second - lower1.second);
// kwadrat mniejszy o punkt z góry
pair<int, int> lower2 = vect[lowerInd + 1];
pair<int, int> upper2 = vect[upperInd];
long bok2 = ((upper2.first - lower2.first) > (upper2.second - lower2.second)) ? (upper2.first - lower2.first) : (upper2.second - lower2.second);
// sprawdzamy który ma mniejszy bok
// odrzucamy wierdzłołek który generuje większy bok
(bok1 >= bok2) ? lowerInd++ : upperInd--;
}
pair<int, int> lower = vect[lowerInd];
pair<int, int> upper = vect[upperInd];
long bok = ((upper.first - lower.first) > (upper.second - lower.second)) ? (upper.first - lower.first) : (upper.second - lower.second);
cout << "small square: " << pow(bok + 2, 2) << endl;
return pow(bok + 2, 2);
}
int main()
{ /*
ofstream fout(getenv("OUTPUT_PATH"));
string x_count_temp;
getline(cin, x_count_temp);
int x_count = stoi(ltrim(rtrim(x_count_temp)));
vector<int> x(x_count);
for (int i = 0; i < x_count; i++) {
string x_item_temp;
getline(cin, x_item_temp);
int x_item = stoi(ltrim(rtrim(x_item_temp)));
x[i] = x_item;
}
string y_count_temp;
getline(cin, y_count_temp);
int y_count = stoi(ltrim(rtrim(y_count_temp)));
vector<int> y(y_count);
for (int i = 0; i < y_count; i++) {
string y_item_temp;
getline(cin, y_item_temp);
int y_item = stoi(ltrim(rtrim(y_item_temp)));
y[i] = y_item;
}
string k_temp;
getline(cin, k_temp);
int k = stoi(ltrim(rtrim(k_temp)));
*/
// out 81
// vector<int> x = {0, 3};
// vector<int> y = {0, 7};
// out 36
vector<int> x = {0, 0, 1, 1, 2, 2};
vector<int> y = {0, 1, 0, 1, 0, 1};
int k = 4;
long result = minArea(x, y, k);
cout << result << "\n";
return 0;
}
string ltrim(const string &str)
{
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))));
return s;
}
string rtrim(const string &str)
{
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end());
return s;
} | 24.925676 | 166 | 0.584169 | gnom1gnom |
2dd75efe9f4490c764ffb6e78a35c63f50a350fe | 1,515 | cpp | C++ | android-31/android/telephony/CarrierConfigManager_Apn.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/telephony/CarrierConfigManager_Apn.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-31/android/telephony/CarrierConfigManager_Apn.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../../JString.hpp"
#include "./CarrierConfigManager_Apn.hpp"
namespace android::telephony
{
// Fields
JString CarrierConfigManager_Apn::KEY_PREFIX()
{
return getStaticObjectField(
"android.telephony.CarrierConfigManager$Apn",
"KEY_PREFIX",
"Ljava/lang/String;"
);
}
JString CarrierConfigManager_Apn::KEY_SETTINGS_DEFAULT_PROTOCOL_STRING()
{
return getStaticObjectField(
"android.telephony.CarrierConfigManager$Apn",
"KEY_SETTINGS_DEFAULT_PROTOCOL_STRING",
"Ljava/lang/String;"
);
}
JString CarrierConfigManager_Apn::KEY_SETTINGS_DEFAULT_ROAMING_PROTOCOL_STRING()
{
return getStaticObjectField(
"android.telephony.CarrierConfigManager$Apn",
"KEY_SETTINGS_DEFAULT_ROAMING_PROTOCOL_STRING",
"Ljava/lang/String;"
);
}
JString CarrierConfigManager_Apn::PROTOCOL_IPV4()
{
return getStaticObjectField(
"android.telephony.CarrierConfigManager$Apn",
"PROTOCOL_IPV4",
"Ljava/lang/String;"
);
}
JString CarrierConfigManager_Apn::PROTOCOL_IPV4V6()
{
return getStaticObjectField(
"android.telephony.CarrierConfigManager$Apn",
"PROTOCOL_IPV4V6",
"Ljava/lang/String;"
);
}
JString CarrierConfigManager_Apn::PROTOCOL_IPV6()
{
return getStaticObjectField(
"android.telephony.CarrierConfigManager$Apn",
"PROTOCOL_IPV6",
"Ljava/lang/String;"
);
}
// QJniObject forward
CarrierConfigManager_Apn::CarrierConfigManager_Apn(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
} // namespace android::telephony
| 23.671875 | 85 | 0.753795 | YJBeetle |
2dd88f1b46450ebb119f797ddb4878d5448526cf | 5,334 | cpp | C++ | geometry/geometry_tests/spline_test.cpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 2 | 2019-01-24T15:36:20.000Z | 2019-12-26T10:03:48.000Z | geometry/geometry_tests/spline_test.cpp | marceldallagnol/omim | 774de15a3b8c369acbf412f15a1db61717358262 | [
"Apache-2.0"
] | 1 | 2018-03-07T15:05:23.000Z | 2018-03-07T15:05:23.000Z | geometry/geometry_tests/spline_test.cpp | maksimandrianov/omim | cbc5a80d09d585afbda01e471887f63b9d3ab0c2 | [
"Apache-2.0"
] | 1 | 2019-08-09T21:31:29.000Z | 2019-08-09T21:31:29.000Z | #include "testing/testing.hpp"
#include "geometry/geometry_tests/equality.hpp"
#include "geometry/spline.hpp"
using m2::Spline;
using m2::PointD;
void TestPointDDir(PointD const & dst, PointD const & src)
{
double len1 = dst.Length();
double len2 = src.Length();
TEST_ALMOST_EQUAL_ULPS(dst.x/len1, src.x/len2, ());
TEST_ALMOST_EQUAL_ULPS(dst.y/len1, src.y/len2, ());
}
UNIT_TEST(SmoothedDirections)
{
vector<PointD> path;
path.push_back(PointD(0, 0));
path.push_back(PointD(40, 40));
path.push_back(PointD(80, 0));
Spline spl(path);
double const sqrt2 = sqrt(2.0);
Spline::iterator itr;
PointD dir1(sqrt2 / 2.0, sqrt2 / 2.0);
PointD dir2(sqrt2 / 2.0, -sqrt2 / 2.0);
itr.Attach(spl);
TestPointDDir(itr.m_avrDir, dir1);
itr.Advance(sqrt2 * 30.0);
TestPointDDir(itr.m_avrDir, dir1);
itr.Advance(sqrt2 * 40.0);
TestPointDDir(itr.m_avrDir, dir1 * 0.25 + dir2 * 0.75);
itr.Advance(sqrt2 * 10.0);
TestPointDDir(itr.m_avrDir, dir2);
path.clear();
path.push_back(PointD(0, 0));
path.push_back(PointD(40, 40));
path.push_back(PointD(80, 40));
path.push_back(PointD(120, 0));
PointD dir12(1.0, 0.0);
Spline spl2(path);
itr.Attach(spl2);
TestPointDDir(itr.m_avrDir, dir1);
itr.Advance(sqrt2 * 80.0 + 40.0);
TestPointDDir(itr.m_avrDir, dir12);
itr.Attach(spl2);
itr.Advance(sqrt2 * 40.0);
TestPointDDir(itr.m_avrDir, dir1);
itr.Advance(80.0);
TestPointDDir(itr.m_avrDir, dir12 * 0.5 + dir2 * 0.5);
}
UNIT_TEST(UsualDirections)
{
vector<PointD> path;
path.push_back(PointD(0, 0));
path.push_back(PointD(40, 40));
path.push_back(PointD(80, 0));
Spline spl(path);
double const sqrt2 = sqrtf(2.0);
Spline::iterator itr;
PointD dir1(sqrt2 / 2.0, sqrt2 / 2.0);
PointD dir2(sqrt2 / 2.0, -sqrt2 / 2.0);
itr.Attach(spl);
TestPointDDir(itr.m_dir, dir1);
itr.Advance(sqrt2 * 30.0);
TestPointDDir(itr.m_dir, dir1);
itr.Advance(sqrt2 * 40.0);
TestPointDDir(itr.m_dir, dir2);
path.clear();
path.push_back(PointD(0, 0));
path.push_back(PointD(40, 40));
path.push_back(PointD(80, 40));
path.push_back(PointD(120, 0));
PointD dir12(1.0, 0.0);
Spline spl2(path);
itr.Attach(spl2);
TestPointDDir(itr.m_dir, dir1);
itr.Advance(sqrt2 * 80.0 + 35.0);
TestPointDDir(itr.m_dir, dir2);
itr.Attach(spl2);
itr.Advance(sqrt2 * 45.0);
TestPointDDir(itr.m_dir, dir12);
itr.Advance(80.0);
TestPointDDir(itr.m_dir, dir2);
}
UNIT_TEST(Positions)
{
vector<PointD> path;
path.push_back(PointD(0, 0));
path.push_back(PointD(40, 40));
path.push_back(PointD(80, 0));
Spline spl0(path);
Spline spl4;
spl4 = spl0;
double const sqrt2 = sqrt(2.0);
Spline::iterator itr;
itr.Attach(spl0);
TestPointDDir(itr.m_pos, PointD(0, 0));
itr.Advance(sqrt2 * 40.0);
TestPointDDir(itr.m_pos, PointD(40, 40));
itr.Advance(sqrt2 * 40.0);
TestPointDDir(itr.m_pos, PointD(80, 0));
itr.Attach(spl4);
TestPointDDir(itr.m_pos, PointD(0, 0));
itr.Advance(sqrt2 * 40.0);
TestPointDDir(itr.m_pos, PointD(40, 40));
itr.Advance(sqrt2 * 40.0);
TestPointDDir(itr.m_pos, PointD(80, 0));
path.clear();
path.push_back(PointD(0, 0));
path.push_back(PointD(40, 40));
path.push_back(PointD(80, 40));
path.push_back(PointD(120, 0));
Spline spl2(path);
Spline spl3 = spl2;
itr.Attach(spl3);
TestPointDDir(itr.m_pos, PointD(0, 0));
itr.Advance(sqrt2 * 80.0 + 40.0);
TestPointDDir(itr.m_pos, PointD(120, 0));
itr.Attach(spl2);
itr.Advance(sqrt2 * 40.0);
TestPointDDir(itr.m_pos, PointD(40, 40));
itr.Advance(2.0);
TestPointDDir(itr.m_pos, PointD(42, 40));
itr.Advance(20.0);
TestPointDDir(itr.m_pos, PointD(62, 40));
itr.Advance(18.0);
TestPointDDir(itr.m_pos, PointD(80, 40));
}
UNIT_TEST(BeginAgain)
{
vector<PointD> path;
path.push_back(PointD(0, 0));
path.push_back(PointD(40, 40));
path.push_back(PointD(80, 0));
Spline spl(path);
double const sqrt2 = sqrtf(2.0);
Spline::iterator itr;
PointD dir1(sqrt2 / 2.0, sqrt2 / 2.0);
PointD dir2(sqrt2 / 2.0, -sqrt2 / 2.0);
itr.Attach(spl);
TEST_EQUAL(itr.BeginAgain(), false, ());
itr.Advance(90.0);
TEST_EQUAL(itr.BeginAgain(), false, ());
itr.Advance(90.0);
TEST_EQUAL(itr.BeginAgain(), true, ());
itr.Advance(190.0);
TEST_EQUAL(itr.BeginAgain(), true, ());
path.clear();
path.push_back(PointD(0, 0));
path.push_back(PointD(40, 40));
path.push_back(PointD(80, 40));
path.push_back(PointD(120, 0));
Spline spl2(path);
itr.Attach(spl2);
TEST_EQUAL(itr.BeginAgain(), false, ());
itr.Advance(90.0);
TEST_EQUAL(itr.BeginAgain(), false, ());
itr.Advance(90.0);
TEST_EQUAL(itr.BeginAgain(), true, ());
itr.Advance(190.0);
TEST_EQUAL(itr.BeginAgain(), true, ());
}
UNIT_TEST(Length)
{
vector<PointD> path;
PointD const p1(27.5536633, 64.2492523);
PointD const p2(27.5547638, 64.2474289);
PointD const p3(27.5549412, 64.2471237);
PointD const p4(27.5559044, 64.2456436);
PointD const p5(27.556284, 64.2451782);
path.push_back(p1);
path.push_back(p2);
path.push_back(p3);
path.push_back(p4);
path.push_back(p5);
Spline spl(path);
double len1 = spl.GetLength();
double l1 = p1.Length(p2);
double l2 = p2.Length(p3);
double l3 = p3.Length(p4);
double l4 = p4.Length(p5);
double len2 = l1 + l2 + l3 + l4;
TEST_ALMOST_EQUAL_ULPS(len1, len2, ());
}
| 25.768116 | 58 | 0.666104 | marceldallagnol |
2dd96491a82cbd24336742059e85bb7440310571 | 203 | hpp | C++ | demos/sjtwo/sd_card/project_config.hpp | SJSURoboticsTeam/urc-control_systems-2020 | 35dff34c1bc0beecc94ad6b8f2d4b551969c6854 | [
"Apache-2.0"
] | 6 | 2020-06-20T23:56:42.000Z | 2021-12-18T08:13:54.000Z | demos/sjtwo/sd_card/project_config.hpp | SJSURoboticsTeam/urc-control_systems-2020 | 35dff34c1bc0beecc94ad6b8f2d4b551969c6854 | [
"Apache-2.0"
] | 153 | 2020-06-09T14:49:29.000Z | 2022-01-31T16:39:39.000Z | demos/sjtwo/sd_card/project_config.hpp | SJSURoboticsTeam/urc-control_systems-2020 | 35dff34c1bc0beecc94ad6b8f2d4b551969c6854 | [
"Apache-2.0"
] | 10 | 2020-08-02T00:55:38.000Z | 2022-01-24T23:06:51.000Z | #pragma once
// Change the "#if 0" to "#if 1" below to see debug information for every
// step of the SD card communication
#if 1
#define SJ2_LOG_LEVEL SJ2_LOG_LEVEL_DEBUG
#endif
#include "config.hpp"
| 20.3 | 73 | 0.743842 | SJSURoboticsTeam |
2ddb3df5d95cfe1b477fb6c53a77c1e7b6a867da | 94 | cpp | C++ | modules/engine/src/Render/Palette/Palette.cpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | 1 | 2016-11-12T02:43:29.000Z | 2016-11-12T02:43:29.000Z | modules/engine/src/Render/Palette/Palette.cpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | null | null | null | modules/engine/src/Render/Palette/Palette.cpp | litty-studios/randar | 95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b | [
"MIT"
] | null | null | null | #include <randar/Render/Palette/Palette.hpp>
// Destructor.
randar::Palette::~Palette()
{
}
| 11.75 | 44 | 0.702128 | litty-studios |
2ddba606153d5f8e2d02c84989be9b1f70aede63 | 2,122 | cpp | C++ | tests/messaging/test_call_many.cpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 61 | 2015-01-08T08:05:28.000Z | 2022-01-07T16:47:47.000Z | tests/messaging/test_call_many.cpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 30 | 2015-04-06T21:41:18.000Z | 2021-08-18T13:24:51.000Z | tests/messaging/test_call_many.cpp | arntanguy/libqi | 7f3e1394cb26126b26fa7ff54d2de1371a1c9f96 | [
"BSD-3-Clause"
] | 64 | 2015-02-23T20:01:11.000Z | 2022-03-14T13:31:20.000Z | /*
** Copyright (C) 2012 Aldebaran Robotics
*/
#include <map>
#include <qi/application.hpp>
#include <qi/anyobject.hpp>
#include <qi/type/dynamicobjectbuilder.hpp>
#include <qi/session.hpp>
#include <testsession/testsessionpair.hpp>
#include <qi/testutils/testutils.hpp>
#include <gtest/gtest.h>
qi::AnyObject oclient1, oclient2;
static qi::Promise<bool> payload;
void onFire1(const int& pl)
{
if (pl)
oclient2.async<void>("onFire2", pl-1);
else
payload.setValue(true);
}
void onFire2(const int& pl)
{
if (pl)
oclient1.async<void>("onFire1", pl-1);
else
payload.setValue(true);
}
TEST(Test, Recurse)
{
payload = qi::Promise<bool>();
TestSessionPair p1;
TestSessionPair p2(TestSessionPair::ShareServiceDirectory, p1);
qi::DynamicObjectBuilder ob1, ob2;
ob1.advertiseMethod("onFire1", &onFire1);
ob2.advertiseMethod("onFire2", &onFire2);
qi::AnyObject oserver1(ob1.object()), oserver2(ob2.object());
unsigned int nbServices = TestMode::getTestMode() == TestMode::Mode_Nightmare ? 2 : 1;
// Two objects with a fire event and a onFire method.
ASSERT_TRUE(test::finishesWithValue(p1.server()->registerService("coin1", oserver1)));
ASSERT_TRUE(test::finishesWithValue(p2.server()->registerService("coin2", oserver2)));
EXPECT_EQ(nbServices, p1.server()->services(qi::Session::ServiceLocality_Local).value().size());
EXPECT_EQ(nbServices, p2.server()->services(qi::Session::ServiceLocality_Local).value().size());
ASSERT_TRUE(test::finishesWithValue(p2.client()->waitForService("coin1")));
ASSERT_TRUE(test::finishesWithValue(p1.client()->waitForService("coin2")));
oclient1 = p2.client()->service("coin1").value();
oclient2 = p1.client()->service("coin2").value();
int niter = 1000;
if (TestMode::getTestMode() == TestMode::Mode_SSL)
{
niter /= 100;
}
if (getenv("VALGRIND"))
{
std::cerr << "Valgrind detected, reducing iteration count" << std::endl;
niter = 50;
}
oclient1.call<void>("onFire1", niter);
ASSERT_TRUE(test::finishesWithValue(payload.future()));
oclient1.reset();
oclient2.reset();
}
| 29.887324 | 98 | 0.694628 | arntanguy |
2ddd8a850b2a9319a6f723ad224f57a35e38a7d5 | 10,532 | cpp | C++ | src/check/proof.cpp | arpj-rebola/rupee-old | b00351cbd3173d329ea183e08c3283c6d86d18a1 | [
"MIT"
] | null | null | null | src/check/proof.cpp | arpj-rebola/rupee-old | b00351cbd3173d329ea183e08c3283c6d86d18a1 | [
"MIT"
] | null | null | null | src/check/proof.cpp | arpj-rebola/rupee-old | b00351cbd3173d329ea183e08c3283c6d86d18a1 | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <iostream>
#include "core.hpp"
#include "proof.hpp"
#include "database.hpp"
//************************************************************
// Class ClauseArray
//************************************************************
// Builders
ClauseArray::ClauseArray(std::uint32_t capacity) :
m_array(nullptr),
m_size(0U),
m_capacity(capacity),
m_balanced(capacity)
{
m_array = static_cast<Short*>(std::malloc(m_capacity * sizeof(Short)));
if(m_array == nullptr) {
Core::fail("Allocation error");
}
}
ClauseArray::~ClauseArray() {
if(m_array != nullptr) {
std::free(m_array);
}
}
//------------------------------------------------------------
// Interface methods
void ClauseArray::insertClause(ClauseIterator& it) {
while(!it.end()) {
insert(it.get());
it.next();
}
}
void ClauseArray::insertResolvent(ClauseIterator& it1, ClauseIterator& it2, Short pivot) {
Short literal;
while(!it1.end()) {
if((literal = it1.get()) != pivot) {
insert(literal);
}
it1.next();
}
pivot = Shortie::complement(pivot);
while(!it2.end()) {
if((literal = it2.get()) != pivot) {
insert(literal);
}
it2.next();
}
}
void ClauseArray::reverseClause(ClauseIterator& it) {
while(!it.end()) {
insert(Shortie::complement(it.get()));
it.next();
}
}
void ClauseArray::reverseResolvent(ClauseIterator& it1, ClauseIterator& it2, Short pivot) {
Short literal;
while(!it1.end()) {
if((literal = it1.get()) != pivot) {
insert(Shortie::complement(literal));
}
it1.next();
}
pivot = Shortie::complement(pivot);
while(!it2.end()) {
if((literal = it2.get()) != pivot) {
insert(Shortie::complement(literal));
}
it2.next();
}
}
void ClauseArray::propagateClause(ClauseIterator& it) {
Short literal = Falsified;
Short propagation = Falsified;
while(!it.end()) {
literal = it.get();
if(!m_balanced.contains(Shortie::complement(literal))) {
if(propagation != Falsified) {
return;
}
propagation = literal;
}
it.next();
}
if(propagation == Falsified) {
propagation = literal;
}
if(propagation != Falsified) {
insert(propagation);
}
}
bool ClauseArray::containsReversed(ClauseIterator& it) {
while(!it.end()) {
if(!contains(Shortie::complement(it.get()))) {
return false;
}
it.next();
}
return true;
}
bool ClauseArray::containsReversedResolvent(ClauseIterator& it1, ClauseIterator& it2, Short pivot) {
Short literal;
while(!it1.end()) {
if((literal = it1.get()) != pivot) {
if(!contains(Shortie::complement(it1.get()))) {
return false;
}
}
it1.next();
}
pivot = Shortie::complement(pivot);
while(!it2.end()) {
if((literal = it2.get()) != pivot) {
if(!contains(Shortie::complement(it2.get()))) {
return false;
}
}
it2.next();
}
return true;
}
bool ClauseArray::upModels(ClauseIterator& it) {
Short found = Falsified;
Short literal;
while(!it.end()) {
literal = it.get();
if(!contains(Shortie::complement(literal))) {
if(contains(literal)) {
return true;
} else if(found == Falsified) {
found = literal;
} else {
return true;
}
}
it.next();
}
return false;
}
bool ClauseArray::tautology() {
return m_balanced.tautology();
}
void ClauseArray::reset() {
m_balanced.reset(m_array, m_size);
m_size = 0U;
}
//------------------------------------------------------------
// Private methods
bool ClauseArray::contains(Short literal) {
return fits(literal) && m_balanced.contains(literal);
}
void ClauseArray::insert(Short literal) {
if(m_balanced.insert(literal)) {
if(full()) {
reallocate();
}
m_array[m_size++] = literal;
}
}
bool ClauseArray::full() {
return m_size >= m_capacity;
}
bool ClauseArray::fits(Short literal) {
return literal < m_capacity;
}
void ClauseArray::reallocate() {
m_capacity *= ReallocationFactor;
m_array = static_cast<Short*>(std::realloc(m_array, m_capacity * sizeof(Short)));
if(m_array == nullptr) {
Core::fail("Reallocation error");
}
}
//************************************************************
// Class LratInference
//************************************************************
// Builders
LratInference::LratInference(Long clause) :
m_kind(PremiseKind),
m_clause(clause),
m_chain(NoRun),
m_resolvents(NoRun),
m_deletion(NoRun)
{}
LratInference::LratInference(std::int32_t kind, Long clause, Long chain) :
m_kind(kind),
m_clause(clause),
m_chain(chain),
m_resolvents(NoRun),
m_deletion(NoRun)
{}
//------------------------------------------------------------
// Interface methods
void LratInference::addResolvents(Long resolvents) {
if(m_resolvents == NoRun) {
m_resolvents = resolvents;
} else {
Core::invalid("Duplicated resolvent chain assigned to instruction");
}
}
void LratInference::addDeletion(Long deletion) {
if(m_deletion == NoRun) {
m_deletion = deletion;
} else {
Core::invalid("Duplicated deletion chain assigned to instruction");
}
}
bool LratInference::isPremise() {
return m_kind == PremiseKind;
}
bool LratInference::isRup() {
return m_kind == RupKind;
}
bool LratInference::isRat() {
return m_kind == RatKind;
}
Long LratInference::getClause() {
return m_clause;
}
Long LratInference::getChain() {
return m_chain;
}
Long LratInference::getResolvents() {
return m_resolvents;
}
Long LratInference::getDeletion() {
return m_deletion;
}
//************************************************************
// Class LratProof
//************************************************************
// Builders
LratProof::LratProof(std::uint32_t capacity) :
m_array(nullptr),
m_size(0U),
m_capacity(capacity),
m_iterator(0U)
{
m_array = static_cast<LratInference*>(std::malloc(m_capacity * sizeof(LratInference)));
if(m_array == nullptr) {
Core::fail("Allocation error");
}
}
LratProof::~LratProof() {
if(m_array != nullptr) {
std::free(m_array);
}
}
//------------------------------------------------------------
// Interface methods
std::uint32_t LratProof::insertPremise(Long clause) {
insert(LratInference(clause));
return m_size - 1;
}
std::uint32_t LratProof::insertRup(Long clause, Long chain) {
insert(LratInference(LratInference::RupKind, clause, chain));
return m_size - 1;
}
std::uint32_t LratProof::insertRat(Long clause, Long chain) {
insert(LratInference(LratInference::RatKind, clause, chain));
return m_size - 1;
}
void LratProof::addResolventChain(std::uint32_t inference, Long chain) {
m_array[inference].addResolvents(chain);
}
void LratProof::addDeletionChain(std::uint32_t inference, Long chain) {
m_array[inference].addDeletion(chain);
}
bool LratProof::end() {
return m_iterator >= m_size;
}
void LratProof::next() {
++m_iterator;
}
LratInference& LratProof::get() {
return m_array[m_iterator];
}
//------------------------------------------------------------
// Private methods
void LratProof::insert(const LratInference& inf) {
if(full()) {
reallocate();
}
m_array[m_size++] = inf;
}
void LratProof::reallocate() {
m_capacity *= ReallocationFactor;
m_array = static_cast<LratInference*>(std::realloc(m_array, m_capacity * sizeof(LratInference)));
if(m_array == nullptr) {
Core::fail("Reallocation error");
}
}
bool LratProof::full() {
return m_size >= m_capacity;
}
//************************************************************
// Class DratInference
//************************************************************
// Builders
DratInference::DratInference(std::int32_t kind, Long clause, Short pivot) :
m_kind(kind),
m_clause(clause),
m_pivot(pivot)
{}
//------------------------------------------------------------
// Interface methods
bool DratInference::isPremise() {
return m_kind == PremiseKind;
}
bool DratInference::isIntroduction() {
return m_kind == IntroductionKind;
}
bool DratInference::isDeletion() {
return m_kind == DeletionKind;
}
Long DratInference::getClause() {
return m_clause;
}
Short DratInference::getPivot() {
return m_pivot;
}
//************************************************************
// Class DratInference
//************************************************************
// Builders
DratProof::DratProof(std::uint32_t capacity) :
m_array(nullptr),
m_size(0U),
m_capacity(capacity)
{
m_array = static_cast<DratInference*>(std::malloc(m_capacity * sizeof(DratInference)));
if(m_array == nullptr) {
Core::fail("Allocation error");
}
}
DratProof::~DratProof() {
if(m_array != nullptr) {
std::free(m_array);
}
}
//------------------------------------------------------------
// Interface methods
std::uint32_t DratProof::insertPremise(Long clause) {
insert(DratInference(DratInference::PremiseKind, clause, Shortie::NegativeZero));
return m_size - 1;
}
std::uint32_t DratProof::insertIntroduction(Long clause, Short pivot) {
insert(DratInference(DratInference::IntroductionKind, clause, pivot));
return m_size - 1;
}
std::uint32_t DratProof::insertDeletion(Long clause) {
insert(DratInference(DratInference::DeletionKind, clause, Shortie::NegativeZero));
return m_size - 1;
}
void DratProof::accumulateFormula(std::uint32_t index, ClauseDatabase& db) {
if(index - 1 >= m_size || index - 1 < 0) {
Core::invalid("Instruction index in SICK file does not correspond to a DRAT proof instruction");
return;
}
for(std::uint32_t i = 0U; i < index - 1; ++i) {
DratInference& inference = m_array[i];
db.setActivity(inference.getClause(), !(inference.isDeletion()));
}
}
DratInference DratProof::getInstruction(std::uint32_t index) {
return m_array[index - 1];
}
//------------------------------------------------------------
// Private methods
void DratProof::insert(const DratInference& inf) {
if(full()) {
reallocate();
}
m_array[m_size++] = inf;
}
void DratProof::reallocate() {
m_capacity *= ReallocationFactor;
m_array = static_cast<DratInference*>(std::realloc(m_array, m_capacity * sizeof(DratInference)));
if(m_array == nullptr) {
Core::fail("Reallocation error");
}
}
bool DratProof::full() {
return m_size >= m_capacity;
}
//************************************************************
// Class SickInstruction
//************************************************************
Short& SickInstruction::pivot() {
return m_pivot;
}
std::uint32_t& SickInstruction::instruction() {
return m_instruction;
}
Long& SickInstruction::naturalClause() {
return m_natclause;
}
Long& SickInstruction::naturalModel() {
return m_natmodel;
}
Long& SickInstruction::resolventClause() {
return m_resclause;
}
Long& SickInstruction::resolventModel() {
return m_resmodel;
}
| 21.537832 | 100 | 0.612704 | arpj-rebola |
2de31312bac455bb206107872c7c3c2c92cc9ff4 | 1,806 | cpp | C++ | C++/src/biopsy/gapped_pssm/gapped_pssm_test.cpp | JohnReid/biopsy | 1eeb714ba5b53f2ecf776d865d32e2078cbc0338 | [
"MIT"
] | null | null | null | C++/src/biopsy/gapped_pssm/gapped_pssm_test.cpp | JohnReid/biopsy | 1eeb714ba5b53f2ecf776d865d32e2078cbc0338 | [
"MIT"
] | null | null | null | C++/src/biopsy/gapped_pssm/gapped_pssm_test.cpp | JohnReid/biopsy | 1eeb714ba5b53f2ecf776d865d32e2078cbc0338 | [
"MIT"
] | null | null | null |
#include "biopsy/gapped_pssm.h"
#include <boost/test/unit_test.hpp>
#include <boost/test/parameterized_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/assign/list_of.hpp>
using namespace boost;
using namespace boost::assign;
using boost::unit_test::test_suite;
#include <iostream>
using namespace std;
//#define VERBOSE_CHECKING
typedef std::vector< std::string > string_vec;
typedef std::vector< string_vec > string_vec_vec;
string_vec_vec test_seqs = list_of< string_vec >
(
list_of< std::string >
( "gaaaac" )
( "aacaat" )
( "aacaat" )
( "aacaag" )
( "aaaatc" )
( "anaacg" )
)
(
list_of< std::string >
( "ttttt" )
( "aaaaa" )
)
;
void
check_gapped_pssm( const string_vec & test_seqs )
{
cout << "******* check_gapped_pssm()" << endl;
using namespace biopsy;
using namespace biopsy::gapped_pssm;
dna_vec_list seqs( test_seqs.size() );
for( unsigned i = 0; test_seqs.size() != i; ++i )
{
string_to_dna_vec( test_seqs[i], seqs[i] );
}
variational_model model(
4,
seqs,
std::vector< double >( 2, 1.0 ),
std::vector< double >( 4, 10.0 ),
std::vector< double >( 4, 0.1 ) );
double ll = model.log_likelihood();
for( unsigned i = 0; 25 != i; ++i )
{
model.update();
ll = model.log_likelihood();
}
model.update();
}
void
register_compressed_int_array_tests( boost::unit_test::test_suite * test )
{
test->add(
BOOST_PARAM_TEST_CASE(
&check_gapped_pssm,
test_seqs.begin(),
test_seqs.end() ),
0);
}
test_suite*
init_unit_test_suite( int argc, char * argv [] )
{
test_suite* suite = BOOST_TEST_SUITE( "Bio test suite" );
try
{
register_compressed_int_array_tests( suite );
}
catch (const std::exception & e)
{
cerr << "Exception: " << e.what() << endl;
}
return suite;
}
| 18.06 | 74 | 0.657254 | JohnReid |
2de368037e9cbf6f6a474a1fcac22b112ca8f03a | 597 | cpp | C++ | diagonaldiff.cpp | d3cod3monk78/hackerrank | 8f3174306754d04d07b42d5c7a95ab32abf17fa1 | [
"MIT"
] | null | null | null | diagonaldiff.cpp | d3cod3monk78/hackerrank | 8f3174306754d04d07b42d5c7a95ab32abf17fa1 | [
"MIT"
] | null | null | null | diagonaldiff.cpp | d3cod3monk78/hackerrank | 8f3174306754d04d07b42d5c7a95ab32abf17fa1 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include <vector>
#include <cstdlib>
using namespace std;
typedef long long int ll;
ll getDiff(vector<vector<int>> arr);
ll getDiff(vector<vector<int>> arr) {
ll sum = 0;
for(ll i = 0; i < (ll)arr.size(); i++) {
sum += arr[i][i] - arr[i][(ll)arr.size() - i - 1];
}
return sum;
}
int main(int argc, char const *argv[]) {
ll n;
cin >> n;
int temp;
vector<vector<int>> arr(n);
for(ll i = 0; i < n; i++) {
arr[i] = vector<int>(n);
for(ll j = 0; j < n; j++) {
cin >> temp;
arr[i][j] = temp;
}
}
cout << abs(getDiff(arr)) << endl;
return 0;
} | 15.710526 | 52 | 0.549414 | d3cod3monk78 |
2de4e2d15a5865802088020fad5bcca7562ea53b | 3,995 | cc | C++ | src/util/LS_trends/rp.cc | mansour2014/ATSP2K_plus | 30842b9f086d1e497aeb778e2a352d1e8e520ec3 | [
"BSD-4-Clause-UC"
] | 1 | 2019-07-21T14:03:39.000Z | 2019-07-21T14:03:39.000Z | src/util/LS_trends/rp.cc | mzmansour/ATSP2K_plus | 30842b9f086d1e497aeb778e2a352d1e8e520ec3 | [
"BSD-4-Clause-UC"
] | null | null | null | src/util/LS_trends/rp.cc | mzmansour/ATSP2K_plus | 30842b9f086d1e497aeb778e2a352d1e8e520ec3 | [
"BSD-4-Clause-UC"
] | null | null | null | #include "rep_lib.hh"
#include "ls.hh"
#include <string>
#include<cmath>
string& ret_str(string& s) {
int a = s.find_first_not_of(" ");
s.erase(0,a);
a = s.find_last_not_of(" ");
s.erase(a+1);
// cout << s.size() << "::" << s << "::" << endl;
return s;
}
string& u_format(string& ss, double dr, double du) {
if (!dr && !du) {
ss = " & ";
return ss;
}
char t1[50];
std::ostrstream BUF1(t1,sizeof(t1));
BUF1.precision(3);
BUF1.setf(ios::scientific, ios::floatfield);
BUF1 << dr << ends;
string s1 = t1;
char t2[50];
std::ostrstream BUF2(t2,sizeof(t2));
BUF2.precision(3);
BUF2.setf(ios::scientific, ios::floatfield);
BUF2 << du << ends;
string s2 = t2;
char* pe1 = &t1[6];
char* pe2 = &t2[6];
istrstream ie1(pe1);
istrstream ie2(pe2);
int e1 = 0;
int e2 = 0;
ie1 >> e1;
ie2 >> e2;
char t3[10];
std::ostrstream BUF3(t3,sizeof(t3));
BUF3.precision(3);
BUF3.setf(ios::scientific, ios::floatfield);
BUF3 << e1 << ends;
string stmp = t3;
string s3("");
if (e1 < 10 && e1 > 0) s3 = " " + stmp;
else s3 = stmp;
if (!du) {
s1.erase(5,8);
ss = s1 + "(" + "-" + ")" + " & " + s3;
return ss;
}
s1.erase(5,8);
int ediff = e1 - e2;
if (ediff >= 4) {
ss = s1 + "(" + "0" + ")" + " & " + s3;
return ss;
}
double maxd = (dr <= du) ? du : dr;
double maxpd = fabs((du)/maxd)*100;
if (maxpd >= 99.99) {
char t10[50];
std::ostrstream BUF1(t10,sizeof(t10));
BUF1.precision(2);
BUF1.setf(ios::scientific, ios::floatfield);
BUF1 << dr << ends;
string s10 = t10;
s10.erase(4,7);
ss = s10 + "(" + "100\\%" + ")" + " & " + s3;
return ss;
}
if (maxpd >= 70) {
char t4[10];
char t10[50];
std::ostrstream BUF1(t10,sizeof(t10));
BUF1.precision(2);
BUF1.setf(ios::scientific, ios::floatfield);
BUF1 << dr << ends;
string s10 = t10;
s10.erase(4,7);
std::ostrstream BUF4(t4,sizeof(t4));
BUF4.precision(1);
BUF4.setf(ios::showpoint);
BUF4.setf(ios::fixed, ios::floatfield);
BUF4 << maxpd << ends;
string s4 = t4;
ss = s10 + "(" + s4 + "\\%" + ")" + " & " + s3;
return ss;
}
if (!ediff) {
char t5[10];
std::ostrstream BUF5(t5,sizeof(t5));
BUF5.precision(2);
BUF5.setf(ios::scientific, ios::floatfield);
BUF5 << dr << ends;
string s5 = t5;
s5.erase(4,7);
char t6[10];
std::ostrstream BUF6(t6,sizeof(t6));
BUF6.precision(2-ediff);
BUF6.setf(ios::showpoint);
BUF6.setf(ios::scientific, ios::floatfield);
BUF6 << du << ends;
string s6 = t6;
int SZ = s6.size();
s6.erase(SZ-4,SZ-1);
s6.erase(1,1);
if (!ediff)
ss = s5 + "(" + s6 + ")" + " & " + s3;
else ss = s5 + "(" + s6 + ")" + " & " + s3;
return ss;
}
if (ediff == 3) {
double DD(10);
int I = int(du/(pow(DD,e2)));
char t8[10];
std::ostrstream BUF8(t8,sizeof(t8));
BUF8 << I << ends;
string s8 = t8;
ss = s1 + "(" + s8 + ")" + " & " + s3;
return ss;
}
if (ediff == 2 || ediff == 1) {
char t7[10];
std::ostrstream BUF7(t7,sizeof(t7));
BUF7.precision(3-ediff);
BUF7.setf(ios::showpoint);
BUF7.setf(ios::scientific, ios::floatfield);
BUF7 << du << ends;
string s7 = t7;
int SZ = s7.size();
s7.erase(SZ-4,SZ-1);
s7.erase(1,1);
if (ediff == 2) ss = s1 + "(" + s7 + ")" + " & " + s3;
else ss = s1 + "(" + s7 + ")" + " & " + s3;
return ss;
}
// #0123456789_123456789_123456789
// #3.333e+05(4.343e+03)#
// #3.333(434) & 5 #
// #3.33(43) & 5 #
// #3.33(10\\%) & 5 #
ss = " & ";
return ss;
}
| 24.212121 | 64 | 0.463079 | mansour2014 |
2de62dcc70ac4b26a94f7541a6a172636c76ce7c | 6,996 | cc | C++ | src/memory/ReproCartridgeV1.cc | imulilla/openMSX_TSXadv_nofork | 4ee003d87a44633c14c054bd59ec2bfd866e5d9f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/memory/ReproCartridgeV1.cc | imulilla/openMSX_TSXadv_nofork | 4ee003d87a44633c14c054bd59ec2bfd866e5d9f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/memory/ReproCartridgeV1.cc | imulilla/openMSX_TSXadv_nofork | 4ee003d87a44633c14c054bd59ec2bfd866e5d9f | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | #include "ReproCartridgeV1.hh"
#include "DummyAY8910Periphery.hh"
#include "MSXCPUInterface.hh"
#include "serialize.hh"
#include <vector>
/******************************************************************************
* DOCUMENTATION AS PROVIDED BY MANUEL PAZOS, WHO DEVELOPED THE CARTRIDGE *
******************************************************************************
Repro Cartridge version 1 is similar to Konami Ultimate Collection. It
uses the same flashROM, SCC/SCC+. But it only supports Konami SCC mapper.
Released were cartridges with the following content (at least): only Metal
Gear, only Metal Gear 2
[REGISTER (#7FFF)]
If it contains value 0x50, the flash is writable and the mapper is disabled.
Otherwise, the mapper is enabled and the flash is readonly.
- Mapper supports 4 different ROMs of 2MB each, with the KonamiSCC mapper
- Cartridge has a PSG at 0x10, write only
- On I/O port 0x13 the 2MB block can be selected (default 0, so up to 3)
******************************************************************************/
namespace openmsx {
static std::vector<AmdFlash::SectorInfo> getSectorInfo()
{
std::vector<AmdFlash::SectorInfo> sectorInfo;
// 8 * 8kB
sectorInfo.insert(end(sectorInfo), 8, {8 * 1024, false});
// 127 * 64kB
sectorInfo.insert(end(sectorInfo), 127, {64 * 1024, false});
return sectorInfo;
}
ReproCartridgeV1::ReproCartridgeV1(
const DeviceConfig& config, Rom&& rom_)
: MSXRom(config, std::move(rom_))
, flash(rom, getSectorInfo(), 0x207E, true, config, false)
, scc("MGCV1 SCC", config, getCurrentTime(), SCC::SCC_Compatible)
, psg("MGCV1 PSG", DummyAY8910Periphery::instance(), config,
getCurrentTime())
{
powerUp(getCurrentTime());
getCPUInterface().register_IO_Out(0x10, this);
getCPUInterface().register_IO_Out(0x11, this);
getCPUInterface().register_IO_Out(0x13, this);
}
ReproCartridgeV1::~ReproCartridgeV1()
{
getCPUInterface().unregister_IO_Out(0x10, this);
getCPUInterface().unregister_IO_Out(0x11, this);
getCPUInterface().unregister_IO_Out(0x13, this);
}
void ReproCartridgeV1::powerUp(EmuTime::param time)
{
scc.powerUp(time);
reset(time);
}
void ReproCartridgeV1::reset(EmuTime::param time)
{
flashRomWriteEnabled = false;
mainBankReg = 0;
sccMode = 0;
for (int bank = 0; bank < 4; ++bank) {
bankRegs[bank] = bank;
}
scc.reset(time);
psgLatch = 0;
psg.reset(time);
flash.reset();
invalidateDeviceRCache(); // flush all to be sure
}
unsigned ReproCartridgeV1::getFlashAddr(unsigned addr) const
{
unsigned page8kB = (addr >> 13) - 2;
if (page8kB >= 4) return unsigned(-1); // outside [0x4000, 0xBFFF]
byte bank = bankRegs[page8kB]; // 2MB max
return (mainBankReg << 21) | (bank << 13) | (addr & 0x1FFF);
}
// Note: implementation (mostly) copied from KUC
bool ReproCartridgeV1::isSCCAccess(word addr) const
{
if (sccMode & 0x10) return false;
if (addr & 0x0100) {
// Address bit 8 must be zero, this is different from a real
// SCC/SCC+. According to Manuel Pazos this is a leftover from
// an earlier version that had 2 SCCs: the SCC on the left or
// right channel reacts when address bit 8 is respectively 0/1.
return false;
}
if (sccMode & 0x20) {
// SCC+ range: 0xB800..0xBFFF, excluding 0xBFFE-0xBFFF
return (bankRegs[3] & 0x80) && (0xB800 <= addr) && (addr < 0xBFFE);
} else {
// SCC range: 0x9800..0x9FFF, excluding 0x9FFE-0x9FFF
return ((bankRegs[2] & 0x3F) == 0x3F) && (0x9800 <= addr) && (addr < 0x9FFE);
}
}
byte ReproCartridgeV1::readMem(word addr, EmuTime::param time)
{
if (isSCCAccess(addr)) {
return scc.readMem(addr & 0xFF, time);
}
unsigned flashAddr = getFlashAddr(addr);
return (flashAddr != unsigned(-1))
? flash.read(flashAddr)
: 0xFF; // unmapped read
}
byte ReproCartridgeV1::peekMem(word addr, EmuTime::param time) const
{
if (isSCCAccess(addr)) {
return scc.peekMem(addr & 0xFF, time);
}
unsigned flashAddr = getFlashAddr(addr);
return (flashAddr != unsigned(-1))
? flash.peek(flashAddr)
: 0xFF; // unmapped read
}
const byte* ReproCartridgeV1::getReadCacheLine(word addr) const
{
if (isSCCAccess(addr)) return nullptr;
unsigned flashAddr = getFlashAddr(addr);
return (flashAddr != unsigned(-1))
? flash.getReadCacheLine(flashAddr)
: unmappedRead;
}
void ReproCartridgeV1::writeMem(word addr, byte value, EmuTime::param time)
{
unsigned page8kB = (addr >> 13) - 2;
if (page8kB >= 4) return; // outside [0x4000, 0xBFFF]
// There are several overlapping functional regions in the address
// space. A single write can trigger behaviour in multiple regions. In
// other words there's no priority amongst the regions where a higher
// priority region blocks the write from the lower priority regions.
// This only goes for places where the flash is 'seen', so not for the
// SCC registers
if (isSCCAccess(addr)) {
scc.writeMem(addr & 0xFF, value, time);
return; // write to SCC blocks write to other functions
}
// address is calculated before writes to other regions take effect
unsigned flashAddr = getFlashAddr(addr);
// Main mapper register
if (addr == 0x7FFF) {
flashRomWriteEnabled = (value == 0x50);
invalidateDeviceRCache(); // flush all to be sure
}
if (!flashRomWriteEnabled) {
// Konami-SCC
if ((addr & 0x1800) == 0x1000) {
// [0x5000,0x57FF] [0x7000,0x77FF]
// [0x9000,0x97FF] [0xB000,0xB7FF]
bankRegs[page8kB] = value;
invalidateDeviceRCache(0x4000 + 0x2000 * page8kB, 0x2000);
}
// SCC mode register
if ((addr & 0xFFFE) == 0xBFFE) {
sccMode = value;
scc.setChipMode((value & 0x20) ? SCC::SCC_plusmode
: SCC::SCC_Compatible);
invalidateDeviceRCache(0x9800, 0x800);
invalidateDeviceRCache(0xB800, 0x800);
}
} else {
if (flashAddr != unsigned(-1)) {
flash.write(flashAddr, value);
}
}
}
byte* ReproCartridgeV1::getWriteCacheLine(word addr) const
{
return ((0x4000 <= addr) && (addr < 0xC000))
? nullptr // [0x4000,0xBFFF] isn't cacheable
: unmappedWrite;
}
void ReproCartridgeV1::writeIO(word port, byte value, EmuTime::param time)
{
switch (port & 0xFF)
{
case 0x10:
psgLatch = value & 0x0F;
break;
case 0x11:
psg.writeRegister(psgLatch, value, time);
break;
case 0x13:
mainBankReg = value & 3;
invalidateDeviceRCache(); // flush all to be sure
break;
default: UNREACHABLE;
}
}
template<typename Archive>
void ReproCartridgeV1::serialize(Archive& ar, unsigned /*version*/)
{
// skip MSXRom base class
ar.template serializeBase<MSXDevice>(*this);
ar.serialize("flash", flash,
"scc", scc,
"psg", psg,
"psgLatch", psgLatch,
"flashRomWriteEnabled", flashRomWriteEnabled,
"mainBankReg", mainBankReg,
"sccMode", sccMode,
"bankRegs", bankRegs);
}
INSTANTIATE_SERIALIZE_METHODS(ReproCartridgeV1);
REGISTER_MSXDEVICE(ReproCartridgeV1, "ReproCartridgeV1");
} // namespace openmsx
| 28.555102 | 79 | 0.665666 | imulilla |
2de70533ced990658f049ae0190745fe7e8b51cb | 5,711 | cpp | C++ | libdsd/src/CDFFFile.cpp | xlm04322/dsd-dop-from-kpidsd | 2fe6916b1a5e3194d65b3d59528b3e053c9a9f50 | [
"MIT"
] | 2 | 2019-03-12T18:14:52.000Z | 2021-12-13T13:08:24.000Z | libdsd/src/CDFFFile.cpp | xlm04322/dsd-dop-from-kpidsd | 2fe6916b1a5e3194d65b3d59528b3e053c9a9f50 | [
"MIT"
] | null | null | null | libdsd/src/CDFFFile.cpp | xlm04322/dsd-dop-from-kpidsd | 2fe6916b1a5e3194d65b3d59528b3e053c9a9f50 | [
"MIT"
] | 4 | 2016-09-21T20:24:16.000Z | 2021-04-10T08:24:55.000Z | #include "stdafx.h"
#include "CDFFFile.h"
CDFFFile::CDFFFile() : CLargeFile()
{
}
CDFFFile::~CDFFFile()
{
}
void CDFFFile::Close()
{
CLargeFile::Close();
}
bool CDFFFile::readChunkHeader(DFFChunkHeader& header, ChunkStep& step)
{
DWORD dwBytesRead = 0;
step.headerOffset = Tell();
if (!Read(&header, sizeof header, &dwBytesRead) || dwBytesRead != sizeof header)
return false;
header.ckID = ntohl(header.ckID);
header.ckDataSize = ntohll(header.ckDataSize);
step.header = header;
step.dataOffset = Tell();
step.dataEndOffset = step.dataOffset + step.header.ckDataSize + (step.header.ckDataSize & 1);
return true;
}
BOOL CDFFFile::Open(CAbstractFile* file)
{
ChunkStep step;
DFFChunkHeader hdr;
hFile = file;
while (readChunkHeader(hdr, step))
{
DFFID parentID = stack.empty() ? 0x0000 : stack.top().header.ckID;
bool handled = false;
stack.push(step);
handled = handled || readFRM8(step, hdr);
handled = handled || readPROP(step, hdr);
handled = handled || readDIIN(step, hdr);
if (!handled)
{
// default action -- skip that chunk
Seek(step.dataEndOffset, NULL, FILE_BEGIN);
stack.pop();
}
}
stack.pop();
if (!stack.empty())
{
// invalid stack state -- hiearchy mismatch
}
return TRUE;
}
bool CDFFFile::readFRM8(ChunkStep& step, DFFChunkHeader& hdr)
{
switch (hdr.ckID)
{
case DFFID_FRM8:
{
frm8.header = hdr;
frm8.offsetToData = step.dataOffset;
Read(&frm8.data, sizeof frm8.data, NULL);
frm8.setupData();
// descend to subchunks
break;
}
case DFFID_FVER:
{
Read(&frm8.fver.data, sizeof frm8.fver.data, NULL);
frm8.fver.setupData();
stack.pop(); // ascend to parent (FRM8) chunk
break;
}
case DFFID_DSD_:
{
frm8.dsd.header = hdr;
frm8.dsd.offsetToData = step.dataOffset;
Seek(step.dataEndOffset, NULL, FILE_BEGIN);
stack.pop(); // ascend to parent (FRM8) chunk
break;
}
case DFFID_COMT:
{
frm8.comt.header = hdr;
frm8.comt.offsetToData = step.dataOffset;
Read(&frm8.comt.data, sizeof frm8.comt.data, NULL);
frm8.comt.setupData();
for (uint32_t i = 0; i < frm8.comt.data.numComments; i++)
{
Comment comment;
Read(&comment.data, sizeof comment.data, NULL);
comment.setupData();
assignBuffer(comment.data.count, comment.commentText);
frm8.comt.comments.push_back(comment);
}
Seek(step.dataEndOffset, NULL, FILE_BEGIN); // may contain padding byte(s)
stack.pop(); // ascend to parent (FRM8) chunk
break;
}
case DFFID_DST_:
case DFFID_DSTI:
case DFFID_MANF:
default:
return false;
}
return true;
}
bool CDFFFile::readPROP(ChunkStep& step, DFFChunkHeader& hdr)
{
switch (hdr.ckID)
{
case DFFID_PROP:
{
frm8.prop.header = hdr;
frm8.prop.offsetToData = step.dataOffset;
Read(&frm8.prop.data, sizeof frm8.prop.data, NULL);
frm8.prop.setupData();
// descend to subchunks
break;
}
case DFFID_FS__:
frm8.prop.fs.header = hdr;
frm8.prop.fs.offsetToData = step.dataOffset;
Read(&frm8.prop.fs.data, sizeof frm8.prop.fs.data, NULL);
frm8.prop.fs.setupData();
stack.pop(); // ascend to parent (PROP) chunk
break;
case DFFID_CHNL:
frm8.prop.chnl.header = hdr;
frm8.prop.chnl.offsetToData = step.dataOffset;
Read(&frm8.prop.chnl.data, sizeof frm8.prop.chnl.data, NULL);
frm8.prop.chnl.setupData();
for (int i = 0; i < frm8.prop.chnl.data.numChannels; i++)
{
DFFID id;
Read(&id, sizeof id, NULL);
id = ntohl(id);
frm8.prop.chnl.chID.push_back(id);
}
stack.pop(); // ascend to parent (PROP) chunk
break;
case DFFID_CMPR:
frm8.prop.cmpr.header = hdr;
frm8.prop.cmpr.offsetToData = step.dataOffset;
Read(&frm8.prop.cmpr.data, sizeof frm8.prop.cmpr.data, NULL);
frm8.prop.cmpr.setupData();
assignBuffer(frm8.prop.cmpr.data.count, frm8.prop.cmpr.compressionName);
Seek(step.dataEndOffset, NULL, FILE_BEGIN);
stack.pop(); // ascend to parent (PROP) chunk
break;
case DFFID_ABSS:
frm8.prop.abss.header = hdr;
frm8.prop.abss.offsetToData = step.dataOffset;
Read(&frm8.prop.abss.data, sizeof frm8.prop.abss.data, NULL);
frm8.prop.abss.setupData();
stack.pop(); // ascend to parent (PROP) chunk
break;
case DFFID_LSCO:
frm8.prop.lsco.header = hdr;
frm8.prop.lsco.offsetToData = step.dataOffset;
Read(&frm8.prop.lsco.data, sizeof frm8.prop.lsco.data, NULL);
frm8.prop.lsco.setupData();
stack.pop(); // ascend to parent (PROP) chunk
break;
default:
return false;
}
return true;
}
bool CDFFFile::readDIIN(ChunkStep& step, DFFChunkHeader& hdr)
{
switch (hdr.ckID)
{
case DFFID_DIIN:
{
frm8.diin.header = hdr;
frm8.diin.offsetToData = step.dataOffset;
// descend to subchunks
break;
}
case DFFID_DIAR:
{
frm8.diin.diar.header = hdr;
frm8.diin.diar.offsetToData = step.dataOffset;
Read(&frm8.diin.diar.data, sizeof frm8.diin.diar.data, NULL);
frm8.diin.diar.setupData();
assignBuffer(frm8.diin.diar.data.count, frm8.diin.diar.artistText);
Seek(step.dataEndOffset, NULL, FILE_BEGIN); // may contain padding byte
stack.pop(); // ascend to parent (DIIN) chunk
break;
}
case DFFID_DITI:
{
frm8.diin.diti.header = hdr;
frm8.diin.diti.offsetToData = step.dataOffset;
Read(&frm8.diin.diti.data, sizeof frm8.diin.diti.data, NULL);
frm8.diin.diti.setupData();
assignBuffer(frm8.diin.diti.data.count, frm8.diin.diti.titleText);
Seek(step.dataEndOffset, NULL, FILE_BEGIN); // may contain padding byte
stack.pop(); // ascend to parent (DIIN) chunk
break;
}
default:
return false;
}
return true;
}
void CDFFFile::assignBuffer(uint32_t bytesToRead, std::string& target)
{
uint8_t* buf = new uint8_t[bytesToRead + 1];
buf[bytesToRead] = '\0';
Read(buf, bytesToRead, NULL);
target.assign((const char*)buf);
delete[] buf;
}
| 23.405738 | 94 | 0.691823 | xlm04322 |
2de745d418d15862c47669ae7d5127ea94dab1f4 | 2,578 | cpp | C++ | ode.cpp | wo3kie/cxxDojo | c63388eb37a62272bfb9ca5c0b207fc5387a29ad | [
"MIT"
] | 2 | 2015-10-26T22:06:11.000Z | 2015-11-25T14:35:00.000Z | ode.cpp | wo3kie/dojo | c63388eb37a62272bfb9ca5c0b207fc5387a29ad | [
"MIT"
] | null | null | null | ode.cpp | wo3kie/dojo | c63388eb37a62272bfb9ca5c0b207fc5387a29ad | [
"MIT"
] | null | null | null | /*
* Website:
* https://github.com/wo3kie/dojo
*
* Author:
* Lukasz Czerwinski
*
* Compilation:
* g++ --std=c++11 ode.euler.cpp -o ode.euler
*
* Usage:
* $ ./ode.euler
*/
#include <cassert>
#include <functional>
#include "./feq.hpp"
double solveOdeImpl(
std::function<double (double, double, double)> approx,
double x0,
double const xN,
double const h,
double y0
){
while(x0 + h <= xN){
y0 += approx(x0, x0 + h, y0);
x0 += h;
}
return y0;
}
double solveOdeEulerForward(
std::function<double (double, double)> f,
double x0,
double xN,
double h,
double y0
){
auto approx = [&f](double x0, double x1, double y){
double const h = x1 - x0;
return h * f(x0, y);
};
return solveOdeImpl(approx, x0, xN, h, y0);
}
double solveOdeEulerMidpoint(
std::function<double (double, double)> f,
double x0,
double xN,
double h,
double y0
){
auto approx = [&f](double x0, double x1, double y){
double const h = (x1 - x0);
double const k1 = h * f(x0, y);
double const k2 = h * f(x0 + h/2, y + h * k1/2);
return k2;
};
return solveOdeImpl(approx, x0, xN, h, y0);
}
double solveOdeTrapezoid(
std::function<double (double, double)> f,
double x0,
double xN,
double h,
double y0
){
auto approx = [&f](double x0, double x1, double y){
double const h = (x1 - x0);
double const x0Slope = h * f(x0, y);
double const x1Slope = h * f(x1, y + h * f(x0, y));
return (x0Slope + x1Slope) / 2;
};
return solveOdeImpl(approx, x0, xN, h, y0);
}
double solveOdeRungeKutta4(
std::function<double (double, double)> f,
double x0,
double xN,
double h,
double y0
){
auto approx = [&f](double x0, double x1, double y){
double const h = (x1 - x0);
double const k1 = h * f(x0, y);
double const k2 = h * f(x0 + h/2, y + k1/2);
double const k3 = h * f(x0 + h/2, y + k2/2);
double const k4 = h * f(x0 + h, y + k3);
return (k1 + 2*k2 + 2*k3 + k4) / 6;
};
return solveOdeImpl(approx, x0, xN, h, y0);
}
double f(double x, double y){
// f(x) = 3x^3
// f'(x) = x * x
return x * x;
}
#include <iostream>
int main(){
assert(feq(8.6950, solveOdeEulerForward(f, 0, 3, 0.3, 1)));
assert(feq(10.045, solveOdeTrapezoid(f, 0, 3, 0.3, 1)));
assert(feq(9.9775, solveOdeEulerMidpoint(f, 0, 3, 0.3, 1)));
assert(feq(10.000, solveOdeRungeKutta4(f, 0, 3, 0.3, 1)));
}
| 21.847458 | 64 | 0.544996 | wo3kie |
2de7ccebe28966caf94c5bd7ec391367006e19b2 | 6,219 | hpp | C++ | openstudiocore/src/model/AirLoopHVACOutdoorAirSystem.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | 1 | 2016-12-29T08:45:03.000Z | 2016-12-29T08:45:03.000Z | openstudiocore/src/model/AirLoopHVACOutdoorAirSystem.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | openstudiocore/src/model/AirLoopHVACOutdoorAirSystem.hpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2016, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library 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 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef MODEL_AIRLOOPHVACOUTDOORAIRSYSTEM_HPP
#define MODEL_AIRLOOPHVACOUTDOORAIRSYSTEM_HPP
#include "ModelAPI.hpp"
#include "HVACComponent.hpp"
#include "StraightComponent.hpp"
#include "Connection.hpp"
namespace openstudio {
namespace model {
namespace detail {
class AirLoopHVACOutdoorAirSystem_Impl;
} // detail
class AvailabilityManagerScheduled;
class ControllerOutdoorAir;
class Node;
/** AirLoopHVACOutdoorAirSystem is an HVACComponent that wraps the IDD object
* named "OS:AirLoopHVAC:OutdoorAirSystem"
*
* The purpose of this class is to simplify the construction and manipulation
* of the EnergyPlus AirLoopHVAC:OutdoorAirSystem object.
*/
class MODEL_API AirLoopHVACOutdoorAirSystem : public HVACComponent {
public:
/** Constructs a new AirLoopHVACOutdoorAirSystem object and places it inside the
* model.
*/
explicit AirLoopHVACOutdoorAirSystem(Model& model, const ControllerOutdoorAir & controller);
virtual ~AirLoopHVACOutdoorAirSystem() {}
/** Returns the return air port of the outdoor air system. */
unsigned returnAirPort() const;
/** Returns the outdoor air port of the outdoor air mixer.
* This is not the most outboard air node of the outdoor air system,
* rather it is the port directly attached to the mixer. There can be
* additional components between this port and the most outboard port.
**/
unsigned outdoorAirPort() const;
/** Returns the outdoor air port of the outdoor air system.
* This is not the most outboard air node of the outdoor air system,
* rather it is the port directly attached to the mixer. There can be
* additional components between this port and the most outboard port.
**/
unsigned reliefAirPort() const;
/** Returns the mixed air port. **/
unsigned mixedAirPort() const;
/** Returns the optional ModelObject attached to the return air port. **/
boost::optional<ModelObject> returnAirModelObject();
/** Returns the optional ModelObject attached to the outdoor air port. **/
boost::optional<ModelObject> outdoorAirModelObject();
/** Returns the optional ModelObject attached to the relief air port. **/
boost::optional<ModelObject> reliefAirModelObject();
/** Returns the optional ModelObject attached to the mixer air port. **/
boost::optional<ModelObject> mixedAirModelObject();
/** Returns the most outboard outdoor air Node. **/
boost::optional<Node> outboardOANode() const;
/** Returns the most outboard relief air Node. **/
boost::optional<Node> outboardReliefNode() const;
/** Returns a vector of model objects that are on the path of the incoming outdoor air stream. **/
std::vector<ModelObject> oaComponents() const;
/** Returns a vector of model objects that are on the path of the outgoing relief air stream. **/
std::vector<ModelObject> reliefComponents() const;
/** Returns a vector that is the concatenation of oaComponents() and reliefComponents(). **/
std::vector<ModelObject> components() const;
/** Returns the optional ModelObject with the Handle given. The optional
* will be false if the given handle does not correspond to the a ModelObject
* that is not part of the outdoor air system.
**/
boost::optional<ModelObject> component(openstudio::Handle handle);
/** Returns the optional ModelObject with the Handle given. The optional
* will be false if the given handle does not correspond to the a ModelObject
* that is not part of the supply side of the outdoor air system.
**/
boost::optional<ModelObject> oaComponent(openstudio::Handle handle);
/** Returns the optional ModelObject with the Handle given. The optional
* will be false if the given handle does not correspond to the a ModelObject
* that is not part of the supply side of the outdoor air system.
**/
boost::optional<ModelObject> reliefComponent(openstudio::Handle handle);
virtual bool addToNode(Node & node);
virtual std::vector<openstudio::IdfObject> remove();
virtual ModelObject clone(Model model) const;
/** Returns the ControllerOutdoorAir object associated with the AirLoopHVACOutdoorAirSystem. **/
ControllerOutdoorAir getControllerOutdoorAir() const;
/** Sets the ControllerOutdoorAir object associated with the AirLoopHVACOutdoorAirSystem. **/
void setControllerOutdoorAir(const ControllerOutdoorAir & controllerOutdoorAir );
/** Reimplemented from HVACComponent. **/
boost::optional<AirLoopHVAC> airLoop() const;
static IddObjectType iddObjectType();
protected:
friend class Model;
friend class openstudio::IdfObject;
/// @cond
typedef detail::AirLoopHVACOutdoorAirSystem_Impl ImplType;
explicit AirLoopHVACOutdoorAirSystem(
std::shared_ptr<detail::AirLoopHVACOutdoorAirSystem_Impl> impl);
private:
REGISTER_LOGGER("openstudio.model.AirLoopHVACOutdoorAirSystem");
/// @endcond
};
/** \relates AirLoopHVACOutdoorAirSystem */
typedef boost::optional<AirLoopHVACOutdoorAirSystem> OptionalAirLoopHVACOutdoorAirSystem;
/** \relates AirLoopHVACOutdoorAirSystem */
typedef std::vector<AirLoopHVACOutdoorAirSystem> AirLoopHVACOutdoorAirSystemVector;
} // model
} // openstudio
#endif // MODEL_AIRLOOPHVACOUTDOORAIRSYSTEM_HPP
| 36.582353 | 100 | 0.735166 | jasondegraw |
2deb4e95e8c74884d97ba274b498690c42019070 | 18,196 | cc | C++ | src/xenia/ui/windowed_app_context_android.cc | amessier/xenia | 6b45cf84472c26436d4a5db61a7b50dab301e398 | [
"BSD-3-Clause"
] | 1 | 2022-03-21T07:35:46.000Z | 2022-03-21T07:35:46.000Z | src/xenia/ui/windowed_app_context_android.cc | amessier/xenia | 6b45cf84472c26436d4a5db61a7b50dab301e398 | [
"BSD-3-Clause"
] | null | null | null | src/xenia/ui/windowed_app_context_android.cc | amessier/xenia | 6b45cf84472c26436d4a5db61a7b50dab301e398 | [
"BSD-3-Clause"
] | null | null | null | /**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2022 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/ui/windowed_app_context_android.h"
#include <android/asset_manager_jni.h>
#include <android/configuration.h>
#include <android/log.h>
#include <android/looper.h>
#include <android/native_window.h>
#include <android/native_window_jni.h>
#include <fcntl.h>
#include <jni.h>
#include <unistd.h>
#include <array>
#include <cstdint>
#include "xenia/base/assert.h"
#include "xenia/base/logging.h"
#include "xenia/base/main_android.h"
#include "xenia/ui/window_android.h"
#include "xenia/ui/windowed_app.h"
namespace xe {
namespace ui {
void AndroidWindowedAppContext::NotifyUILoopOfPendingFunctions() {
// Don't check ui_thread_looper_callback_registered_, as it's owned
// exclusively by the UI thread, while this may be called by any, and in case
// of a pipe error, the callback will be invoked by the looper, which will
// trigger all the necessary shutdown, and the pending functions will be
// called anyway by the shutdown.
UIThreadLooperCallbackCommand command =
UIThreadLooperCallbackCommand::kExecutePendingFunctions;
if (write(ui_thread_looper_callback_pipe_[1], &command, sizeof(command)) !=
sizeof(command)) {
XELOGE(
"AndroidWindowedAppContext: Failed to write a pending function "
"execution command to the UI thread looper callback pipe");
return;
}
ALooper_wake(ui_thread_looper_);
}
void AndroidWindowedAppContext::PlatformQuitFromUIThread() {
// All the shutdown will be done in onDestroy of the activity.
if (activity_ && activity_method_finish_) {
ui_thread_jni_env_->CallVoidMethod(activity_, activity_method_finish_);
}
}
void AndroidWindowedAppContext::PostInvalidateWindowSurface() {
// May be called from non-UI threads.
JNIEnv* jni_env = GetAndroidThreadJniEnv();
if (!jni_env) {
return;
}
jni_env->CallVoidMethod(activity_,
activity_method_post_invalidate_window_surface_);
}
AndroidWindowedAppContext*
AndroidWindowedAppContext::JniActivityInitializeWindowedAppOnCreate(
JNIEnv* jni_env, jobject activity, jstring windowed_app_identifier,
jobject asset_manager) {
WindowedApp::Creator app_creator;
{
const char* windowed_app_identifier_c_str =
jni_env->GetStringUTFChars(windowed_app_identifier, nullptr);
if (!windowed_app_identifier_c_str) {
__android_log_write(
ANDROID_LOG_ERROR, "AndroidWindowedAppContext",
"Failed to get the UTF-8 string for the windowed app identifier");
return nullptr;
}
app_creator = WindowedApp::GetCreator(windowed_app_identifier_c_str);
if (!app_creator) {
__android_log_print(ANDROID_LOG_ERROR, "AndroidWindowedAppContext",
"Failed to get the creator for the windowed app %s",
windowed_app_identifier_c_str);
jni_env->ReleaseStringUTFChars(windowed_app_identifier,
windowed_app_identifier_c_str);
return nullptr;
}
jni_env->ReleaseStringUTFChars(windowed_app_identifier,
windowed_app_identifier_c_str);
}
AndroidWindowedAppContext* app_context = new AndroidWindowedAppContext;
if (!app_context->Initialize(jni_env, activity, asset_manager)) {
delete app_context;
return nullptr;
}
if (!app_context->InitializeApp(app_creator)) {
// InitializeApp might have sent commands to the UI thread looper callback
// pipe, perform deferred destruction.
app_context->RequestDestruction();
return nullptr;
}
return app_context;
}
void AndroidWindowedAppContext::JniActivityOnDestroy() {
if (app_) {
app_->InvokeOnDestroy();
app_.reset();
}
// Expecting that the destruction of the app will destroy the window as well,
// no need to notify it explicitly.
assert_null(activity_window_);
RequestDestruction();
}
void AndroidWindowedAppContext::JniActivityOnWindowSurfaceLayoutChange(
jint left, jint top, jint right, jint bottom) {
window_surface_layout_left_ = left;
window_surface_layout_top_ = top;
window_surface_layout_right_ = right;
window_surface_layout_bottom_ = bottom;
if (activity_window_) {
activity_window_->OnActivitySurfaceLayoutChange();
}
}
void AndroidWindowedAppContext::JniActivityOnWindowSurfaceChanged(
jobject window_surface_object) {
// Detach from the old surface.
if (window_surface_) {
ANativeWindow* old_window_surface = window_surface_;
window_surface_ = nullptr;
if (activity_window_) {
activity_window_->OnActivitySurfaceChanged();
}
ANativeWindow_release(old_window_surface);
}
if (!window_surface_object) {
return;
}
window_surface_ =
ANativeWindow_fromSurface(ui_thread_jni_env_, window_surface_object);
if (!window_surface_) {
return;
}
if (activity_window_) {
activity_window_->OnActivitySurfaceChanged();
}
}
void AndroidWindowedAppContext::JniActivityPaintWindow(bool force_paint) {
if (!activity_window_) {
return;
}
activity_window_->PaintActivitySurface(force_paint);
}
AndroidWindowedAppContext::~AndroidWindowedAppContext() { Shutdown(); }
bool AndroidWindowedAppContext::Initialize(JNIEnv* ui_thread_jni_env,
jobject activity,
jobject asset_manager) {
// Xenia logging is not initialized yet - use __android_log_write or
// __android_log_print until InitializeAndroidAppFromMainThread is done.
ui_thread_jni_env_ = ui_thread_jni_env;
// Initialize the asset manager for retrieving the current configuration.
asset_manager_jobject_ = ui_thread_jni_env_->NewGlobalRef(asset_manager);
if (!asset_manager_jobject_) {
__android_log_write(
ANDROID_LOG_ERROR, "AndroidWindowedAppContext",
"Failed to create a global reference to the asset manager");
Shutdown();
return false;
}
asset_manager_ =
AAssetManager_fromJava(ui_thread_jni_env_, asset_manager_jobject_);
if (!asset_manager_) {
__android_log_write(ANDROID_LOG_ERROR, "AndroidWindowedAppContext",
"Failed to create get the AAssetManager");
Shutdown();
return false;
}
// Get the initial configuration.
configuration_ = AConfiguration_new();
if (!configuration_) {
__android_log_write(ANDROID_LOG_ERROR, "AndroidWindowedAppContext",
"Failed to create an AConfiguration");
Shutdown();
return false;
}
AConfiguration_fromAssetManager(configuration_, asset_manager_);
// Get the activity class, needed for the application context here, and for
// other activity interaction later.
{
jclass activity_class_local_ref =
ui_thread_jni_env_->GetObjectClass(activity);
if (!activity_class_local_ref) {
__android_log_write(ANDROID_LOG_ERROR, "AndroidWindowedAppContext",
"Failed to get the activity class");
Shutdown();
return false;
}
activity_class_ = reinterpret_cast<jclass>(ui_thread_jni_env_->NewGlobalRef(
reinterpret_cast<jobject>(activity_class_local_ref)));
ui_thread_jni_env_->DeleteLocalRef(
reinterpret_cast<jobject>(activity_class_local_ref));
}
if (!activity_class_) {
__android_log_write(
ANDROID_LOG_ERROR, "AndroidWindowedAppContext",
"Failed to create a global reference to the activity class");
Shutdown();
return false;
}
// Get the application context.
jmethodID activity_get_application_context = ui_thread_jni_env_->GetMethodID(
activity_class_, "getApplicationContext", "()Landroid/content/Context;");
if (!activity_get_application_context) {
__android_log_write(
ANDROID_LOG_ERROR, "AndroidWindowedAppContext",
"Failed to get the getApplicationContext method of the activity");
Shutdown();
return false;
}
jobject application_context_init_ref = ui_thread_jni_env_->CallObjectMethod(
activity, activity_get_application_context);
if (!application_context_init_ref) {
__android_log_write(
ANDROID_LOG_ERROR, "AndroidWindowedAppContext",
"Failed to get the application context from the activity");
Shutdown();
return false;
}
// Initialize Xenia globals that may depend on the base globals and logging.
xe::InitializeAndroidAppFromMainThread(
AConfiguration_getSdkVersion(configuration_), ui_thread_jni_env_,
application_context_init_ref);
android_base_initialized_ = true;
ui_thread_jni_env_->DeleteLocalRef(application_context_init_ref);
// Initialize interfacing with the WindowedAppActivity.
activity_ = ui_thread_jni_env_->NewGlobalRef(activity);
if (!activity_) {
XELOGE(
"AndroidWindowedAppContext: Failed to create a global reference to the "
"activity");
Shutdown();
return false;
}
bool activity_ids_obtained = true;
activity_ids_obtained &=
(activity_method_finish_ = ui_thread_jni_env_->GetMethodID(
activity_class_, "finish", "()V")) != nullptr;
activity_ids_obtained &=
(activity_method_post_invalidate_window_surface_ =
ui_thread_jni_env_->GetMethodID(
activity_class_, "postInvalidateWindowSurface", "()V")) !=
nullptr;
if (!activity_ids_obtained) {
XELOGE("AndroidWindowedAppContext: Failed to get the activity class IDs");
Shutdown();
return false;
}
// Initialize sending commands to the UI thread looper callback, for
// requesting function calls in the UI thread.
ui_thread_looper_ = ALooper_forThread();
// The context may be created only in the UI thread, which must have an
// internal looper.
assert_not_null(ui_thread_looper_);
if (!ui_thread_looper_) {
XELOGE("AndroidWindowedAppContext: Failed to get the UI thread looper");
Shutdown();
return false;
}
// The looper can be woken up by other threads, so acquiring it. Shutdown
// assumes that if ui_thread_looper_ is not null, it has been acquired.
ALooper_acquire(ui_thread_looper_);
if (pipe(ui_thread_looper_callback_pipe_.data())) {
XELOGE(
"AndroidWindowedAppContext: Failed to create the UI thread looper "
"callback pipe");
Shutdown();
return false;
}
if (ALooper_addFd(ui_thread_looper_, ui_thread_looper_callback_pipe_[0],
ALOOPER_POLL_CALLBACK, ALOOPER_EVENT_INPUT,
UIThreadLooperCallback, this) != 1) {
XELOGE(
"AndroidWindowedAppContext: Failed to add the callback to the UI "
"thread looper");
Shutdown();
return false;
}
ui_thread_looper_callback_registered_ = true;
return true;
}
void AndroidWindowedAppContext::Shutdown() {
if (app_) {
app_->InvokeOnDestroy();
app_.reset();
}
// The app should destroy the window, but make sure everything is cleaned up
// anyway.
assert_null(activity_window_);
activity_window_ = nullptr;
if (ui_thread_looper_callback_registered_) {
ALooper_removeFd(ui_thread_looper_, ui_thread_looper_callback_pipe_[0]);
ui_thread_looper_callback_registered_ = false;
}
for (int& pipe_fd : ui_thread_looper_callback_pipe_) {
if (pipe_fd == -1) {
continue;
}
close(pipe_fd);
pipe_fd = -1;
}
if (ui_thread_looper_) {
ALooper_release(ui_thread_looper_);
ui_thread_looper_ = nullptr;
}
activity_method_finish_ = nullptr;
if (activity_) {
ui_thread_jni_env_->DeleteGlobalRef(activity_);
activity_ = nullptr;
}
if (android_base_initialized_) {
xe::ShutdownAndroidAppFromMainThread();
android_base_initialized_ = false;
}
if (activity_class_) {
ui_thread_jni_env_->DeleteGlobalRef(
reinterpret_cast<jobject>(activity_class_));
activity_class_ = nullptr;
}
if (configuration_) {
AConfiguration_delete(configuration_);
configuration_ = nullptr;
}
asset_manager_ = nullptr;
if (asset_manager_jobject_) {
ui_thread_jni_env_->DeleteGlobalRef(asset_manager_jobject_);
asset_manager_jobject_ = nullptr;
}
ui_thread_jni_env_ = nullptr;
}
void AndroidWindowedAppContext::RequestDestruction() {
// According to ALooper_removeFd documentation:
// "...it is possible for the callback to already be running or for it to run
// one last time if the file descriptor was already signalled. Calling code
// is responsible for ensuring that this case is safely handled. For example,
// if the callback takes care of removing itself during its own execution
// either by returning 0 or by calling this method..."
// If the looper callback is registered, the pipe may have pending commands,
// and thus the callback may still be called with the pointer to the context
// as the user data.
if (!ui_thread_looper_callback_registered_) {
delete this;
return;
}
UIThreadLooperCallbackCommand command =
UIThreadLooperCallbackCommand::kDestroy;
if (write(ui_thread_looper_callback_pipe_[1], &command, sizeof(command)) !=
sizeof(command)) {
XELOGE(
"AndroidWindowedAppContext: Failed to write a destruction command to "
"the UI thread looper callback pipe");
delete this;
return;
}
ALooper_wake(ui_thread_looper_);
}
int AndroidWindowedAppContext::UIThreadLooperCallback(int fd, int events,
void* data) {
// In case of errors, destruction of the pipe (most importantly the write end)
// must not be done here immediately as other threads, which may still be
// sending commands, would not be aware of that.
auto app_context = static_cast<AndroidWindowedAppContext*>(data);
if (events &
(ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP | ALOOPER_EVENT_INVALID)) {
// Will return 0 to unregister self, this file descriptor is not usable
// anymore, so let everything potentially referencing it in QuitFromUIThread
// know.
app_context->ui_thread_looper_callback_registered_ = false;
XELOGE(
"AndroidWindowedAppContext: The UI thread looper callback pipe file "
"descriptor has encountered an error condition during polling");
app_context->QuitFromUIThread();
return 0;
}
if (!(events & ALOOPER_EVENT_INPUT)) {
// Spurious callback call. Need a non-empty pipe.
return 1;
}
// Process one command with a blocking `read`. The callback will be invoked
// again and again if there is still data after this read.
UIThreadLooperCallbackCommand command;
switch (read(fd, &command, sizeof(command))) {
case sizeof(command):
break;
case -1:
// Will return 0 to unregister self, this file descriptor is not usable
// anymore, so let everything potentially referencing it in
// QuitFromUIThread know.
app_context->ui_thread_looper_callback_registered_ = false;
XELOGE(
"AndroidWindowedAppContext: The UI thread looper callback pipe file "
"descriptor has encountered an error condition during reading");
app_context->QuitFromUIThread();
return 0;
default:
// Something like incomplete data - shouldn't be happening, but not a
// reported error.
return 1;
}
switch (command) {
case UIThreadLooperCallbackCommand::kDestroy:
// Final destruction requested. Will unregister self by returning 0, so
// set ui_thread_looper_callback_registered_ to false so Shutdown won't
// try to unregister it too.
app_context->ui_thread_looper_callback_registered_ = false;
delete app_context;
return 0;
case UIThreadLooperCallbackCommand::kExecutePendingFunctions:
app_context->ExecutePendingFunctionsFromUIThread();
break;
}
return 1;
}
bool AndroidWindowedAppContext::InitializeApp(std::unique_ptr<WindowedApp> (
*app_creator)(WindowedAppContext& app_context)) {
assert_null(app_);
app_ = app_creator(*this);
if (!app_->OnInitialize()) {
app_->InvokeOnDestroy();
app_.reset();
return false;
}
return true;
}
} // namespace ui
} // namespace xe
extern "C" {
JNIEXPORT jlong JNICALL
Java_jp_xenia_emulator_WindowedAppActivity_initializeWindowedAppOnCreate(
JNIEnv* jni_env, jobject activity, jstring windowed_app_identifier,
jobject asset_manager) {
return reinterpret_cast<jlong>(
xe::ui::AndroidWindowedAppContext ::
JniActivityInitializeWindowedAppOnCreate(
jni_env, activity, windowed_app_identifier, asset_manager));
}
JNIEXPORT void JNICALL
Java_jp_xenia_emulator_WindowedAppActivity_onDestroyNative(
JNIEnv* jni_env, jobject activity, jlong app_context_ptr) {
reinterpret_cast<xe::ui::AndroidWindowedAppContext*>(app_context_ptr)
->JniActivityOnDestroy();
}
JNIEXPORT void JNICALL
Java_jp_xenia_emulator_WindowedAppActivity_onWindowSurfaceLayoutChange(
JNIEnv* jni_env, jobject activity, jlong app_context_ptr, jint left,
jint top, jint right, jint bottom) {
reinterpret_cast<xe::ui::AndroidWindowedAppContext*>(app_context_ptr)
->JniActivityOnWindowSurfaceLayoutChange(left, top, right, bottom);
}
JNIEXPORT void JNICALL
Java_jp_xenia_emulator_WindowedAppActivity_onWindowSurfaceChanged(
JNIEnv* jni_env, jobject activity, jlong app_context_ptr,
jobject window_surface_object) {
reinterpret_cast<xe::ui::AndroidWindowedAppContext*>(app_context_ptr)
->JniActivityOnWindowSurfaceChanged(window_surface_object);
}
JNIEXPORT void JNICALL Java_jp_xenia_emulator_WindowedAppActivity_paintWindow(
JNIEnv* jni_env, jobject activity, jlong app_context_ptr,
jboolean force_paint) {
reinterpret_cast<xe::ui::AndroidWindowedAppContext*>(app_context_ptr)
->JniActivityPaintWindow(bool(force_paint));
}
} // extern "C"
| 35.469786 | 80 | 0.713673 | amessier |
2dedad29c413841e2cfa8e4592f1c5207d64efa4 | 422 | cpp | C++ | basic_datastructure/binary_heap/heapSort.cpp | weekieACpper/DataStructre-weekie | 9f15d95dd57c02d7d385b151940bbee4f3c2d99b | [
"MIT"
] | null | null | null | basic_datastructure/binary_heap/heapSort.cpp | weekieACpper/DataStructre-weekie | 9f15d95dd57c02d7d385b151940bbee4f3c2d99b | [
"MIT"
] | null | null | null | basic_datastructure/binary_heap/heapSort.cpp | weekieACpper/DataStructre-weekie | 9f15d95dd57c02d7d385b151940bbee4f3c2d99b | [
"MIT"
] | null | null | null | /*
* @Author: weekie
* @Date: 2022-03-04 21:02:16
* @LastEditTime: 2022-03-04 21:05:33
* @LastEditors: Please set LastEditors
* @Description: 实现堆排序
* @FilePath: /datastructure/basic_datastructre/binary_heap/heapSort.cpp
*/
#include<maxHeap.hpp>
//堆排序
void heapSort(int* array, int size)
{
maxHeap heap(array, size);//建堆
for (int i = size - 1; i >= 0; i--)
{
array[i] = heap.extractMax();
}
} | 23.444444 | 72 | 0.635071 | weekieACpper |
2dee1f0719d195dbbaf955c178593aa2e2fcc941 | 4,262 | cxx | C++ | pandatool/src/eggcharbase/eggJointPointer.cxx | kestred/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | pandatool/src/eggcharbase/eggJointPointer.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | pandatool/src/eggcharbase/eggJointPointer.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | // Filename: eggJointPointer.cxx
// Created by: drose (26Feb01)
//
////////////////////////////////////////////////////////////////////
//
// 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."
//
////////////////////////////////////////////////////////////////////
#include "eggJointPointer.h"
TypeHandle EggJointPointer::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: EggJointPointer::add_frame
// Access: Public, Virtual
// Description: Appends a new frame onto the end of the data, if
// possible; returns true if not possible, or false
// otherwise (e.g. for a static joint).
////////////////////////////////////////////////////////////////////
bool EggJointPointer::
add_frame(const LMatrix4d &) {
return false;
}
////////////////////////////////////////////////////////////////////
// Function: EggJointPointer::move_vertices_to
// Access: Public, Virtual
// Description: Moves the vertices assigned to this joint into the
// other joint (which should be of the same type).
////////////////////////////////////////////////////////////////////
void EggJointPointer::
move_vertices_to(EggJointPointer *) {
}
////////////////////////////////////////////////////////////////////
// Function: EggJointPointer::do_rebuild
// Access: Public, Virtual
// Description: Rebuilds the entire table all at once, based on the
// frames added by repeated calls to add_rebuild_frame()
// since the last call to begin_rebuild().
//
// Until do_rebuild() is called, the animation table is
// not changed.
//
// The return value is true if all frames are
// acceptable, or false if there is some problem.
////////////////////////////////////////////////////////////////////
bool EggJointPointer::
do_rebuild(EggCharacterDb &db) {
return true;
}
////////////////////////////////////////////////////////////////////
// Function: EggJointPointer::optimize
// Access: Public, Virtual
// Description: Resets the table before writing to disk so that
// redundant rows (e.g. i { 1 1 1 1 1 1 1 1 }) are
// collapsed out.
////////////////////////////////////////////////////////////////////
void EggJointPointer::
optimize() {
}
////////////////////////////////////////////////////////////////////
// Function: EggJointPointer::expose
// Access: Public, Virtual
// Description: Flags the joint with the indicated DCS flag so that
// it will be loaded as a separate node in the player.
////////////////////////////////////////////////////////////////////
void EggJointPointer::
expose(EggGroup::DCSType) {
}
////////////////////////////////////////////////////////////////////
// Function: EggJointPointer::zero_channels
// Access: Public, Virtual
// Description: Zeroes out the named components of the transform in
// the animation frames.
////////////////////////////////////////////////////////////////////
void EggJointPointer::
zero_channels(const string &) {
}
////////////////////////////////////////////////////////////////////
// Function: EggJointPointer::quantize_channels
// Access: Public, Virtual
// Description: Rounds the named components of the transform to the
// nearest multiple of quantum.
////////////////////////////////////////////////////////////////////
void EggJointPointer::
quantize_channels(const string &, double) {
}
////////////////////////////////////////////////////////////////////
// Function: EggJointPointer::apply_default_pose
// Access: Public, Virtual
// Description: Applies the pose from the indicated frame of the
// indicated source joint as the initial pose for
// this joint.
////////////////////////////////////////////////////////////////////
void EggJointPointer::
apply_default_pose(EggJointPointer *source_joint, int frame) {
}
| 38.053571 | 70 | 0.475129 | kestred |
2dee406bec450bd7527cd85e1ffbb731beda210d | 1,738 | cxx | C++ | src/Cxx/Visualization/CornerAnnotation.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 81 | 2020-08-10T01:44:30.000Z | 2022-03-23T06:46:36.000Z | src/Cxx/Visualization/CornerAnnotation.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 2 | 2020-09-12T17:33:52.000Z | 2021-04-15T17:33:09.000Z | src/Cxx/Visualization/CornerAnnotation.cxx | ajpmaclean/vtk-examples | 1a55fc8c6af67a3c07791807c7d1ec0ab97607a2 | [
"Apache-2.0"
] | 27 | 2020-08-17T07:09:30.000Z | 2022-02-15T03:44:58.000Z | #include <vtkActor.h>
#include <vtkCornerAnnotation.h>
#include <vtkNamedColors.h>
#include <vtkNew.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderWindowInteractor.h>
#include <vtkRenderer.h>
#include <vtkSphereSource.h>
#include <vtkTextProperty.h>
int main(int, char*[])
{
vtkNew<vtkNamedColors> colors;
vtkNew<vtkSphereSource> sphereSource;
sphereSource->Update();
vtkNew<vtkPolyDataMapper> mapper;
mapper->SetInputConnection(sphereSource->GetOutputPort());
vtkNew<vtkActor> actor;
actor->SetMapper(mapper);
actor->GetProperty()->SetColor(colors->GetColor3d("MistyRose").GetData());
// Visualize
vtkNew<vtkRenderer> renderer;
vtkNew<vtkRenderWindow> renderWindow;
renderWindow->AddRenderer(renderer);
renderWindow->SetWindowName("ComplexV");
vtkNew<vtkRenderWindowInteractor> renderWindowInteractor;
renderWindowInteractor->SetRenderWindow(renderWindow);
renderer->AddActor(actor);
renderer->SetBackground(colors->GetColor3d("DarkSlateGray").GetData());
// Annotate the image with window/level and mouse over pixel information
vtkNew<vtkCornerAnnotation> cornerAnnotation;
cornerAnnotation->SetLinearFontScaleFactor(2);
cornerAnnotation->SetNonlinearFontScaleFactor(1);
cornerAnnotation->SetMaximumFontSize(20);
cornerAnnotation->SetText(0, "lower left");
cornerAnnotation->SetText(1, "lower right");
cornerAnnotation->SetText(2, "upper left");
cornerAnnotation->SetText(3, "upper right");
cornerAnnotation->GetTextProperty()->SetColor(
colors->GetColor3d("Gold").GetData());
renderer->AddViewProp(cornerAnnotation);
renderWindow->Render();
renderWindowInteractor->Start();
return EXIT_SUCCESS;
}
| 30.491228 | 76 | 0.76985 | ajpmaclean |
2dee7b31ab8c7e91333b5fb86e1ce4d941b2bb5e | 323 | cpp | C++ | artifact/storm/src/storm/solver/stateelimination/StatePriorityQueue.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/storm/solver/stateelimination/StatePriorityQueue.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | null | null | null | artifact/storm/src/storm/solver/stateelimination/StatePriorityQueue.cpp | glatteis/tacas21-artifact | 30b4f522bd3bdb4bebccbfae93f19851084a3db5 | [
"MIT"
] | 1 | 2022-02-05T12:39:53.000Z | 2022-02-05T12:39:53.000Z | #include "storm/solver/stateelimination/StatePriorityQueue.h"
namespace storm {
namespace solver {
namespace stateelimination {
void StatePriorityQueue::update(storm::storage::sparse::state_type) {
// Intentionally left empty.
}
}
}
}
| 23.071429 | 81 | 0.572755 | glatteis |
2def344c3e3fa1c905bc0f8f37b53328c24bae73 | 1,248 | hpp | C++ | Pods/Headers/Private/GeoFeatures/Internal/geofeatures/Geometry.hpp | xarvey/Yuuuuuge | 9f4ec32f81cf813ea630ba2c44eb03970c56dad3 | [
"Apache-2.0"
] | null | null | null | Pods/Headers/Private/GeoFeatures/Internal/geofeatures/Geometry.hpp | xarvey/Yuuuuuge | 9f4ec32f81cf813ea630ba2c44eb03970c56dad3 | [
"Apache-2.0"
] | null | null | null | Pods/Headers/Private/GeoFeatures/Internal/geofeatures/Geometry.hpp | xarvey/Yuuuuuge | 9f4ec32f81cf813ea630ba2c44eb03970c56dad3 | [
"Apache-2.0"
] | null | null | null | /**
* Geometry.hpp
*
* Copyright 2015 The Climate Corporation
* Copyright 2015 Tony Stone
*
* 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.
*
* Created by Tony Stone on 6/9/15.
*
* MODIFIED 2015 BY Tony Stone. Modifications licensed under Apache License, Version 2.0.
*
*/
#pragma once
#ifndef __Geometry_HPP_
#define __Geometry_HPP_
namespace geofeatures {
/**
* @class Geometry
*
* @brief Base abstract type for all Geometric types.
*
* @author Tony Stone
* @date 6/10/15
*/
class Geometry {
public:
inline Geometry() noexcept {}
inline virtual ~Geometry() noexcept {};
};
} // namespace geofeatures
#endif //__Geometry_HPP_
| 24.96 | 90 | 0.671474 | xarvey |
2defd0758e952e32156596da699a0ad6aafae47e | 6,081 | cpp | C++ | media_driver/media_driver_next/agnostic/gen12/codec/hal/dec/av1/pipeline/decode_filmgrain_presubpipeline_g12.cpp | saosipov/media-driver | e280504bb3ccc429aa43f30aa76e0c990df6ccbf | [
"MIT",
"Intel",
"BSD-3-Clause"
] | null | null | null | media_driver/media_driver_next/agnostic/gen12/codec/hal/dec/av1/pipeline/decode_filmgrain_presubpipeline_g12.cpp | saosipov/media-driver | e280504bb3ccc429aa43f30aa76e0c990df6ccbf | [
"MIT",
"Intel",
"BSD-3-Clause"
] | null | null | null | media_driver/media_driver_next/agnostic/gen12/codec/hal/dec/av1/pipeline/decode_filmgrain_presubpipeline_g12.cpp | saosipov/media-driver | e280504bb3ccc429aa43f30aa76e0c990df6ccbf | [
"MIT",
"Intel",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2020, Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
//!
//! \file decode_filmgrain_presubpipeline_g12.cpp
//! \brief Defines the preSubpipeline for film grain generate noise
//! \details Defines the preSubpipeline for film grain generate noise, including getRandomValues, regressPhase1, regressPhase2 kernels.
//!
#include "decode_filmgrain_presubpipeline_g12.h"
#include "decode_basic_feature.h"
#include "decode_pipeline.h"
#include "decode_av1_filmgrain_feature_g12.h"
#include "decode_av1_feature_defs_g12.h"
namespace decode {
FilmGrainPreSubPipeline::FilmGrainPreSubPipeline(DecodePipeline *pipeline, MediaTask *task, uint8_t numVdbox)
: DecodeSubPipeline(pipeline, task, numVdbox)
{}
MOS_STATUS FilmGrainPreSubPipeline::Init(CodechalSetting &settings)
{
DECODE_CHK_NULL(m_pipeline);
CodechalHwInterface* hwInterface = m_pipeline->GetHwInterface();
DECODE_CHK_NULL(hwInterface);
PMOS_INTERFACE osInterface = hwInterface->GetOsInterface();
DECODE_CHK_NULL(osInterface);
InitScalabilityPars(osInterface);
m_allocator = m_pipeline->GetDecodeAllocator();
DECODE_CHK_NULL(m_allocator);
MediaFeatureManager* featureManager = m_pipeline->GetFeatureManager();
DECODE_CHK_NULL(featureManager);
m_basicFeature = dynamic_cast<DecodeBasicFeature*>(featureManager->GetFeature(FeatureIDs::basicFeature));
DECODE_CHK_NULL(m_basicFeature);
m_filmGrainFeature = dynamic_cast<Av1DecodeFilmGrainG12 *>(featureManager->GetFeature(Av1FeatureIDs::av1SwFilmGrain));
DECODE_CHK_NULL(m_filmGrainFeature);
//Create Packets
m_filmGrainGrvPkt = MOS_New(FilmGrainGrvPacket, m_pipeline, m_task, hwInterface);
Av1PipelineG12 *pipeline = dynamic_cast<Av1PipelineG12 *>(m_pipeline);
DECODE_CHK_STATUS(RegisterPacket(DecodePacketId(pipeline, av1FilmGrainGrvPacketId), *m_filmGrainGrvPkt));
DECODE_CHK_STATUS(m_filmGrainGrvPkt->Init());
m_filmGrainRp1Pkt = MOS_New(FilmGrainRp1Packet, m_pipeline, m_task, hwInterface);
DECODE_CHK_STATUS(RegisterPacket(DecodePacketId(pipeline, av1FilmGrainRp1PacketId), *m_filmGrainRp1Pkt));
DECODE_CHK_STATUS(m_filmGrainRp1Pkt->Init());
m_filmGrainRp2Pkt = MOS_New(FilmGrainRp2Packet, m_pipeline, m_task, hwInterface);
DECODE_CHK_STATUS(RegisterPacket(DecodePacketId(pipeline, av1FilmGrainRp2PacketId), *m_filmGrainRp2Pkt));
DECODE_CHK_STATUS(m_filmGrainRp2Pkt->Init());
return MOS_STATUS_SUCCESS;
}
MOS_STATUS FilmGrainPreSubPipeline::Prepare(DecodePipelineParams ¶ms)
{
if (params.m_pipeMode == decodePipeModeBegin)
{
DECODE_CHK_STATUS(Begin());
}
else if (params.m_pipeMode == decodePipeModeProcess)
{
DECODE_CHK_NULL(params.m_params);
CodechalDecodeParams *decodeParams = params.m_params;
DECODE_CHK_STATUS(DoFilmGrainGenerateNoise(*decodeParams));
}
return MOS_STATUS_SUCCESS;
}
MOS_STATUS FilmGrainPreSubPipeline::Begin()
{
DECODE_CHK_STATUS(DecodeSubPipeline::Reset());
return MOS_STATUS_SUCCESS;
}
MOS_STATUS FilmGrainPreSubPipeline::DoFilmGrainGenerateNoise(const CodechalDecodeParams &decodeParams)
{
if (m_filmGrainFeature->m_filmGrainEnabled)
{
//Step1: Get Random Values
DECODE_CHK_STATUS(GetRandomValuesKernel(decodeParams));
//Step2: regressPhase1
DECODE_CHK_STATUS(RegressPhase1Kernel(decodeParams));
//Step3: regressPhase2
DECODE_CHK_STATUS(RegressPhase2Kernel(decodeParams));
}
return MOS_STATUS_SUCCESS;
}
MOS_STATUS FilmGrainPreSubPipeline::GetRandomValuesKernel(const CodechalDecodeParams &decodeParams)
{
Av1PipelineG12 *pipeline = dynamic_cast<Av1PipelineG12 *>(m_pipeline);
DECODE_CHK_STATUS(ActivatePacket(DecodePacketId(pipeline, av1FilmGrainGrvPacketId), true, 0, 0));
return MOS_STATUS_SUCCESS;
}
MOS_STATUS FilmGrainPreSubPipeline::RegressPhase1Kernel(const CodechalDecodeParams &decodeParams)
{
Av1PipelineG12 *pipeline = dynamic_cast<Av1PipelineG12 *>(m_pipeline);
DECODE_CHK_STATUS(ActivatePacket(DecodePacketId(pipeline, av1FilmGrainRp1PacketId), true, 0, 0));
return MOS_STATUS_SUCCESS;
}
MOS_STATUS FilmGrainPreSubPipeline::RegressPhase2Kernel(const CodechalDecodeParams &decodeParams)
{
Av1PipelineG12 *pipeline = dynamic_cast<Av1PipelineG12 *>(m_pipeline);
DECODE_CHK_STATUS(ActivatePacket(DecodePacketId(pipeline, av1FilmGrainRp2PacketId), true, 0, 0));
return MOS_STATUS_SUCCESS;
}
MediaFunction FilmGrainPreSubPipeline::GetMediaFunction()
{
if(!MEDIA_IS_SKU(m_pipeline->GetSkuTable(), FtrCCSNode))
{
return RenderGenericFunc;
}
return ComputeVppFunc;
}
void FilmGrainPreSubPipeline::InitScalabilityPars(PMOS_INTERFACE osInterface)
{
MOS_ZeroMemory(&m_decodeScalabilityPars, sizeof(ScalabilityPars));
m_decodeScalabilityPars.disableScalability = true;
m_decodeScalabilityPars.disableRealTile = true;
m_decodeScalabilityPars.enableVE = MOS_VE_SUPPORTED(osInterface);
m_decodeScalabilityPars.numVdbox = m_numVdbox;
}
}
| 37.537037 | 136 | 0.781286 | saosipov |
2df007d43bd64a839027f78c56d8a469f325895a | 3,828 | tpp | C++ | breeze/encoding/brz/base64_to_binary.tpp | gennaroprota/breeze | 7afe88a30dc8ac8b97a76a192dc9b189d9752e8b | [
"BSD-3-Clause"
] | 1 | 2021-04-03T22:35:52.000Z | 2021-04-03T22:35:52.000Z | breeze/encoding/brz/base64_to_binary.tpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | null | null | null | breeze/encoding/brz/base64_to_binary.tpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | 1 | 2021-10-01T04:26:48.000Z | 2021-10-01T04:26:48.000Z | // ===========================================================================
// Copyright 2016 Gennaro Prota
//
// Licensed under the 3-Clause BSD License.
// (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or
// <https://opensource.org/licenses/BSD-3-Clause>.)
// ___________________________________________________________________________
#include "breeze/counting/signed_count.hpp"
#include <climits>
#include <stdexcept>
#include <type_traits>
namespace breeze_ns {
template< typename InputIter, typename OutputIter >
void
base64_to_binary( InputIter begin, InputIter end, OutputIter out )
{
// Table generated by 'generate_inverse_base64_table': see the
// extra/ subdirectory.
// -----------------------------------------------------------------------
static int const table[] =
{
-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, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -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, -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
} ;
static_assert( UCHAR_MAX == ( signed_count( table ) - 1 ) &&
( std::is_same< typename InputIter::value_type, char >::value
|| std::is_same< typename InputIter::value_type, unsigned char >::value )
) ;
static char const error_message[] = "invalid input to base64_to_binary()" ;
int const not_to_be_translated = -1 ;
int const block_length = 6 ;
int const char_bit = CHAR_BIT ;
unsigned block = 0 ;
int num_bits = 0 ;
bool equals_seen = false ;
for ( InputIter curr( begin ) ; curr != end ; ++ curr ) {
auto const x = static_cast< unsigned char >( *curr ) ;
int const value = table[ x ] ;
// Once we've seen an equal sign, only equal signs or
// newlines can follow; otherwise the input is ill-formed.
// -------------------------------------------------------------------
if ( x == '=' ) {
equals_seen = true ;
}
if ( x != '=' && x != '\n' && equals_seen ) {
throw std::runtime_error( error_message ) ;
}
if ( value == not_to_be_translated ) {
if ( x != '\n' && x != '=' ) {
throw std::runtime_error( error_message ) ;
}
} else {
block = ( block << block_length ) | value ;
num_bits += block_length ;
if ( num_bits >= char_bit ) {
num_bits -= char_bit ;
*out = static_cast< unsigned char >( block >> num_bits ) ;
++ out ;
block &= ( ( 1 << num_bits ) - 1 ) ;
}
}
}
}
}
// Local Variables:
// mode: c++
// End:
// vim: set ft=cpp:
| 42.065934 | 81 | 0.421369 | gennaroprota |
2df021c5be5a9a6256429e5fd634c66eb398cff0 | 3,066 | cpp | C++ | Tools/Src/SFToolLib/Content/Pipeline/SFMeshComponent.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | 1 | 2020-06-20T07:35:25.000Z | 2020-06-20T07:35:25.000Z | Tools/Src/SFToolLib/Content/Pipeline/SFMeshComponent.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | Tools/Src/SFToolLib/Content/Pipeline/SFMeshComponent.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null |
#include "stdafx.h"
#include "UMMeshComponent.h"
#include "UMNodeContent.h"
#include "UMVertexBufferContent.h"
UMMeshComponent::UMMeshComponent( UMNodeContent& owner )
:UMNodeContentComponent(owner)
,m_pVertexBuffer(nullptr)
,m_pRootBone(nullptr)
{
if( m_pVertexBuffer == nullptr )
m_pVertexBuffer = new UMVertexBufferContent;
}
UMMeshComponent::~UMMeshComponent()
{
if( m_pRootBone != nullptr )
delete m_pRootBone;
delete m_pVertexBuffer;
}
// Initialize components after load/create
bool UMMeshComponent::InitializeComponent()
{
return true;
}
// Get vertex buffer
UMVertexBufferContent *UMMeshComponent::GetVertexBuffer()
{
return m_pVertexBuffer;
}
void UMMeshComponent::TransfoSF( const UMTransfoSFMatrix& transfoSF )
{
if( m_pVertexBuffer == nullptr || m_pVertexBuffer->GetNumberOfVertex() == 0 )
return;
auto positionChannel = m_pVertexBuffer->GetVertexChannel( UMVertexBufferContent::StreamChannelType::POSITION );
if( positionChannel != nullptr )
{
auto positions = positionChannel->GetArrayData<float>();
for( UINT iVert = 0 ; iVert < m_pVertexBuffer->GetNumberOfVertex(); iVert++ )
{
auto pCur = &positions[iVert*positionChannel->NumElement + 0];
UMVector4 pos( pCur[0], pCur[1], pCur[2] );
pos = transfoSF.MultT( pos );
pCur[0] = (float)pos[0];
pCur[1] = (float)pos[1];
pCur[2] = (float)pos[2];
}
}
auto noSFalChannel = m_pVertexBuffer->GetVertexChannel( UMVertexBufferContent::StreamChannelType::NOSFAL );
if( noSFalChannel != nullptr )
{
UMTransfoSFMatrix noSFalTransfoSF = transfoSF;
noSFalTransfoSF.SetTOnly(UMVector4(0,0,0));
auto noSFals = noSFalChannel->GetArrayData<float>();
for( UINT iVert = 0 ; iVert < m_pVertexBuffer->GetNumberOfVertex(); iVert++ )
{
auto pCur = &noSFals[iVert*noSFalChannel->NumElement + 0];
UMVector4 pos( pCur[0], pCur[1], pCur[2] );
pos = noSFalTransfoSF.MultT( pos );
pos.NoSFalize();
pCur[0] = (float)pos[0];
pCur[1] = (float)pos[1];
pCur[2] = (float)pos[2];
}
}
}
// Copy Submesh array
void UMMeshComponent::SetSubMeshes( const UMArray<SubMesh*>& subMeshes )
{
std::for_each(m_SubMeshes.begin(), m_SubMeshes.end(), [](SubMesh*pSubMesh)
{
delete pSubMesh;
});
m_SubMeshes.clear();
m_SubMeshes = subMeshes;
}
void UMMeshComponent::ForeachSubMeshes( std::function<void(SubMesh*)> action )
{
std::for_each(m_SubMeshes.begin(), m_SubMeshes.end(), action);
}
UINT UMMeshComponent::AddBone( UMNodeContent* pBone, const UMTransfoSFMatrix& bindPose )
{
int index = FindBone(pBone);
if( index >= 0 )
return index;
BoneNode boneNode;
boneNode.BindPose = bindPose;
boneNode.pBone = pBone;
m_SkinBones.push_back(boneNode);
return m_SkinBones.size() -1;
}
int UMMeshComponent::FindBone( UMNodeContent* pBone )
{
for(int index = 0; index < (int)m_SkinBones.size(); index++ )
{
if( m_SkinBones[index].pBone == pBone )
return index;
}
return -1;
}
void UMMeshComponent::ForeachBones( std::function<void(const BoneNode&)> action )
{
std::for_each(m_SkinBones.begin(), m_SkinBones.end(), action);
}
| 23.40458 | 112 | 0.71559 | blue3k |
2df060e10d97d059caf31b43077c11933f250b12 | 69 | cpp | C++ | src/main/Value.cpp | kkysen/SiliconScratchCpp | 0e3248403c4198fd4ba55ce72a259f5530454577 | [
"MIT"
] | null | null | null | src/main/Value.cpp | kkysen/SiliconScratchCpp | 0e3248403c4198fd4ba55ce72a259f5530454577 | [
"MIT"
] | null | null | null | src/main/Value.cpp | kkysen/SiliconScratchCpp | 0e3248403c4198fd4ba55ce72a259f5530454577 | [
"MIT"
] | null | null | null | //
// Created by Khyber on 8/3/2019.
//
#include "src/main/Value.h"
| 11.5 | 33 | 0.623188 | kkysen |
2df146cf61ed811b382b0b4998192b78caf66ffe | 18,370 | cpp | C++ | cpp/Tests/TestsSmurff.cpp | ExaScience/smurff | 29c3859badca49275833024cd77f8ca7fa6f76be | [
"MIT"
] | 65 | 2017-06-23T14:01:58.000Z | 2022-03-10T16:13:48.000Z | cpp/Tests/TestsSmurff.cpp | ExaScience/smurff | 29c3859badca49275833024cd77f8ca7fa6f76be | [
"MIT"
] | 143 | 2017-08-11T10:43:52.000Z | 2021-09-23T17:07:51.000Z | cpp/Tests/TestsSmurff.cpp | ExaScience/smurff | 29c3859badca49275833024cd77f8ca7fa6f76be | [
"MIT"
] | 14 | 2018-05-17T18:33:28.000Z | 2021-12-23T20:41:32.000Z | #include <cstdio>
#include <fstream>
#include <iomanip>
#include "catch.hpp"
#include <SmurffCpp/Types.h>
#include <SmurffCpp/Configs/Config.h>
#include <SmurffCpp/Sessions/TrainSession.h>
#include <SmurffCpp/Utils/MatrixUtils.h>
#include <SmurffCpp/Utils/StateFile.h>
#include <SmurffCpp/result.h>
#include "Tests.h"
#define TAG_MATRIX_TESTS "[matrix][random]"
#define TAG_TWO_DIMENTIONAL_TENSOR_TESTS "[tensor2d][random]"
#define TAG_THREE_DIMENTIONAL_TENSOR_TESTS "[tensor3d][random]"
namespace smurff {
namespace test {
// Code for printing test results that can then be copy-pasted into tests as
// expected results
static void printActualResults(int nr, double actualRmseAvg, const std::vector<smurff::ResultItem> &actualResults) {
static const char *fname = "TestsSmurff_ExpectedResults.h.generated";
static bool cleanup = true;
if (cleanup) {
std::remove(fname);
cleanup = false;
}
std::ofstream os(fname, std::ofstream::app);
os << "{ " << nr << ",\n"
<< " { " << std::fixed << std::setprecision(16) << actualRmseAvg << "," << std::endl
<< " {\n";
auto sortedResults = actualResults;
std::sort(sortedResults.begin(), sortedResults.end());
for (const auto &actualResultItem : actualResults) {
os << std::setprecision(16);
os << " { { " << actualResultItem.coords << " }, " << actualResultItem.val << ", " << std::fixed
<< actualResultItem.pred_1sample << ", " << actualResultItem.pred_avg << ", " << actualResultItem.var << ", "
<< " }," << std::endl;
}
os << " }\n"
<< " }\n"
<< "},\n";
}
struct ExpectedResult {
double rmseAvg;
std::vector<ResultItem> resultItems;
};
std::map<int, ExpectedResult> expectedResults = {
#include "TestsSmurff_ExpectedResults.h"
};
// result comparison
void checkValue(double actualValue, double expectedValue, double epsilon)
{
#ifdef _OPENMP
double abs_max = std::max(std::abs(actualValue), std::abs(expectedValue));
if (abs_max > 0)
CHECK((std::abs(actualValue - expectedValue) / abs_max) < 10.);
else
CHECK(std::abs(actualValue - expectedValue) < 10.);
#else
CHECK(actualValue == Approx(expectedValue).epsilon(epsilon));
#endif
}
void checkResultItems(const std::vector<ResultItem> &actualResultItems,
const std::vector<ResultItem> &expectedResultItems) {
CHECK(actualResultItems.size() == expectedResultItems.size());
auto sortedActualResultItems = actualResultItems;
std::sort(sortedActualResultItems.begin(), sortedActualResultItems.end());
auto sortedExpectedResultItems = expectedResultItems;
std::sort(sortedExpectedResultItems.begin(), sortedExpectedResultItems.end());
for (std::vector<ResultItem>::size_type i = 0; i < sortedActualResultItems.size(); i++)
{
const ResultItem &actualResultItem = sortedActualResultItems[i];
const ResultItem &expectedResultItem = sortedExpectedResultItems[i];
CHECK(actualResultItem.coords == expectedResultItem.coords);
CHECK(actualResultItem.val == expectedResultItem.val);
checkValue(actualResultItem.pred_1sample,expectedResultItem.pred_1sample, single_item_epsilon);
checkValue(actualResultItem.pred_avg, expectedResultItem.pred_avg, single_item_epsilon);
checkValue(actualResultItem.var, expectedResultItem.var, single_item_epsilon);
}
}
struct SmurffTest {
Config config;
SmurffTest(const Matrix &train, const SparseMatrix &test, std::vector<PriorTypes> priors)
: config(genConfig(train, test, priors)) {}
SmurffTest(const SparseMatrix &train, const SparseMatrix &test, std::vector<PriorTypes> priors)
: config(genConfig(train, test, priors)) {}
SmurffTest(const DenseTensor &train, const SparseTensor &test, std::vector<PriorTypes> priors)
: config(genConfig(train, test, priors)) {}
SmurffTest(const SparseTensor &train, const SparseTensor &test, std::vector<PriorTypes> priors)
: config(genConfig(train, test, priors)) {}
template<class M>
SmurffTest &addSideInfo(int m, const M &c, bool direct = true) {
config.addSideInfo(m, makeSideInfoConfig(c, direct));
return *this;
}
SmurffTest &addAuxData(const DataConfig &c) {
config.addData() = c;
return *this;
}
void runAndCheck(int nr) {
std::shared_ptr<ISession> trainSession = std::make_shared<TrainSession>(config);
trainSession->run();
double actualRmseAvg = trainSession->getRmseAvg();
const std::vector<ResultItem> &actualResults = trainSession->getResultItems();
printActualResults(nr, actualRmseAvg, actualResults);
if(expectedResults.find(nr) == expectedResults.end())
FAIL("Expected results for nr " << nr << " not found\n");
double &expectedRmseAvg = expectedResults[nr].rmseAvg;
auto &expectedResultItems = expectedResults[nr].resultItems;
checkValue(actualRmseAvg, expectedRmseAvg, rmse_epsilon);
checkResultItems(actualResults, expectedResultItems);
}
};
///===========================================================================
TEST_CASE("train_dense_matrix_test_sparse_matrix_normal_normal_none_none",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::normal, PriorTypes::normal}).runAndCheck(359);
}
TEST_CASE("train_sparse_matrix_test_sparse_matrix_normal_normal_none_none",
TAG_MATRIX_TESTS) {
SmurffTest(trainSparseMatrix, testSparseMatrix, {PriorTypes::normal, PriorTypes::normal}).runAndCheck(411);
}
TEST_CASE("train_dense_matrix_test_sparse_matrix_normal_normal_dense_matrix_dense_matrix",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::normal, PriorTypes::normal})
.addAuxData(rowAuxDense)
.addAuxData(colAuxDense)
.runAndCheck(467);
}
TEST_CASE("train_sparse_matrix_test_sparse_matrix_normal_normal_dense_matrix_dense_matrix",
TAG_MATRIX_TESTS) {
SmurffTest(trainSparseMatrix, testSparseMatrix, {PriorTypes::normal, PriorTypes::normal})
.addAuxData(rowAuxDense)
.addAuxData(colAuxDense)
.runAndCheck(523);
}
//=================================================================
TEST_CASE("train_dense_matrix_test_sparse_matrix_spikeandslab_spikeandslab_none_none",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::spikeandslab, PriorTypes::spikeandslab}).runAndCheck(577);
}
TEST_CASE("train_sparse_matrix_test_sparse_matrix_spikeandslab_spikeandslab_none_none",
TAG_MATRIX_TESTS) {
SmurffTest(trainSparseMatrix, testSparseMatrix, {PriorTypes::spikeandslab, PriorTypes::spikeandslab})
.runAndCheck(629);
}
TEST_CASE("train_dense_matrix_test_sparse_matrix_spikeandslab_spikeandslab_dense_matrix_dense_matrix",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::spikeandslab, PriorTypes::spikeandslab})
.addAuxData(rowAuxDense)
.addAuxData(colAuxDense)
.runAndCheck(685);
}
TEST_CASE("train_sparse_matrix_test_sparse_matrix_spikeandslab_spikeandslab_dense_matrix_dense_matrix",
TAG_MATRIX_TESTS) {
SmurffTest(trainSparseMatrix, testSparseMatrix, {PriorTypes::spikeandslab, PriorTypes::spikeandslab})
.addAuxData(rowAuxDense)
.addAuxData(colAuxDense)
.runAndCheck(741);
}
//=================================================================
TEST_CASE("train_dense_matrix_test_sparse_matrix_normalone_normalone_none_none",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::normalone, PriorTypes::normalone}).runAndCheck(795);
}
TEST_CASE("train_sparse_matrix_test_sparse_matrix_normalone_normalone_none_none",
TAG_MATRIX_TESTS) {
SmurffTest(trainSparseMatrix, testSparseMatrix, {PriorTypes::normalone, PriorTypes::normalone}).runAndCheck(847);
}
TEST_CASE("train_dense_matrix_test_sparse_matrix_normalone_normalone_dense_matrix_dense_matrix",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::normalone, PriorTypes::normalone})
.addAuxData(rowAuxDense)
.addAuxData(colAuxDense)
.runAndCheck(903);
}
TEST_CASE("train_sparse_matrix_test_sparse_matrix_normalone_normalone_dense_matrix_dense_matrix",
TAG_MATRIX_TESTS) {
SmurffTest(trainSparseMatrix, testSparseMatrix, {PriorTypes::normalone, PriorTypes::normalone})
.addAuxData(rowAuxDense)
.addAuxData(colAuxDense)
.runAndCheck(959);
}
//=================================================================
TEST_CASE("train_dense_matrix_test_sparse_matrix_macau_macau_row_side_info_dense_matrix_col_side_info_dense_matrix_",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::macau, PriorTypes::macau})
.addSideInfo(0, rowSideDenseMatrix)
.addSideInfo(1, colSideDenseMatrix)
.runAndCheck(1018);
}
TEST_CASE("train_sparse_matrix_test_sparse_matrix_macau_macau_row_side_info_dense_matrix_col_side_info_dense_matrix_",
TAG_MATRIX_TESTS) {
SmurffTest(trainSparseMatrix, testSparseMatrix, {PriorTypes::macau, PriorTypes::macau})
.addSideInfo(0, rowSideDenseMatrix)
.addSideInfo(1, colSideDenseMatrix)
.runAndCheck(1075);
}
//=================================================================
TEST_CASE("train_dense_matrix_test_sparse_matrix_macauone_macauone_row_side_info_sparse_matrix_col_side_info_sparse_matrix_",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::macauone, PriorTypes::macauone})
.addSideInfo(0, rowSideSparseMatrix)
.addSideInfo(1, colSideSparseMatrix)
.runAndCheck(1135);
}
TEST_CASE("train_sparse_matrix_test_sparse_matrix_macauone_macauone_row_side_info_sparse_matrix_col_side_info_sparse_matrix_",
TAG_MATRIX_TESTS) {
SmurffTest(trainSparseMatrix, testSparseMatrix, {PriorTypes::macauone, PriorTypes::macauone})
.addSideInfo(0, rowSideSparseMatrix)
.addSideInfo(1, colSideSparseMatrix)
.runAndCheck(1193);
}
//=================================================================
TEST_CASE("train_dense_matrix_test_sparse_matrix_macau_normal_row_side_info_dense_matrix_none_",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::macau, PriorTypes::normal})
.addSideInfo(0, rowSideDenseMatrix)
.runAndCheck(1250);
}
//TEST_CASE("train_dense_matrix_test_sparse_matrix_macau_normal_row_side_info_dense_matrix_none_cg",
// TAG_MATRIX_TESTS) {
//
// SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::macau, PriorTypes::normal})
// .addSideInfo(0, rowSideDenseMatrix, false)
// .runAndCheck(1250);
//}
TEST_CASE("train_dense_matrix_test_sparse_matrix_normal_macau_none_col_side_info_dense_matrix_",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::normal, PriorTypes::macau})
.addSideInfo(1, colSideDenseMatrix)
.runAndCheck(1305);
}
//TEST_CASE("train_dense_matrix_test_sparse_matrix_normal_macau_none_col_side_info_dense_matrix_cg",
// TAG_MATRIX_TESTS) {
//
// SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::normal, PriorTypes::macau})
// .addSideInfo(1, colSideDenseMatrix, false)
// .runAndCheck(1305);
//}
// test throw - macau prior should have side info
TEST_CASE("train_dense_matrix_test_sparse_matrix_macau_normal_none_none_",
TAG_MATRIX_TESTS) {
Config config = genConfig(trainDenseMatrix, testSparseMatrix, {PriorTypes::macau, PriorTypes::normal});
config.addSideInfo(1, makeSideInfoConfig(rowSideDenseMatrix));
REQUIRE_THROWS(TrainSession(config).init());
}
// test throw - wrong dimentions of side info
TEST_CASE("train_dense_matrix_test_sparse_matrix_macau_normal_col_side_info_dense_matrix_none_",
TAG_MATRIX_TESTS) {
Config config = genConfig(trainDenseMatrix, testSparseMatrix, {PriorTypes::macau, PriorTypes::normal});
config.addSideInfo(1, makeSideInfoConfig(colSideDenseMatrix));
REQUIRE_THROWS(TrainSession(config).init());
}
//=================================================================
TEST_CASE("train_dense_matrix_test_sparse_matrix_normal_spikeandslab_none_none",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::normal, PriorTypes::spikeandslab}).runAndCheck(1466);
}
TEST_CASE("train_dense_matrix_test_sparse_matrix_spikeandslab_normal_none_none",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::spikeandslab, PriorTypes::normal}).runAndCheck(1518);
}
TEST_CASE("train_dense_matrix_test_sparse_matrix_normal_spikeandslab_none_dense_matrix",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::spikeandslab, PriorTypes::normal})
.addAuxData(colAuxDense)
.runAndCheck(1572);
}
TEST_CASE("train_dense_matrix_test_sparse_matrix_spikeandslab_normal_dense_matrix_none",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::spikeandslab, PriorTypes::normal})
.addAuxData(rowAuxDense)
.runAndCheck(1626);
}
//=================================================================
TEST_CASE("train_dense_matrix_test_sparse_matrix_macau_spikeandslab_row_side_info_dense_matrix_none_",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::macau, PriorTypes::spikeandslab})
.addSideInfo(0, rowSideDenseMatrix)
.runAndCheck(1683);
}
TEST_CASE("train_dense_matrix_test_sparse_matrix_spikeandslab_macau_none_col_side_info_dense_matrix_",
TAG_MATRIX_TESTS) {
SmurffTest(trainDenseMatrix, testSparseMatrix, {PriorTypes::spikeandslab, PriorTypes::macau})
.addSideInfo(1, colSideDenseMatrix)
.runAndCheck(1738);
}
//=================================================================
TEST_CASE("train_dense_2d_tensor_test_sparse_2d_tensor_normal_normal_none_none",
TAG_TWO_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainDenseTensor2d, testSparseTensor2d, {PriorTypes::normal, PriorTypes::normal}).runAndCheck(1792);
}
TEST_CASE("train_sparse_2d_tensor_test_sparse_2d_tensor_normal_normal_none_none",
TAG_TWO_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainSparseTensor2d, testSparseTensor2d, {PriorTypes::normal, PriorTypes::normal}).runAndCheck(1844);
}
//=================================================================
TEST_CASE("train_dense_2d_tensor_test_sparse_2d_tensor_spikeandslab_spikeandslab_none_none",
TAG_TWO_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainDenseTensor2d, testSparseTensor2d, {PriorTypes::spikeandslab, PriorTypes::spikeandslab})
.runAndCheck(1898);
}
TEST_CASE("train_sparse_2d_tensor_test_sparse_2d_tensor_spikeandslab_spikeandslab_none_none",
TAG_TWO_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainSparseTensor2d, testSparseTensor2d, {PriorTypes::spikeandslab, PriorTypes::spikeandslab})
.runAndCheck(1950);
}
//=================================================================
TEST_CASE("train_dense_2d_tensor_test_sparse_2d_tensor_normalone_normalone_none_none",
TAG_TWO_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainDenseTensor2d, testSparseTensor2d, {PriorTypes::normalone, PriorTypes::normalone}).runAndCheck(2004);
}
TEST_CASE("train_sparse_2d_tensor_test_sparse_2d_tensor_normalone_normalone_none_none",
TAG_TWO_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainSparseTensor2d, testSparseTensor2d, {PriorTypes::normalone, PriorTypes::normalone}).runAndCheck(2056);
}
//=================================================================
TEST_CASE("train_dense_3d_tensor_test_sparse_3d_tensor_normal_normal_none_none",
TAG_THREE_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainDenseTensor3d, testSparseTensor3d, {PriorTypes::normal, PriorTypes::normal, PriorTypes::normal})
.runAndCheck(2110);
}
TEST_CASE("train_dense_3d_tensor_test_sparse_3d_tensor_spikeandslab_spikeandslab_none_none",
TAG_THREE_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainDenseTensor3d, testSparseTensor3d,
{PriorTypes::spikeandslab, PriorTypes::spikeandslab, PriorTypes::spikeandslab})
.runAndCheck(2164);
}
TEST_CASE("train_dense_3d_tensor_test_sparse_3d_tensor_macau_normal_row_dense_side_info_none",
TAG_THREE_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainDenseTensor3d, testSparseTensor3d, {PriorTypes::macau, PriorTypes::normal, PriorTypes::normal})
.addSideInfo(0, rowSideDenseMatrix3d)
.runAndCheck(2222);
}
TEST_CASE("train_dense_3d_tensor_test_sparse_3d_tensor_macauone_normal_row_dense_side_info_none",
TAG_THREE_DIMENTIONAL_TENSOR_TESTS "[!mayfail]") {
SmurffTest(trainDenseTensor3d, testSparseTensor3d, {PriorTypes::macauone, PriorTypes::normal, PriorTypes::normal})
.addSideInfo(0, rowSideDenseMatrix3d)
.runAndCheck(2280);
}
//=================================================================
TEST_CASE("train_sparse_3d_tensor_test_sparse_3d_tensor_normal_normal_none_none",
TAG_THREE_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainSparseTensor3d, testSparseTensor3d, {PriorTypes::normal, PriorTypes::normal, PriorTypes::normal})
.runAndCheck(3110);
}
TEST_CASE("train_sparse_3d_tensor_test_sparse_3d_tensor_spikeandslab_spikeandslab_none_none",
TAG_THREE_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainSparseTensor3d, testSparseTensor3d,
{PriorTypes::spikeandslab, PriorTypes::spikeandslab, PriorTypes::spikeandslab})
.runAndCheck(3164);
}
TEST_CASE("train_sparse_3d_tensor_test_sparse_3d_tensor_macau_normal_row_dense_side_info_none",
TAG_THREE_DIMENTIONAL_TENSOR_TESTS) {
SmurffTest(trainSparseTensor3d, testSparseTensor3d, {PriorTypes::macau, PriorTypes::normal, PriorTypes::normal})
.addSideInfo(0, rowSideDenseMatrix3d)
.runAndCheck(3222);
}
TEST_CASE("train_sparse_3d_tensor_test_sparse_3d_tensor_macauone_normal_row_dense_side_info_none",
TAG_THREE_DIMENTIONAL_TENSOR_TESTS "[!mayfail]") {
SmurffTest(trainSparseTensor3d, testSparseTensor3d, {PriorTypes::macauone, PriorTypes::normal, PriorTypes::normal})
.addSideInfo(0, rowSideDenseMatrix3d)
.runAndCheck(3280);
}
} // namespace test
} // namespace smurff
| 37.798354 | 126 | 0.728688 | ExaScience |
2df69628b3445d5ba6387fbbd0daa3a06e8d08f5 | 2,340 | cpp | C++ | files/source/objectmask.cpp | Luminyx1/NewerSMBU | 66c719b0afab0c5db5e26b8114d3fc02c15c7300 | [
"MIT"
] | null | null | null | files/source/objectmask.cpp | Luminyx1/NewerSMBU | 66c719b0afab0c5db5e26b8114d3fc02c15c7300 | [
"MIT"
] | null | null | null | files/source/objectmask.cpp | Luminyx1/NewerSMBU | 66c719b0afab0c5db5e26b8114d3fc02c15c7300 | [
"MIT"
] | null | null | null |
#include "game.h"
#include "neweru.h"
#include "groundmask.h"
//Replaces sprite 358
class ObjectMask : public StageActor {
public:
agl::TextureData texdata;
int onCreate();
int onExecute();
int onDraw();
void addMask(Vec3 *pos, float radius);
ObjectMask(ActorBuildInfo *);
static Actor *build(ActorBuildInfo *);
};
ObjectMask::ObjectMask(ActorBuildInfo *buildInfo) : StageActor(buildInfo) {}
Actor *ObjectMask::build(ActorBuildInfo *buildInfo) {
return new ObjectMask(buildInfo);
}
const ActorInfo actorInfo = {0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0};
const Profile profile(ObjectMask::build, SCAFFOLD_WITH_BOLT, "ObjectMask", &actorInfo, 0);
const ActorFiles actorFiles(SCAFFOLD_WITH_BOLT, 0, 0);
int ObjectMask::onCreate() {
MaskTexData::loadTexture(MaskTexture::cave, &texdata);
onExecute();
return 1;
}
int ObjectMask::onExecute() {
StageActor *player = PlayerMgr::instance->players[0];
position = player->position;
return 1;
}
struct ActorMask {
Actors actor;
float radius;
};
ActorMask actorMasks[] = {
GOOMBA, 16,
PARAGOOMBA, 16,
KOOPA_TROOPA, 16,
KOOPA_PARATROOPA, 16,
BUZZY_BEETLE, 16,
SPIKE_TOP, 16,
SPINY, 16,
QSWITCH, 16,
PSWITCH, 16,
BUBBLE_BABY_YOSHI, 24,
BALLOON_BABY_YOSHI, 24,
GLOW_BABY_YOSHI, 24,
MUSHROOM, 16,
FIRE_FLOWER, 16,
ICE_FLOWER, 16,
PROPELLER_MUSHROOM, 16,
PENGUIN_MUSHROOM, 16,
ACORN_MUSHROOM, 16,
MINI_MUSHROOM, 16,
LIFE_MUSHROOM, 16,
LIFE_MOON, 16,
PLAYER_ICEBALL, 12,
PLAYER_FIREBALL, 12
};
int ObjectMask::onDraw() {
addMask(&position, 48);
Actor **current = ActorMgr::instance->actorList.first;
while (current < ActorMgr::instance->actorList.last) {
Actor *actor = *current;
if (actor) {
Actors profileId = actor->getProfileId();
for (u32 i = 0; i < 14; i++) {
if (actorMasks[i].actor == profileId) {
addMask(&((StageActor *)actor)->position, actorMasks[i].radius);
break;
}
}
}
current++;
}
return 1;
}
void ObjectMask::addMask(Vec3 *pos, float radius) {
MaskInfo tl = {{pos->X - radius, pos->Y - radius}, 1, {0, 0}};
MaskInfo tr = {{pos->X + radius, pos->Y - radius}, 1, {1, 0}};
MaskInfo br = {{pos->X + radius, pos->Y + radius}, 1, {1, 1}};
MaskInfo bl = {{pos->X - radius, pos->Y + radius}, 1, {0, 1}};
((NewerBgRenderer *)BgRenderer::instance)->revealMasks.add(&tl, &tr, &br, &bl, &texdata, 3);
}
| 22.941176 | 93 | 0.676068 | Luminyx1 |
2df6d6a0e322a8ae519325c0b3c30265c4fd5428 | 715 | cpp | C++ | libcxx/test/std/utilities/memory/util.smartptr/util.smartptr.weak/util.smartptr.weak.obs/not_less_than.fail.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | libcxx/test/std/utilities/memory/util.smartptr/util.smartptr.weak/util.smartptr.weak.obs/not_less_than.fail.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | libcxx/test/std/utilities/memory/util.smartptr/util.smartptr.weak/util.smartptr.weak.obs/not_less_than.fail.cpp | medismailben/llvm-project | e334a839032fe500c3bba22bf976ab7af13ce1c1 | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// <memory>
// template <class T> class weak_ptr;
//
// not less than comparable
#include <memory>
#include <cassert>
int main(int, char**)
{
const std::shared_ptr<int> p1(new int);
const std::shared_ptr<int> p2(new int);
const std::weak_ptr<int> w1(p1);
const std::weak_ptr<int> w2(p2);
bool b = w1 < w2;
return 0;
}
| 24.655172 | 80 | 0.516084 | medismailben |
2dfb034ef23c7ede4e43dcbd4c84cc83f6de0e08 | 570 | cpp | C++ | C++/problem0070.cpp | 1050669722/LeetCode-Answers | c8f4d1ccaac09cda63b60d75144335347b06dc81 | [
"MIT"
] | null | null | null | C++/problem0070.cpp | 1050669722/LeetCode-Answers | c8f4d1ccaac09cda63b60d75144335347b06dc81 | [
"MIT"
] | null | null | null | C++/problem0070.cpp | 1050669722/LeetCode-Answers | c8f4d1ccaac09cda63b60d75144335347b06dc81 | [
"MIT"
] | null | null | null | //代码中使用的 \texttt{pow}pow 函数的时空复杂度与 CPU 支持的指令集相关;
class Solution {
public:
int climbStairs(int n) {
// if (n == 1)
// {
// return 1;
// }
// else if (n == 2)
// {
// return 2;
// }
// return climbStairs(n - 1) + climbStairs(n - 2);
vector<int> v{1, 2};
for (int i = 2; i < n; ++i)
{
v.push_back(v[i - 1] + v[i - 2]);
}
// cout << n - 1 << ' ' << v.size() << endl;
return v[n - 1];
// return v[v.size() - 1];
}
};
| 21.923077 | 58 | 0.366667 | 1050669722 |
2dff3f699f37bdea6bc7bc03df35961e1ad4d918 | 2,756 | cpp | C++ | 2A. C++ Advanced (STL)/Attic/doubly.cpp | alemesa1991/School-Projects | ed9170fa4cadfe18c6d9850a17077686ca16d1a1 | [
"MIT"
] | null | null | null | 2A. C++ Advanced (STL)/Attic/doubly.cpp | alemesa1991/School-Projects | ed9170fa4cadfe18c6d9850a17077686ca16d1a1 | [
"MIT"
] | null | null | null | 2A. C++ Advanced (STL)/Attic/doubly.cpp | alemesa1991/School-Projects | ed9170fa4cadfe18c6d9850a17077686ca16d1a1 | [
"MIT"
] | null | null | null | // Algorithms - Doubly Linked List
// doubly.cpp
#include <iostream>
using namespace std;
class Data {
int data;
public:
Data(int d = 0) : data(d) {}
int out() const {
return data;
}
};
struct Node {
Data data;
Node* next;
Node* previous;
Node (const Data& d, Node* n, Node* p) :
data(d), next(n), previous(p) {}
};
class DLList {
Node* head;
Node* tail;
Node* current;
public:
DLList() : head(NULL), tail(NULL), current(NULL) {}
~DLList() {
while ( (current = head) ) { // extra () to silence compiler warning
head = head->next;
delete current;
}
}
void goHead() {
current = head;
}
void goNext() {
if (current) current = current->next;
}
void remove() {
if (current) {
Node* p = current;
if (current == head) {
head = head->next;
}
else {
current->next->previous = current->previous;
current->previous->next = current->next;
current = current->next;
}
delete p;
}
}
bool end() {
return !current;
}
Data get() const {
return current ? current->data : Data();
}
void insertBefore(const Data& a) {
if (current) {
Node* p = new (nothrow) Node(a, current,
current->previous);
if (p) {
if (current->previous)
current->previous->next = p;
else
head = p;
current->previous = p;
}
}
else {
Node* p = new (nothrow) Node(a, NULL, NULL);
if (p)
head = tail = current = p;
}
}
void insertAfter(const Data& a) {
if (current) {
Node* p = new (nothrow) Node(a, current->next,
current);
if (p) {
if (current->next)
current->next->previous = p;
else
tail = p;
current->next = p;
}
}
else {
Node* p = new (nothrow) Node(a, NULL, NULL);
if (p)
head = tail = current = p;
}
}
};
int main () {
DLList r;
// Insert Data
r.insertAfter(3);
r.insertAfter(5);
r.goHead();
r.insertAfter(9);
r.goNext();
r.insertAfter(8);
// Display Data
r.goHead();
while (!r.end()) {
cout << r.get().out() << ' ';
r.goNext();
}
cout << "\n";
}
| 23.159664 | 78 | 0.412917 | alemesa1991 |
9301e5d243cf4f39b13265d1037851ae243d1e95 | 1,199 | hpp | C++ | source/Arguments.hpp | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | 8 | 2015-01-23T05:41:46.000Z | 2019-11-20T05:10:27.000Z | source/Arguments.hpp | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | null | null | null | source/Arguments.hpp | fstudio/Phoenix | 28a7c6a3932fd7d6fea12770d0aa1e20bc70db7d | [
"MIT"
] | 4 | 2015-05-05T05:15:43.000Z | 2020-03-07T11:10:56.000Z | /*********************************************************************************************************
* Arguments.hpp
* Note: Phoenix CommandLine Arguments
* Date: @2015.03
* E-mail:<forcemz@outlook.com>
* Copyright (C) 2015 The ForceStudio All Rights Reserved.
**********************************************************************************************************/
#ifndef COMMANDLINEARGUMENTS_HPP
#define COMMANDLINEARGUMENTS_HPP
#pragma once
#include <string>
#include <vector>
enum OptionLevel{
OptionLevel_Normal=0x0000,
OptionLevel_Foreground=0x0001,
OptionLevel_Version=0x0002,
OptionLevel_Usage=0x0004,
OptionLevel_Reset=0x0008,
OptionLevel_Setting=0x0010,
OptionLevel_Init=0x0020,
OptionLevel_New=0x0040,
OptionLevel_UNKNOWN=0xF000
};
enum InstanceLevel{
InstanceLevel_UI=1,
InstanceLevel_Task=2
};
//-Profile with setting profile
struct ProcessParameters{
int cmdMode;////CMD md is mutex.
int taskMode;////is
bool isProfile;
std::wstring profile;
std::vector<std::wstring> vfile;
std::vector<std::wstring> unknowns;
};
bool ArgumentsFlow(ProcessParameters &pparam,bool isStoreUnknownOptions=false);
#endif
| 26.644444 | 107 | 0.616347 | fstudio |
9301f55a1847c1cd83daeb4255a176415fd44397 | 738 | hpp | C++ | src/controllers/actions/npc_action_move.hpp | astrellon/simple-space | 20e98d4f562a78b1efeaedb0a0012f3c9306ac7e | [
"MIT"
] | 1 | 2020-09-23T11:17:35.000Z | 2020-09-23T11:17:35.000Z | src/controllers/actions/npc_action_move.hpp | astrellon/simple-space | 20e98d4f562a78b1efeaedb0a0012f3c9306ac7e | [
"MIT"
] | null | null | null | src/controllers/actions/npc_action_move.hpp | astrellon/simple-space | 20e98d4f562a78b1efeaedb0a0012f3c9306ac7e | [
"MIT"
] | null | null | null | #pragma once
#include <SFML/System.hpp>
#include "npc_action.hpp"
namespace space
{
class NpcActionMove : public NpcAction
{
public:
// Fields
// Constructor
NpcActionMove(NpcController *controller, sf::Vector2f destination);
// Methods
static const std::string ActionType() { return "move-action"; }
virtual std::string type() const { return ActionType(); }
virtual void update(sf::Time dt);
virtual bool isComplete() const;
virtual void onComplete();
private:
// Fields
sf::Vector2f _destination;
float _toDestination;
// Methods
};
} // space | 22.363636 | 79 | 0.554201 | astrellon |
9302276d6a893e28e8e5298ea61964b603b553e4 | 6,680 | cc | C++ | xmllite/xmlbuilder_unittest.cc | MIPS/external-chromium_org-third_party-libjingle-source-talk | 06a093c73d10bd918baa95312974108bf37b54b4 | [
"BSL-1.0",
"BSD-3-Clause"
] | 284 | 2015-01-05T08:31:00.000Z | 2022-03-25T06:12:55.000Z | xmllite/xmlbuilder_unittest.cc | MIPS/external-chromium_org-third_party-libjingle-source-talk | 06a093c73d10bd918baa95312974108bf37b54b4 | [
"BSL-1.0",
"BSD-3-Clause"
] | 1 | 2019-11-12T20:07:52.000Z | 2019-11-12T20:07:52.000Z | xmllite/xmlbuilder_unittest.cc | MIPS/external-chromium_org-third_party-libjingle-source-talk | 06a093c73d10bd918baa95312974108bf37b54b4 | [
"BSL-1.0",
"BSD-3-Clause"
] | 171 | 2015-01-06T06:56:02.000Z | 2022-01-24T03:56:37.000Z | /*
* libjingle
* Copyright 2004, Google Inc.
*
* 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. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <string>
#include <sstream>
#include <iostream>
#include "talk/base/common.h"
#include "talk/base/gunit.h"
#include "talk/xmllite/xmlbuilder.h"
#include "talk/xmllite/xmlelement.h"
#include "talk/xmllite/xmlparser.h"
using buzz::XmlBuilder;
using buzz::XmlElement;
using buzz::XmlParser;
TEST(XmlBuilderTest, TestTrivial) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing/>");
EXPECT_EQ("<testing/>", builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestAttributes1) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing a='b'/>");
EXPECT_EQ("<testing a=\"b\"/>", builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestAttributes2) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing e='' long='some text'/>");
EXPECT_EQ("<testing e=\"\" long=\"some text\"/>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestNesting1) {
XmlBuilder builder;
XmlParser::ParseXml(&builder,
"<top><first/><second><third></third></second></top>");
EXPECT_EQ("<top><first/><second><third/></second></top>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestNesting2) {
XmlBuilder builder;
XmlParser::ParseXml(&builder,
"<top><fifth><deeper><and><deeper/></and><sibling><leaf/>"
"</sibling></deeper></fifth><first/><second><third></third>"
"</second></top>");
EXPECT_EQ("<top><fifth><deeper><and><deeper/></and><sibling><leaf/>"
"</sibling></deeper></fifth><first/><second><third/>"
"</second></top>", builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestQuoting1) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing a='>'/>");
EXPECT_EQ("<testing a=\">\"/>", builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestQuoting2) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing a='<>&"'/>");
EXPECT_EQ("<testing a=\"<>&"\"/>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestQuoting3) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing a='so "important"'/>");
EXPECT_EQ("<testing a=\"so "important"\"/>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestQuoting4) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing a='"important", yes'/>");
EXPECT_EQ("<testing a=\""important", yes\"/>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestQuoting5) {
XmlBuilder builder;
XmlParser::ParseXml(&builder,
"<testing a='<what is "important">'/>");
EXPECT_EQ("<testing a=\"<what is "important">\"/>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestText1) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing>></testing>");
EXPECT_EQ("<testing>></testing>", builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestText2) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing><>&"</testing>");
EXPECT_EQ("<testing><>&\"</testing>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestText3) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing>so <important></testing>");
EXPECT_EQ("<testing>so <important></testing>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestText4) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing><important>, yes</testing>");
EXPECT_EQ("<testing><important>, yes</testing>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestText5) {
XmlBuilder builder;
XmlParser::ParseXml(&builder,
"<testing>importance &<important>&</testing>");
EXPECT_EQ("<testing>importance &<important>&</testing>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestNamespace1) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing xmlns='foo'/>");
EXPECT_EQ("<testing xmlns=\"foo\"/>", builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestNamespace2) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing xmlns:a='foo' a:b='c'/>");
EXPECT_EQ("<testing xmlns:a=\"foo\" a:b=\"c\"/>",
builder.BuiltElement()->Str());
}
TEST(XmlBuilderTest, TestNamespace3) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing xmlns:a=''/>");
EXPECT_TRUE(NULL == builder.BuiltElement());
}
TEST(XmlBuilderTest, TestNamespace4) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing a:b='c'/>");
EXPECT_TRUE(NULL == builder.BuiltElement());
}
TEST(XmlBuilderTest, TestAttrCollision1) {
XmlBuilder builder;
XmlParser::ParseXml(&builder, "<testing a='first' a='second'/>");
EXPECT_TRUE(NULL == builder.BuiltElement());
}
TEST(XmlBuilderTest, TestAttrCollision2) {
XmlBuilder builder;
XmlParser::ParseXml(&builder,
"<testing xmlns:a='foo' xmlns:b='foo' a:x='c' b:x='d'/>");
EXPECT_TRUE(NULL == builder.BuiltElement());
}
TEST(XmlBuilderTest, TestAttrCollision3) {
XmlBuilder builder;
XmlParser::ParseXml(&builder,
"<testing xmlns:a='foo'><nested xmlns:b='foo' a:x='c' b:x='d'/>"
"</testing>");
EXPECT_TRUE(NULL == builder.BuiltElement());
}
| 34.25641 | 80 | 0.69012 | MIPS |
930321bc2357c214572a970bb2f9f8a715355734 | 17,090 | cpp | C++ | B2G/gecko/js/src/ion/x64/Trampoline-x64.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/js/src/ion/x64/Trampoline-x64.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/js/src/ion/x64/Trampoline-x64.cpp | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=4 sw=4 et tw=99:
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "jscompartment.h"
#include "assembler/assembler/MacroAssembler.h"
#include "ion/IonCompartment.h"
#include "ion/IonLinker.h"
#include "ion/IonFrames.h"
#include "ion/Bailouts.h"
#include "ion/VMFunctions.h"
#include "ion/IonSpewer.h"
#include "jsscriptinlines.h"
using namespace js;
using namespace js::ion;
/* This method generates a trampoline on x64 for a c++ function with
* the following signature:
* JSBool blah(void *code, int argc, Value *argv, Value *vp)
* ...using standard x64 fastcall calling convention
*/
IonCode *
IonCompartment::generateEnterJIT(JSContext *cx)
{
MacroAssembler masm(cx);
const Register reg_code = IntArgReg0;
const Register reg_argc = IntArgReg1;
const Register reg_argv = IntArgReg2;
JS_ASSERT(OsrFrameReg == IntArgReg3);
#if defined(_WIN64)
const Operand token = Operand(rbp, 16 + ShadowStackSpace);
const Operand result = Operand(rbp, 24 + ShadowStackSpace);
#else
const Register token = IntArgReg4;
const Register result = IntArgReg5;
#endif
// Save old stack frame pointer, set new stack frame pointer.
masm.push(rbp);
masm.mov(rsp, rbp);
// Save non-volatile registers. These must be saved by the trampoline, rather
// than by the JIT'd code, because they are scanned by the conservative scanner.
masm.push(rbx);
masm.push(r12);
masm.push(r13);
masm.push(r14);
masm.push(r15);
#if defined(_WIN64)
masm.push(rdi);
masm.push(rsi);
// 16-byte aligment for movdqa
masm.subq(Imm32(16 * 10 + 8), rsp);
masm.movdqa(xmm6, Operand(rsp, 16 * 0));
masm.movdqa(xmm7, Operand(rsp, 16 * 1));
masm.movdqa(xmm8, Operand(rsp, 16 * 2));
masm.movdqa(xmm9, Operand(rsp, 16 * 3));
masm.movdqa(xmm10, Operand(rsp, 16 * 4));
masm.movdqa(xmm11, Operand(rsp, 16 * 5));
masm.movdqa(xmm12, Operand(rsp, 16 * 6));
masm.movdqa(xmm13, Operand(rsp, 16 * 7));
masm.movdqa(xmm14, Operand(rsp, 16 * 8));
masm.movdqa(xmm15, Operand(rsp, 16 * 9));
#endif
// Save arguments passed in registers needed after function call.
masm.push(result);
// Remember stack depth without padding and arguments.
masm.mov(rsp, r14);
// Remember number of bytes occupied by argument vector
masm.mov(reg_argc, r13);
masm.shll(Imm32(3), r13);
// Guarantee 16-byte alignment.
// We push argc, callee token, frame size, and return address.
// The latter two are 16 bytes together, so we only consider argc and the
// token.
masm.mov(rsp, r12);
masm.subq(r13, r12);
masm.subq(Imm32(8), r12);
masm.andl(Imm32(0xf), r12);
masm.subq(r12, rsp);
/***************************************************************
Loop over argv vector, push arguments onto stack in reverse order
***************************************************************/
// r13 still stores the number of bytes in the argument vector.
masm.addq(reg_argv, r13); // r13 points above last argument.
// while r13 > rdx, push arguments.
{
Label header, footer;
masm.bind(&header);
masm.cmpq(r13, reg_argv);
masm.j(AssemblerX86Shared::BelowOrEqual, &footer);
masm.subq(Imm32(8), r13);
masm.push(Operand(r13, 0));
masm.jmp(&header);
masm.bind(&footer);
}
// Push the number of actual arguments. |result| is used to store the
// actual number of arguments without adding an extra argument to the enter
// JIT.
masm.movq(result, reg_argc);
masm.unboxInt32(Operand(reg_argc, 0), reg_argc);
masm.push(reg_argc);
// Push the callee token.
masm.push(token);
/*****************************************************************
Push the number of bytes we've pushed so far on the stack and call
*****************************************************************/
masm.subq(rsp, r14);
// Create a frame descriptor.
masm.makeFrameDescriptor(r14, IonFrame_Entry);
masm.push(r14);
// Call function.
masm.call(reg_code);
// Pop arguments and padding from stack.
masm.pop(r14); // Pop and decode descriptor.
masm.shrq(Imm32(FRAMESIZE_SHIFT), r14);
masm.addq(r14, rsp); // Remove arguments.
/*****************************************************************
Place return value where it belongs, pop all saved registers
*****************************************************************/
masm.pop(r12); // vp
masm.storeValue(JSReturnOperand, Operand(r12, 0));
// Restore non-volatile registers.
#if defined(_WIN64)
masm.movdqa(Operand(rsp, 16 * 0), xmm6);
masm.movdqa(Operand(rsp, 16 * 1), xmm7);
masm.movdqa(Operand(rsp, 16 * 2), xmm8);
masm.movdqa(Operand(rsp, 16 * 3), xmm9);
masm.movdqa(Operand(rsp, 16 * 4), xmm10);
masm.movdqa(Operand(rsp, 16 * 5), xmm11);
masm.movdqa(Operand(rsp, 16 * 6), xmm12);
masm.movdqa(Operand(rsp, 16 * 7), xmm13);
masm.movdqa(Operand(rsp, 16 * 8), xmm14);
masm.movdqa(Operand(rsp, 16 * 9), xmm15);
masm.addq(Imm32(16 * 10 + 8), rsp);
masm.pop(rsi);
masm.pop(rdi);
#endif
masm.pop(r15);
masm.pop(r14);
masm.pop(r13);
masm.pop(r12);
masm.pop(rbx);
// Restore frame pointer and return.
masm.pop(rbp);
masm.ret();
Linker linker(masm);
return linker.newCode(cx);
}
IonCode *
IonCompartment::generateReturnError(JSContext *cx)
{
MacroAssembler masm(cx);
masm.pop(r14); // sizeDescriptor.
masm.xorl(Imm32(0x1), r14); // Unmark EntryFrame.
masm.addq(r14, rsp); // Remove arguments.
masm.pop(r11); // Discard |vp|: returning from error.
Linker linker(masm);
return linker.newCode(cx);
}
IonCode *
IonCompartment::generateInvalidator(JSContext *cx)
{
AutoIonContextAlloc aica(cx);
MacroAssembler masm(cx);
// See explanatory comment in x86's IonCompartment::generateInvalidator.
masm.addq(Imm32(sizeof(uintptr_t)), rsp);
// Push registers such that we can access them from [base + code].
masm.reserveStack(Registers::Total * sizeof(void *));
for (uint32 i = 0; i < Registers::Total; i++)
masm.movq(Register::FromCode(i), Operand(rsp, i * sizeof(void *)));
// Push xmm registers, such that we can access them from [base + code].
masm.reserveStack(FloatRegisters::Total * sizeof(double));
for (uint32 i = 0; i < FloatRegisters::Total; i++)
masm.movsd(FloatRegister::FromCode(i), Operand(rsp, i * sizeof(double)));
masm.movq(rsp, rbx); // Argument to ion::InvalidationBailout.
// Make space for InvalidationBailout's frameSize outparam.
masm.reserveStack(sizeof(size_t));
masm.movq(rsp, rcx);
masm.setupUnalignedABICall(2, rdx);
masm.passABIArg(rbx);
masm.passABIArg(rcx);
masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, InvalidationBailout));
masm.pop(rbx); // Get the frameSize outparam.
// Pop the machine state and the dead frame.
masm.lea(Operand(rsp, rbx, TimesOne, sizeof(InvalidationBailoutStack)), rsp);
masm.generateBailoutTail(rdx);
Linker linker(masm);
return linker.newCode(cx);
}
IonCode *
IonCompartment::generateArgumentsRectifier(JSContext *cx)
{
// Do not erase the frame pointer in this function.
MacroAssembler masm(cx);
// ArgumentsRectifierReg contains the |nargs| pushed onto the current frame.
// Including |this|, there are (|nargs| + 1) arguments to copy.
JS_ASSERT(ArgumentsRectifierReg == r8);
// Load the number of |undefined|s to push into %rcx.
masm.movq(Operand(rsp, IonRectifierFrameLayout::offsetOfCalleeToken()), rax);
masm.movzwl(Operand(rax, offsetof(JSFunction, nargs)), rcx);
masm.subq(r8, rcx);
// Copy the number of actual arguments
masm.movq(Operand(rsp, IonRectifierFrameLayout::offsetOfNumActualArgs()), rdx);
masm.moveValue(UndefinedValue(), r10);
masm.movq(rsp, r9); // Save %rsp.
// Push undefined.
{
Label undefLoopTop;
masm.bind(&undefLoopTop);
masm.push(r10);
masm.subl(Imm32(1), rcx);
masm.testl(rcx, rcx);
masm.j(Assembler::NonZero, &undefLoopTop);
}
// Get the topmost argument.
BaseIndex b = BaseIndex(r9, r8, TimesEight, sizeof(IonRectifierFrameLayout));
masm.lea(Operand(b), rcx);
// Push arguments, |nargs| + 1 times (to include |this|).
{
Label copyLoopTop, initialSkip;
masm.jump(&initialSkip);
masm.bind(©LoopTop);
masm.subq(Imm32(sizeof(Value)), rcx);
masm.subl(Imm32(1), r8);
masm.bind(&initialSkip);
masm.push(Operand(rcx, 0x0));
masm.testl(r8, r8);
masm.j(Assembler::NonZero, ©LoopTop);
}
// Construct descriptor.
masm.subq(rsp, r9);
masm.makeFrameDescriptor(r9, IonFrame_Rectifier);
// Construct IonJSFrameLayout.
masm.push(rdx); // numActualArgs
masm.push(rax); // calleeToken
masm.push(r9); // descriptor
// Call the target function.
// Note that this code assumes the function is JITted.
masm.movq(Operand(rax, offsetof(JSFunction, u.i.script_)), rax);
masm.movq(Operand(rax, offsetof(JSScript, ion)), rax);
masm.movq(Operand(rax, IonScript::offsetOfMethod()), rax);
masm.movq(Operand(rax, IonCode::offsetOfCode()), rax);
masm.call(rax);
// Remove the rectifier frame.
masm.pop(r9); // r9 <- descriptor with FrameType.
masm.shrq(Imm32(FRAMESIZE_SHIFT), r9);
masm.pop(r11); // Discard calleeToken.
masm.pop(r11); // Discard numActualArgs.
masm.addq(r9, rsp); // Discard pushed arguments.
masm.ret();
Linker linker(masm);
return linker.newCode(cx);
}
static void
GenerateBailoutThunk(JSContext *cx, MacroAssembler &masm, uint32 frameClass)
{
// Push registers such that we can access them from [base + code].
masm.reserveStack(Registers::Total * sizeof(void *));
for (uint32 i = 0; i < Registers::Total; i++)
masm.movq(Register::FromCode(i), Operand(rsp, i * sizeof(void *)));
// Push xmm registers, such that we can access them from [base + code].
masm.reserveStack(FloatRegisters::Total * sizeof(double));
for (uint32 i = 0; i < FloatRegisters::Total; i++)
masm.movsd(FloatRegister::FromCode(i), Operand(rsp, i * sizeof(double)));
// Get the stack pointer into a register, pre-alignment.
masm.movq(rsp, r8);
// Call the bailout function.
masm.setupUnalignedABICall(1, rax);
masm.passABIArg(r8);
masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, Bailout));
// Stack is:
// [frame]
// snapshotOffset
// frameSize
// [bailoutFrame]
//
// Remove both the bailout frame and the topmost Ion frame's stack.
static const uint32 BailoutDataSize = sizeof(void *) * Registers::Total +
sizeof(double) * FloatRegisters::Total;
masm.addq(Imm32(BailoutDataSize), rsp);
masm.pop(rcx);
masm.lea(Operand(rsp, rcx, TimesOne, sizeof(void *)), rsp);
masm.generateBailoutTail(rdx);
}
IonCode *
IonCompartment::generateBailoutTable(JSContext *cx, uint32 frameClass)
{
JS_NOT_REACHED("x64 does not use bailout tables");
return NULL;
}
IonCode *
IonCompartment::generateBailoutHandler(JSContext *cx)
{
MacroAssembler masm;
GenerateBailoutThunk(cx, masm, NO_FRAME_SIZE_CLASS_ID);
Linker linker(masm);
return linker.newCode(cx);
}
IonCode *
IonCompartment::generateVMWrapper(JSContext *cx, const VMFunction &f)
{
typedef MoveResolver::MoveOperand MoveOperand;
JS_ASSERT(!StackKeptAligned);
JS_ASSERT(functionWrappers_);
JS_ASSERT(functionWrappers_->initialized());
VMWrapperMap::AddPtr p = functionWrappers_->lookupForAdd(&f);
if (p)
return p->value;
// Generate a separated code for the wrapper.
MacroAssembler masm;
// Avoid conflicts with argument registers while discarding the result after
// the function call.
GeneralRegisterSet regs = GeneralRegisterSet(Register::Codes::WrapperMask);
// Wrapper register set is a superset of Volatile register set.
JS_STATIC_ASSERT((Register::Codes::VolatileMask & ~Register::Codes::WrapperMask) == 0);
// Stack is:
// ... frame ...
// +12 [args]
// +8 descriptor
// +0 returnAddress
//
// We're aligned to an exit frame, so link it up.
masm.enterExitFrame(&f);
// Save the current stack pointer as the base for copying arguments.
Register argsBase = InvalidReg;
if (f.explicitArgs) {
argsBase = r10;
regs.take(argsBase);
masm.lea(Operand(rsp,IonExitFrameLayout::SizeWithFooter()), argsBase);
}
// Reserve space for the outparameter.
Register outReg = InvalidReg;
switch (f.outParam) {
case Type_Value:
outReg = regs.takeAny();
masm.reserveStack(sizeof(Value));
masm.movq(esp, outReg);
break;
case Type_Handle:
outReg = regs.takeAny();
masm.Push(UndefinedValue());
masm.movq(esp, outReg);
break;
case Type_Int32:
outReg = regs.takeAny();
masm.reserveStack(sizeof(int32));
masm.movq(esp, outReg);
break;
default:
JS_ASSERT(f.outParam == Type_Void);
break;
}
Register temp = regs.getAny();
masm.setupUnalignedABICall(f.argc(), temp);
// Initialize the context parameter.
Register cxreg = IntArgReg0;
masm.loadJSContext(cxreg);
masm.passABIArg(cxreg);
size_t argDisp = 0;
// Copy arguments.
if (f.explicitArgs) {
for (uint32 explicitArg = 0; explicitArg < f.explicitArgs; explicitArg++) {
MoveOperand from;
switch (f.argProperties(explicitArg)) {
case VMFunction::WordByValue:
masm.passABIArg(MoveOperand(argsBase, argDisp));
argDisp += sizeof(void *);
break;
case VMFunction::WordByRef:
masm.passABIArg(MoveOperand(argsBase, argDisp, MoveOperand::EFFECTIVE));
argDisp += sizeof(void *);
break;
case VMFunction::DoubleByValue:
case VMFunction::DoubleByRef:
JS_NOT_REACHED("NYI: x64 callVM should not be used with 128bits values.");
break;
}
}
}
// Copy the implicit outparam, if any.
if (outReg != InvalidReg)
masm.passABIArg(outReg);
masm.callWithABI(f.wrapped);
// Test for failure.
Label exception;
switch (f.failType()) {
case Type_Object:
masm.testq(rax, rax);
masm.j(Assembler::Zero, &exception);
break;
case Type_Bool:
masm.testb(rax, rax);
masm.j(Assembler::Zero, &exception);
break;
default:
JS_NOT_REACHED("unknown failure kind");
break;
}
// Load the outparam and free any allocated stack.
switch (f.outParam) {
case Type_Handle:
case Type_Value:
masm.loadValue(Address(esp, 0), JSReturnOperand);
masm.freeStack(sizeof(Value));
break;
case Type_Int32:
masm.load32(Address(esp, 0), ReturnReg);
masm.freeStack(sizeof(int32));
break;
default:
JS_ASSERT(f.outParam == Type_Void);
break;
}
masm.leaveExitFrame();
masm.retn(Imm32(sizeof(IonExitFrameLayout) + f.explicitStackSlots() * sizeof(void *)));
masm.bind(&exception);
masm.handleException();
Linker linker(masm);
IonCode *wrapper = linker.newCode(cx);
if (!wrapper)
return NULL;
// linker.newCode may trigger a GC and sweep functionWrappers_ so we have to
// use relookupOrAdd instead of add.
if (!functionWrappers_->relookupOrAdd(p, &f, wrapper))
return NULL;
return wrapper;
}
IonCode *
IonCompartment::generatePreBarrier(JSContext *cx, MIRType type)
{
MacroAssembler masm;
RegisterSet regs = RegisterSet(GeneralRegisterSet(Registers::VolatileMask),
FloatRegisterSet(FloatRegisters::VolatileMask));
masm.PushRegsInMask(regs);
JS_ASSERT(PreBarrierReg == rdx);
masm.movq(ImmWord(cx->compartment), rcx);
masm.setupUnalignedABICall(2, rax);
masm.passABIArg(rcx);
masm.passABIArg(rdx);
if (type == MIRType_Value) {
masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, MarkValueFromIon));
} else {
JS_ASSERT(type == MIRType_Shape);
masm.callWithABI(JS_FUNC_TO_DATA_PTR(void *, MarkShapeFromIon));
}
masm.PopRegsInMask(regs);
masm.ret();
Linker linker(masm);
return linker.newCode(cx);
}
| 30.463458 | 91 | 0.625278 | wilebeast |
930822c3bd7b3c5b7d843281c62c2fcfad70ea0e | 5,950 | cpp | C++ | tests/filesource.cpp | therocode/rexource | 0de08b9cce20930b19ddcd6780e7e4a173e9782f | [
"MIT"
] | 5 | 2016-02-07T21:39:50.000Z | 2017-09-16T23:31:30.000Z | tests/filesource.cpp | therocode/rexource | 0de08b9cce20930b19ddcd6780e7e4a173e9782f | [
"MIT"
] | null | null | null | tests/filesource.cpp | therocode/rexource | 0de08b9cce20930b19ddcd6780e7e4a173e9782f | [
"MIT"
] | null | null | null | #include <catch.hpp>
#include "helpers/treefilesource.hpp"
SCENARIO("File sources set to a folder with a regex will find files recursively with the regex as a filter")
{
GIVEN("a file source which is set to read all files in a directory")
{
TreeFileSource treeSource("tests/data/trees", std::regex(".*"));
WHEN("all contained resurces are listed by the source")
{
auto trees = treeSource.list();
THEN("the list contains the expected result")
{
REQUIRE(trees.size() == 1000);
std::set<std::string> paths(trees.begin(), trees.end());
for(int32_t i = 0; i < 1000; ++i)
{
std::string expectedId = "tree" + std::to_string(i);
CHECK(paths.count(expectedId) != 0);
}
}
}
}
GIVEN("a file source which is set to read all files with a number in the 500s in a directory")
{
TreeFileSource treeSource("tests/data/trees", std::regex(".*5\\d\\d.*"));
WHEN("all contained resurces are listed by the source")
{
auto trees = treeSource.list();
THEN("the list contains the expected result")
{
REQUIRE(trees.size() == 100);
std::set<std::string> paths(trees.begin(), trees.end());
for(int32_t i = 500; i < 600; ++i)
{
std::string expectedId = "tree" + std::to_string(i);
CHECK(paths.count(expectedId) != 0);
}
}
}
}
GIVEN("a file source which is not given a regex")
{
TreeFileSource treeSource("tests/data/trees");
WHEN("all contained resurces are listed by the source")
{
auto trees = treeSource.list();
THEN("the list contains all the files")
{
REQUIRE(trees.size() == 1000);
std::set<std::string> paths(trees.begin(), trees.end());
for(int32_t i = 0; i < 1000; ++i)
{
std::string expectedId = "tree" + std::to_string(i);
CHECK(paths.count(expectedId) != 0);
}
}
}
}
GIVEN("a file source which is set to read all files within a directory that doesn't exist")
{
WHEN("all contained resurces are listed by the source")
{
THEN("an exception is thrown")
{
CHECK_THROWS_AS(TreeFileSource("tests/data/tres", std::regex(".*")), rex::InvalidFileException);
}
}
}
}
SCENARIO("File sources name resources differently based on the Naming flag. This affects ambiguity of resources")
{
GIVEN("")
{
WHEN("a file source is used to load a folder with entirely unique file names")
{
THEN("it doesn't throw with Naming::NO_EXT")
{
CHECK_NOTHROW(TreeFileSource("tests/data/unique", std::regex(".*"), rex::Naming::NO_EXT));
}
THEN("it doesn't throw with Naming::FILE_NAME")
{
CHECK_NOTHROW(TreeFileSource("tests/data/unique", std::regex(".*"), rex::Naming::FILE_NAME));
}
THEN("it doesn't throw with Naming::PATH")
{
CHECK_NOTHROW(TreeFileSource("tests/data/unique", std::regex(".*"), rex::Naming::PATH));
}
}
WHEN("a file source is used to load a folder with file names that collide with file extensions")
{
THEN("it throws with Naming::NO_EXT")
{
CHECK_THROWS_AS(TreeFileSource("tests/data/collide_ext", std::regex(".*"), rex::Naming::NO_EXT), rex::AmbiguousNameException);
}
THEN("it throws with Naming::FILE_NAME")
{
CHECK_THROWS_AS(TreeFileSource("tests/data/collide_ext", std::regex(".*"), rex::Naming::FILE_NAME), rex::AmbiguousNameException);
}
THEN("it doesn't throw with Naming::PATH")
{
CHECK_NOTHROW(TreeFileSource("tests/data/collide_ext", std::regex(".*"), rex::Naming::PATH));
}
}
WHEN("a file source is used to load a folder with file names that collide without file extensions")
{
THEN("it throws with Naming::NO_EXT")
{
CHECK_THROWS_AS(TreeFileSource("tests/data/collide_no_ext", std::regex(".*"), rex::Naming::NO_EXT), rex::AmbiguousNameException);
}
THEN("it doesn't throw with Naming::FILE_NAME")
{
CHECK_NOTHROW(TreeFileSource("tests/data/collide_no_ext", std::regex(".*"), rex::Naming::FILE_NAME));
}
THEN("it doesn't throw with Naming::PATH")
{
CHECK_NOTHROW(TreeFileSource("tests/data/collide_no_ext", std::regex(".*"), rex::Naming::PATH));
}
}
}
}
SCENARIO("a file source can be used to access the resources it represents")
{
GIVEN("a file source setup to a directory with resources")
{
TreeFileSource treeSource("tests/data/trees");
WHEN("existing resources are accessed")
{
const Tree& tree1 = treeSource.load("tree1");
const Tree& tree2 = treeSource.load("tree2");
THEN("the resources have correct values")
{
CHECK(tree1.leafType == "gigantic");
CHECK(tree1.branchingFactor == Approx(65.7f));
CHECK(tree1.barkType == "naked");
CHECK(tree1.height == Approx(5.2f));
CHECK(tree2.leafType == "wide");
CHECK(tree2.branchingFactor == Approx(78.1f));
CHECK(tree2.barkType == "paper");
CHECK(tree2.height == Approx(43.2f));
}
}
}
}
| 35 | 145 | 0.529748 | therocode |
93083a3238bf41db9f725c8a83e96c8256dc68f9 | 2,036 | cpp | C++ | src/WindowManager.cpp | jamiesyme/MoxelEd | b8ad87587057a79ce0324fd5e3c1290a760adc7a | [
"Unlicense"
] | 1 | 2016-03-09T01:32:22.000Z | 2016-03-09T01:32:22.000Z | src/WindowManager.cpp | jamiesyme/MoxelEd | b8ad87587057a79ce0324fd5e3c1290a760adc7a | [
"Unlicense"
] | null | null | null | src/WindowManager.cpp | jamiesyme/MoxelEd | b8ad87587057a79ce0324fd5e3c1290a760adc7a | [
"Unlicense"
] | null | null | null | #include "WindowManager.hpp"
#include "Window.hpp"
#include "GlHelper.hpp"
#include "App.hpp"
#include <iostream>
WindowManager::WindowManager(App* app)
{
m_app = app;
m_mouseX = 0;
m_mouseY = 0;
m_nextWindowY = 0;
}
WindowManager::~WindowManager()
{
while (m_windows.size() != 0)
destroyWindow(m_windows[0]);
}
void WindowManager::draw()
{
GlHelper gl;
gl.disableDepthTest();
gl.setWindowSize(m_app->getWindowWidth(), m_app->getWindowHeight());
gl.enableOrtho();
for (int i = (int)m_windows.size() - 1; i >= 0; i--)
m_windows[i]->draw();
}
bool WindowManager::mousePress(const int button)
{
int selectIndex = -1;
bool quitEarly = false;
for (unsigned int i = 0; i < m_windows.size(); i++)
{
if (selectIndex == -1 && m_windows[i]->isOver(m_mouseX, m_mouseY))
selectIndex = (int)i;
if (m_windows[i]->mousePress(button))
{
quitEarly = true;
break;
}
}
if (selectIndex != -1)
{
Window* newFront = m_windows[selectIndex];
for (int i = selectIndex; i > 0; i--)
m_windows[i] = m_windows[i - 1];
m_windows[0] = newFront;
}
return quitEarly;
}
void WindowManager::mouseRelease(const int button)
{
for (unsigned int i = 0; i < m_windows.size(); i++)
m_windows[i]->mouseRelease(button);
return;
}
bool WindowManager::mouseMove(const int x, const int y)
{
m_mouseX = x;
m_mouseY = y;
for (unsigned int i = 0; i < m_windows.size(); i++)
if (m_windows[i]->mouseMove(x, y))
return true;
return false;
}
bool WindowManager::mouseWheelMove(const int w)
{
for (unsigned int i = 0; i < m_windows.size(); i++)
if (m_windows[i]->mouseWheelMove(w))
return true;
return false;
}
Window* WindowManager::createWindow()
{
Window* w = new Window();
w->setY(m_nextWindowY);
m_nextWindowY += w->getHeadSizeY() + 1;
m_windows.push_back(w);
return w;
}
void WindowManager::destroyWindow(Window* w)
{
for (unsigned int i = 0; i < m_windows.size(); i++)
{
if (w == m_windows[i])
{
delete w;
m_windows.erase(m_windows.begin() + i);
return;
}
}
}
| 16.826446 | 69 | 0.649312 | jamiesyme |
9308b2575e79755371a4ea80004e21d00a4acdde | 1,421 | cpp | C++ | src/main/cpp/logging/CSVUtil.cpp | frc3512/Robot-2020 | c6811155900ccffba93ea9ba131192dcb9fcb1bd | [
"BSD-3-Clause"
] | 10 | 2020-02-07T04:13:15.000Z | 2022-02-26T00:13:39.000Z | src/main/cpp/logging/CSVUtil.cpp | frc3512/Robot-2020 | c6811155900ccffba93ea9ba131192dcb9fcb1bd | [
"BSD-3-Clause"
] | 82 | 2020-02-12T03:05:15.000Z | 2022-02-18T02:14:38.000Z | src/main/cpp/logging/CSVUtil.cpp | frc3512/Robot-2020 | c6811155900ccffba93ea9ba131192dcb9fcb1bd | [
"BSD-3-Clause"
] | 5 | 2020-02-14T16:24:01.000Z | 2022-03-31T09:10:01.000Z | // Copyright (c) 2020-2021 FRC Team 3512. All Rights Reserved.
#include "logging/CSVUtil.hpp"
#include <algorithm>
#if __has_include(<filesystem>)
#include <filesystem>
#elif __has_include(<experimental/filesystem>)
#include <experimental/filesystem>
namespace std {
namespace filesystem = experimental::filesystem;
} // namespace std
#endif
#include <frc2/Timer.h>
namespace frc3512 {
constexpr bool ends_with(std::string_view str, std::string_view x) noexcept {
return str.size() >= x.size() &&
str.compare(str.size() - x.size(), std::string_view::npos, x) == 0;
}
void DeleteCSVs() {
#if !defined(__FRC_ROBORIO__)
namespace fs = std::filesystem;
// Delete CSV files
for (auto& p : fs::recursive_directory_iterator(".")) {
if (!p.is_directory() && ends_with(p.path().string(), ".csv")) {
fs::remove(p.path());
}
}
// Delete empty directories
for (auto& p : fs::directory_iterator(".")) {
if (p.is_directory()) {
auto childPath = fs::recursive_directory_iterator(p.path());
auto numFiles =
std::count_if(fs::begin(childPath), fs::end(childPath),
[](const auto& p) { return !p.is_directory(); });
if (numFiles == 0) {
fs::remove_all(p.path());
}
}
}
#endif // !defined(__FRC_ROBORIO__)
}
} // namespace frc3512
| 27.326923 | 79 | 0.599578 | frc3512 |
93097b0e546672fa8fa1ee5491a5fd642ca8e8d0 | 2,029 | cpp | C++ | Plain/src/Runtime/Rendering/Backend/VulkanCommandRecording.cpp | Gaukler/PlainRenderer | cf0f41a2300bee9f29a886230c061776cb29ba5e | [
"MIT"
] | 9 | 2021-04-09T14:07:45.000Z | 2022-03-06T07:51:14.000Z | Plain/src/Runtime/Rendering/Backend/VulkanCommandRecording.cpp | Gaukler/PlainRenderer | cf0f41a2300bee9f29a886230c061776cb29ba5e | [
"MIT"
] | 14 | 2021-04-10T11:06:06.000Z | 2021-05-07T14:20:34.000Z | Plain/src/Runtime/Rendering/Backend/VulkanCommandRecording.cpp | Gaukler/PlainRenderer | cf0f41a2300bee9f29a886230c061776cb29ba5e | [
"MIT"
] | null | null | null | #include "pch.h"
#include "VulkanCommandRecording.h"
#include "VulkanContext.h"
void resetCommandBuffer(const VkCommandBuffer buffer) {
auto res = vkResetCommandBuffer(buffer, 0);
checkVulkanResult(res);
}
void beginCommandBuffer(const VkCommandBuffer buffer, const VkCommandBufferUsageFlags usageFlags,
const VkCommandBufferInheritanceInfo* pInheritance) {
VkCommandBufferBeginInfo beginInfo = {};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
beginInfo.pNext = nullptr;
beginInfo.flags = usageFlags;
beginInfo.pInheritanceInfo = pInheritance;
const auto res = vkBeginCommandBuffer(buffer, &beginInfo);
checkVulkanResult(res);
}
void endCommandBufferRecording(const VkCommandBuffer cmdBuffer) {
const auto result = vkEndCommandBuffer(cmdBuffer);
checkVulkanResult;
}
VkCommandBufferInheritanceInfo createCommandBufferInheritanceInfo(const VkRenderPass renderPass,
const VkFramebuffer framebuffer) {
VkCommandBufferInheritanceInfo inheritanceInfo;
inheritanceInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO;
inheritanceInfo.pNext = nullptr;
inheritanceInfo.renderPass = renderPass;
inheritanceInfo.subpass = 0;
inheritanceInfo.framebuffer = framebuffer;
inheritanceInfo.occlusionQueryEnable = false;
inheritanceInfo.queryFlags = 0;
inheritanceInfo.pipelineStatistics = 0;
return inheritanceInfo;
}
void recordSetViewportCommand(const VkCommandBuffer buffer, const float width, const float height) {
VkViewport viewport;
viewport.x = 0;
viewport.y = 0;
viewport.width = width;
viewport.height = height;
viewport.minDepth = 0.f;
viewport.maxDepth = 1.f;
vkCmdSetViewport(buffer, 0, 1, &viewport);
}
void recordSetScissorCommand(const VkCommandBuffer buffer, const float width, const float height) {
VkRect2D scissor;
scissor.offset = { 0, 0 };
scissor.extent.width = width;
scissor.extent.height = height;
vkCmdSetScissor(buffer, 0, 1, &scissor);
} | 34.982759 | 100 | 0.765402 | Gaukler |
930ddd595a06b78fcd816253870aa15d61e90d82 | 974 | hpp | C++ | LEDTableApps/include/LEDTableApps/pong.hpp | michaelbarbera/LEDTableEngine | d7f5fd1e3030c0833086269a6c462954c0fe4d18 | [
"Apache-2.0"
] | 53 | 2018-03-12T12:39:53.000Z | 2021-08-21T02:41:10.000Z | LEDTableApps/include/LEDTableApps/pong.hpp | michaelbarbera/LEDTableEngine | d7f5fd1e3030c0833086269a6c462954c0fe4d18 | [
"Apache-2.0"
] | 29 | 2018-01-24T15:46:47.000Z | 2021-05-14T12:04:06.000Z | LEDTableApps/include/LEDTableApps/pong.hpp | michaelbarbera/LEDTableEngine | d7f5fd1e3030c0833086269a6c462954c0fe4d18 | [
"Apache-2.0"
] | 5 | 2018-05-03T20:03:36.000Z | 2020-01-18T02:35:51.000Z | #ifndef _H_PONG_APP_
#define _H_PONG_APP_
#include <LEDTableEngine/core/baseApplication.hpp>
namespace ledApps{
class Pong : public led::BaseApplication {
protected:
std::default_random_engine m_generator;
std::uniform_real_distribution<float> m_randFloat;
led::Pointf m_ballSpeed;
led::Pointf m_ballPos;
int m_playerHeight;
std::array<int, 2> m_playerPos;
std::array<int, 2> m_playerScore;
std::array<bool, 2> m_playerWonRound;
float m_speedIncrease;
led::TimeUnit m_movementSpeed;
led::TimeUnit m_lastUpdateTime;
led::TimeUnit m_deathTime;
public:
Pong();
virtual ~Pong();
void initialize(led::BaseController *ctrl);
void processInput(const led::BaseInput::InputEvents& events,
led::TimeUnit deltaTime);
void draw(led::Image& frame);
const std::string getName() const{
return "Pong";
}
private:
void resetRound();
};
}
#endif // ifndef _H_PONG_APP_
| 20.723404 | 64 | 0.687885 | michaelbarbera |
931678f6c087b46d2355d1510252fd43c6bb1929 | 652 | hpp | C++ | src/engine/engine.hpp | MoriokaReimen/randballs | 9566558524407ebce401afc6ef62b54b2057f86a | [
"MIT"
] | 29 | 2018-05-17T14:08:16.000Z | 2021-12-01T08:15:03.000Z | src/engine/engine.hpp | MoriokaReimen/randballs | 9566558524407ebce401afc6ef62b54b2057f86a | [
"MIT"
] | 4 | 2018-09-04T13:46:19.000Z | 2020-05-15T16:05:35.000Z | src/engine/engine.hpp | MoriokaReimen/randballs | 9566558524407ebce401afc6ef62b54b2057f86a | [
"MIT"
] | 2 | 2020-03-30T05:19:37.000Z | 2020-04-24T03:02:25.000Z | #pragma once
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Window/Event.hpp>
#include "graphics/scenemanager.hpp"
#include "graphics/texturemanager.hpp"
#define UPDATES_PER_SEC 60
#define TIMESTEP_N 1000000000 / UPDATES_PER_SEC
#define TIMESTEP_S 1.f / UPDATES_PER_SEC
class Engine
{
bool isRunning = true;
sf::RenderWindow window;
SceneManager sceneMng;
TextureManager textureMng;
public:
Engine();
~Engine();
void start();
void stop();
inline sf::RenderWindow& getWindow() { return window; }
inline SceneManager& getSceneManager() { return sceneMng; }
inline TextureManager& getTextureManager() { return textureMng; }
};
| 21.032258 | 66 | 0.760736 | MoriokaReimen |
931917a5ab54b49f9aae674635f95cef057eb835 | 1,493 | hpp | C++ | unlabeled_mapf/include/ten.hpp | Kei18/tswap | 4f1fb59579c88de122d04a3760dbdda8aa82ba34 | [
"MIT"
] | 2 | 2022-02-13T23:31:31.000Z | 2022-02-14T05:34:38.000Z | unlabeled_mapf/include/ten.hpp | AlbaIntelligence/unlabeled-MAPF | db60f8aa4a12dfee1d0736037372a6d3a93813ce | [
"MIT"
] | null | null | null | unlabeled_mapf/include/ten.hpp | AlbaIntelligence/unlabeled-MAPF | db60f8aa4a12dfee1d0736037372a6d3a93813ce | [
"MIT"
] | 1 | 2022-03-18T00:07:47.000Z | 2022-03-18T00:07:47.000Z | /*
* Time Expanded Network, TEN
*/
#pragma once
#include "lib_ten.hpp"
#include "plan.hpp"
#include "problem.hpp"
class TEN
{
protected:
Problem* const P; // original problem
const Nodes V; // all nodes in G
LibTEN::ResidualNetwork network; // main body
bool valid_network; //
Plan solution; // generate solutions
int time_limit; // time limit
Time::time_point t_start; // to measure computation time
private:
const int max_timestep; // max timestep
protected:
// extend time expanded network only for one timestep
void extendGraphOneTimestep(const int t);
// create time expanded network
virtual void updateGraph();
// convert the flow to the plan of unlabeled-MAPF
void createPlan(const int T);
virtual void createPlan();
// check time limit
bool overCompTime() const;
public:
TEN(Problem* const _P, const int _T, const bool _apply_filter = false);
virtual ~TEN();
// update time expanded network
virtual void update();
virtual void update(const int t);
bool isValid() { return valid_network; }
Plan getPlan() { return solution; }
// clear all flows
void resetFlow() { network.clearAllCapacity(); }
// set time limit of computation time
void setTimeLimit(int _time_limit);
// return info of time expanded network
int getNodesNum();
int getEdgesNum();
// return the number of visited nodes by the Ford Furlkerson algorithm
int getDfsCnt();
};
| 23.698413 | 73 | 0.679169 | Kei18 |
931abc44c5f2568db7c0429acbc3f5bfed311d12 | 233 | cpp | C++ | C++:C#/POOL/main.cpp | bryarcole/The-Portfolio | 62c2573ce4f007dccf5be1d67daf97286d6b4a5e | [
"MIT"
] | null | null | null | C++:C#/POOL/main.cpp | bryarcole/The-Portfolio | 62c2573ce4f007dccf5be1d67daf97286d6b4a5e | [
"MIT"
] | null | null | null | C++:C#/POOL/main.cpp | bryarcole/The-Portfolio | 62c2573ce4f007dccf5be1d67daf97286d6b4a5e | [
"MIT"
] | null | null | null | #include <iostream>
#include "POOLBALL.h"
using namespace std;
int main() {
POOLBALL ball;
cout << "Testing the poolball class" << endl;
cout << "WE have a new ball radius " << ball.getRadius() << endl;
return 0;
} | 19.416667 | 69 | 0.626609 | bryarcole |
793504b5c55a608afef0a8e37739499df9413acd | 7,450 | cc | C++ | aos/network/sctp_lib.cc | Ewpratten/frc_971_mirror | 3a8a0c4359f284d29547962c2b4c43d290d8065c | [
"BSD-2-Clause"
] | null | null | null | aos/network/sctp_lib.cc | Ewpratten/frc_971_mirror | 3a8a0c4359f284d29547962c2b4c43d290d8065c | [
"BSD-2-Clause"
] | null | null | null | aos/network/sctp_lib.cc | Ewpratten/frc_971_mirror | 3a8a0c4359f284d29547962c2b4c43d290d8065c | [
"BSD-2-Clause"
] | null | null | null | #include "aos/network/sctp_lib.h"
#include <arpa/inet.h>
#include <net/if.h>
#include <netdb.h>
#include <netinet/sctp.h>
#include <string_view>
DEFINE_string(interface, "", "ipv6 interface");
namespace aos {
namespace message_bridge {
namespace {
const char *sac_state_tbl[] = {"COMMUNICATION_UP", "COMMUNICATION_LOST",
"RESTART", "SHUTDOWN_COMPLETE",
"CANT_START_ASSOCICATION"};
typedef union {
struct sctp_initmsg init;
struct sctp_sndrcvinfo sndrcvinfo;
} _sctp_cmsg_data_t;
} // namespace
struct sockaddr_storage ResolveSocket(std::string_view host, int port) {
struct sockaddr_storage result;
struct addrinfo *addrinfo_result;
struct sockaddr_in *t_addr = (struct sockaddr_in *)&result;
struct sockaddr_in6 *t_addr6 = (struct sockaddr_in6 *)&result;
PCHECK(getaddrinfo(std::string(host).c_str(), 0, NULL, &addrinfo_result) ==
0);
switch (addrinfo_result->ai_family) {
case AF_INET:
memcpy(t_addr, addrinfo_result->ai_addr, addrinfo_result->ai_addrlen);
t_addr->sin_family = addrinfo_result->ai_family;
t_addr->sin_port = htons(port);
break;
case AF_INET6:
memcpy(t_addr6, addrinfo_result->ai_addr, addrinfo_result->ai_addrlen);
t_addr6->sin6_family = addrinfo_result->ai_family;
t_addr6->sin6_port = htons(port);
if (FLAGS_interface.size() > 0) {
t_addr6->sin6_scope_id = if_nametoindex(FLAGS_interface.c_str());
}
break;
}
// Now print it back out nicely.
char host_string[NI_MAXHOST];
char service_string[NI_MAXSERV];
int error = getnameinfo((struct sockaddr *)&result,
addrinfo_result->ai_addrlen, host_string, NI_MAXHOST,
service_string, NI_MAXSERV, NI_NUMERICHOST);
if (error) {
LOG(ERROR) << "Reverse lookup failed ... " << gai_strerror(error);
}
LOG(INFO) << "remote:addr=" << host_string << ", port=" << service_string
<< ", family=" << addrinfo_result->ai_family;
freeaddrinfo(addrinfo_result);
return result;
}
std::string_view Family(const struct sockaddr_storage &sockaddr) {
if (sockaddr.ss_family == AF_INET) {
return "AF_INET";
} else if (sockaddr.ss_family == AF_INET6) {
return "AF_INET6";
} else {
return "unknown";
}
}
std::string Address(const struct sockaddr_storage &sockaddr) {
char addrbuf[INET6_ADDRSTRLEN];
if (sockaddr.ss_family == AF_INET) {
const struct sockaddr_in *sin = (const struct sockaddr_in *)&sockaddr;
return std::string(
inet_ntop(AF_INET, &sin->sin_addr, addrbuf, INET6_ADDRSTRLEN));
} else {
const struct sockaddr_in6 *sin6 = (const struct sockaddr_in6 *)&sockaddr;
return std::string(
inet_ntop(AF_INET6, &sin6->sin6_addr, addrbuf, INET6_ADDRSTRLEN));
}
}
void PrintNotification(const Message *msg) {
const union sctp_notification *snp =
(const union sctp_notification *)msg->data();
LOG(INFO) << "Notification:";
switch (snp->sn_header.sn_type) {
case SCTP_ASSOC_CHANGE: {
const struct sctp_assoc_change *sac = &snp->sn_assoc_change;
LOG(INFO) << "SCTP_ASSOC_CHANGE(" << sac_state_tbl[sac->sac_state] << ")";
VLOG(1) << " (assoc_change: state=" << sac->sac_state
<< ", error=" << sac->sac_error
<< ", instr=" << sac->sac_inbound_streams
<< " outstr=" << sac->sac_outbound_streams
<< ", assoc=" << sac->sac_assoc_id << ")";
} break;
case SCTP_PEER_ADDR_CHANGE: {
const struct sctp_paddr_change *spc = &snp->sn_paddr_change;
LOG(INFO) << " SlCTP_PEER_ADDR_CHANGE";
VLOG(1) << "\t\t(peer_addr_change: " << Address(spc->spc_aaddr)
<< " state=" << spc->spc_state << ", error=" << spc->spc_error
<< ")";
} break;
case SCTP_SEND_FAILED: {
const struct sctp_send_failed *ssf = &snp->sn_send_failed;
LOG(INFO) << " SCTP_SEND_FAILED";
VLOG(1) << "\t\t(sendfailed: len=" << ssf->ssf_length
<< " err=" << ssf->ssf_error << ")";
} break;
case SCTP_REMOTE_ERROR: {
const struct sctp_remote_error *sre = &snp->sn_remote_error;
LOG(INFO) << " SCTP_REMOTE_ERROR";
VLOG(1) << "\t\t(remote_error: err=" << ntohs(sre->sre_error) << ")";
} break;
case SCTP_SHUTDOWN_EVENT: {
LOG(INFO) << " SCTP_SHUTDOWN_EVENT";
} break;
default:
LOG(INFO) << " Unknown type: " << snp->sn_header.sn_type;
break;
}
}
::std::string GetHostname() {
char buf[256];
buf[sizeof(buf) - 1] = '\0';
PCHECK(gethostname(buf, sizeof(buf) - 1) == 0);
return buf;
}
std::string Message::PeerAddress() const { return Address(sin); }
void LogSctpStatus(int fd, sctp_assoc_t assoc_id) {
struct sctp_status status;
memset(&status, 0, sizeof(status));
status.sstat_assoc_id = assoc_id;
socklen_t size = sizeof(status);
PCHECK(getsockopt(fd, SOL_SCTP, SCTP_STATUS,
reinterpret_cast<void *>(&status), &size) == 0);
LOG(INFO) << "sctp_status) sstat_assoc_id:" << status.sstat_assoc_id
<< " sstat_state:" << status.sstat_state
<< " sstat_rwnd:" << status.sstat_rwnd
<< " sstat_unackdata:" << status.sstat_unackdata
<< " sstat_penddata:" << status.sstat_penddata
<< " sstat_instrms:" << status.sstat_instrms
<< " sstat_outstrms:" << status.sstat_outstrms
<< " sstat_fragmentation_point:" << status.sstat_fragmentation_point
<< " sstat_primary.spinfo_srtt:" << status.sstat_primary.spinfo_srtt
<< " sstat_primary.spinfo_rto:" << status.sstat_primary.spinfo_rto;
}
aos::unique_c_ptr<Message> ReadSctpMessage(int fd, int max_size) {
char incmsg[CMSG_SPACE(sizeof(_sctp_cmsg_data_t))];
struct iovec iov;
struct msghdr inmessage;
memset(&inmessage, 0, sizeof(struct msghdr));
aos::unique_c_ptr<Message> result(
reinterpret_cast<Message *>(malloc(sizeof(Message) + max_size)));
iov.iov_len = max_size;
iov.iov_base = result->mutable_data();
inmessage.msg_iov = &iov;
inmessage.msg_iovlen = 1;
inmessage.msg_control = incmsg;
inmessage.msg_controllen = sizeof(incmsg);
inmessage.msg_namelen = sizeof(struct sockaddr_storage);
inmessage.msg_name = &result->sin;
ssize_t size;
PCHECK((size = recvmsg(fd, &inmessage, 0)) > 0);
result->size = size;
if ((MSG_NOTIFICATION & inmessage.msg_flags)) {
result->message_type = Message::kNotification;
} else {
result->message_type = Message::kMessage;
}
for (struct cmsghdr *scmsg = CMSG_FIRSTHDR(&inmessage); scmsg != NULL;
scmsg = CMSG_NXTHDR(&inmessage, scmsg)) {
switch (scmsg->cmsg_type) {
case SCTP_RCVINFO: {
struct sctp_rcvinfo *data = (struct sctp_rcvinfo *)CMSG_DATA(scmsg);
result->header.rcvinfo = *data;
} break;
default:
LOG(INFO) << "\tUnknown type: " << scmsg->cmsg_type;
break;
}
}
return result;
}
void Message::LogRcvInfo() const {
LOG(INFO) << "\tSNDRCV (stream=" << header.rcvinfo.rcv_sid
<< " ssn=" << header.rcvinfo.rcv_ssn
<< " tsn=" << header.rcvinfo.rcv_tsn << " flags=0x" << std::hex
<< header.rcvinfo.rcv_flags << std::dec
<< " ppid=" << header.rcvinfo.rcv_ppid
<< " cumtsn=" << header.rcvinfo.rcv_cumtsn << ")";
}
} // namespace message_bridge
} // namespace aos
| 32.391304 | 80 | 0.637315 | Ewpratten |