hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7853276613002d45956c6fbb9c24e6db990246dc | 7,596 | cpp | C++ | openfpga/src/fpga_bitstream/fabric_bitstream.cpp | avesus/OpenFPGA | c1dab2168655d41eb59d4923156dabd253ffbd3e | [
"MIT"
] | 246 | 2020-12-03T08:49:29.000Z | 2022-03-28T21:19:55.000Z | openfpga/src/fpga_bitstream/fabric_bitstream.cpp | a-canela/OpenFPGA | 063c58b6cbe2e01aa5520ec43ec80ff064d7f228 | [
"MIT"
] | 261 | 2020-12-03T00:23:54.000Z | 2022-03-31T10:00:37.000Z | openfpga/src/fpga_bitstream/fabric_bitstream.cpp | a-canela/OpenFPGA | 063c58b6cbe2e01aa5520ec43ec80ff064d7f228 | [
"MIT"
] | 66 | 2020-12-12T09:05:53.000Z | 2022-03-28T07:51:41.000Z | /******************************************************************************
* This file includes member functions for data structure FabricBitstream
******************************************************************************/
#include <algorithm>
#include "vtr_assert.h"
#include "openfpga_decode.h"
#include "fabric_bitstream.h"
/* begin namespace openfpga */
namespace openfpga {
/**************************************************
* Public Constructor
*************************************************/
FabricBitstream::FabricBitstream() {
num_bits_ = 0;
invalid_bit_ids_.clear();
address_length_ = 0;
wl_address_length_ = 0;
num_regions_ = 0;
invalid_region_ids_.clear();
use_address_ = false;
use_wl_address_ = false;
}
/**************************************************
* Public Accessors : Aggregates
*************************************************/
size_t FabricBitstream::num_bits() const {
return num_bits_;
}
/* Find all the configuration bits */
FabricBitstream::fabric_bit_range FabricBitstream::bits() const {
return vtr::make_range(fabric_bit_iterator(FabricBitId(0), invalid_bit_ids_),
fabric_bit_iterator(FabricBitId(num_bits_), invalid_bit_ids_));
}
size_t FabricBitstream::num_regions() const {
return num_regions_;
}
/* Find all the configuration bits */
FabricBitstream::fabric_bit_region_range FabricBitstream::regions() const {
return vtr::make_range(fabric_bit_region_iterator(FabricBitRegionId(0), invalid_region_ids_),
fabric_bit_region_iterator(FabricBitRegionId(num_regions_), invalid_region_ids_));
}
std::vector<FabricBitId> FabricBitstream::region_bits(const FabricBitRegionId& region_id) const {
/* Ensure a valid id */
VTR_ASSERT(true == valid_region_id(region_id));
return region_bit_ids_[region_id];
}
/******************************************************************************
* Public Accessors
******************************************************************************/
ConfigBitId FabricBitstream::config_bit(const FabricBitId& bit_id) const {
/* Ensure a valid id */
VTR_ASSERT(true == valid_bit_id(bit_id));
return config_bit_ids_[bit_id];
}
std::vector<char> FabricBitstream::bit_address(const FabricBitId& bit_id) const {
/* Ensure a valid id */
VTR_ASSERT(true == valid_bit_id(bit_id));
VTR_ASSERT(true == use_address_);
return bit_addresses_[bit_id];
}
std::vector<char> FabricBitstream::bit_bl_address(const FabricBitId& bit_id) const {
return bit_address(bit_id);
}
std::vector<char> FabricBitstream::bit_wl_address(const FabricBitId& bit_id) const {
/* Ensure a valid id */
VTR_ASSERT(true == valid_bit_id(bit_id));
VTR_ASSERT(true == use_address_);
VTR_ASSERT(true == use_wl_address_);
return bit_wl_addresses_[bit_id];
}
char FabricBitstream::bit_din(const FabricBitId& bit_id) const {
/* Ensure a valid id */
VTR_ASSERT(true == valid_bit_id(bit_id));
VTR_ASSERT(true == use_address_);
return bit_dins_[bit_id];
}
bool FabricBitstream::use_address() const {
return use_address_;
}
bool FabricBitstream::use_wl_address() const {
return use_wl_address_;
}
/******************************************************************************
* Public Mutators
******************************************************************************/
void FabricBitstream::reserve_bits(const size_t& num_bits) {
config_bit_ids_.reserve(num_bits);
if (true == use_address_) {
bit_addresses_.reserve(num_bits);
bit_dins_.reserve(num_bits);
if (true == use_wl_address_) {
bit_wl_addresses_.reserve(num_bits);
}
}
}
FabricBitId FabricBitstream::add_bit(const ConfigBitId& config_bit_id) {
FabricBitId bit = FabricBitId(num_bits_);
/* Add a new bit, and allocate associated data structures */
num_bits_++;
config_bit_ids_.push_back(config_bit_id);
if (true == use_address_) {
bit_addresses_.emplace_back();
bit_dins_.emplace_back();
if (true == use_wl_address_) {
bit_wl_addresses_.emplace_back();
}
}
return bit;
}
void FabricBitstream::set_bit_address(const FabricBitId& bit_id,
const std::vector<char>& address) {
VTR_ASSERT(true == valid_bit_id(bit_id));
VTR_ASSERT(true == use_address_);
VTR_ASSERT(address_length_ == address.size());
bit_addresses_[bit_id] = address;
}
void FabricBitstream::set_bit_bl_address(const FabricBitId& bit_id,
const std::vector<char>& address) {
set_bit_address(bit_id, address);
}
void FabricBitstream::set_bit_wl_address(const FabricBitId& bit_id,
const std::vector<char>& address) {
VTR_ASSERT(true == valid_bit_id(bit_id));
VTR_ASSERT(true == use_address_);
VTR_ASSERT(true == use_wl_address_);
VTR_ASSERT(wl_address_length_ == address.size());
bit_wl_addresses_[bit_id] = address;
}
void FabricBitstream::set_bit_din(const FabricBitId& bit_id,
const char& din) {
VTR_ASSERT(true == valid_bit_id(bit_id));
VTR_ASSERT(true == use_address_);
bit_dins_[bit_id] = din;
}
void FabricBitstream::set_use_address(const bool& enable) {
/* Add a lock, only can be modified when num bits are zero*/
if (0 == num_bits_) {
use_address_ = enable;
}
}
void FabricBitstream::set_address_length(const size_t& length) {
if (true == use_address_) {
address_length_ = length;
}
}
void FabricBitstream::set_bl_address_length(const size_t& length) {
set_address_length(length);
}
void FabricBitstream::set_use_wl_address(const bool& enable) {
/* Add a lock, only can be modified when num bits are zero*/
if (0 == num_bits_) {
use_wl_address_ = enable;
}
}
void FabricBitstream::set_wl_address_length(const size_t& length) {
if (true == use_address_) {
wl_address_length_ = length;
}
}
void FabricBitstream::reserve_regions(const size_t& num_regions) {
region_bit_ids_.reserve(num_regions);
}
FabricBitRegionId FabricBitstream::add_region() {
FabricBitRegionId region = FabricBitRegionId(num_regions_);
/* Add a new bit, and allocate associated data structures */
num_regions_++;
region_bit_ids_.emplace_back();
return region;
}
void FabricBitstream::add_bit_to_region(const FabricBitRegionId& region_id,
const FabricBitId& bit_id) {
VTR_ASSERT(true == valid_region_id(region_id));
VTR_ASSERT(true == valid_bit_id(bit_id));
region_bit_ids_[region_id].push_back(bit_id);
}
void FabricBitstream::reverse() {
std::reverse(config_bit_ids_.begin(), config_bit_ids_.end());
if (true == use_address_) {
std::reverse(bit_addresses_.begin(), bit_addresses_.end());
std::reverse(bit_dins_.begin(), bit_dins_.end());
if (true == use_wl_address_) {
std::reverse(bit_wl_addresses_.begin(), bit_wl_addresses_.end());
}
}
}
void FabricBitstream::reverse_region_bits(const FabricBitRegionId& region_id) {
VTR_ASSERT(true == valid_region_id(region_id));
std::reverse(region_bit_ids_[region_id].begin(), region_bit_ids_[region_id].end());
}
/******************************************************************************
* Public Validators
******************************************************************************/
bool FabricBitstream::valid_bit_id(const FabricBitId& bit_id) const {
return (size_t(bit_id) < num_bits_);
}
bool FabricBitstream::valid_region_id(const FabricBitRegionId& region_id) const {
return (size_t(region_id) < num_regions_);
}
} /* end namespace openfpga */
| 30.142857 | 107 | 0.637704 | [
"vector"
] |
78534fcdd6b6eca7dee2387a685d37269be68ff5 | 382 | cpp | C++ | abc122/d/main.cpp | kamiyaowl/atcoder | 30521be1684e72e75c7ba21312c5f96ae81bf25a | [
"MIT"
] | null | null | null | abc122/d/main.cpp | kamiyaowl/atcoder | 30521be1684e72e75c7ba21312c5f96ae81bf25a | [
"MIT"
] | 1 | 2019-04-20T11:51:59.000Z | 2019-04-20T11:51:59.000Z | abc122/d/main.cpp | kamiyaowl/atcoder | 30521be1684e72e75c7ba21312c5f96ae81bf25a | [
"MIT"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <tuple>
#include <stdbool.h>
#include <bitset>
#include <string>
#include <boost/multiprecision/cpp_int.hpp>
namespace mp = boost::multiprecision;
using namespace std;
bool validate(const string& src) {
}
int main(void) {
int n;
cin >> n;
return 0;
} | 15.28 | 43 | 0.691099 | [
"vector"
] |
785453cd125610a6226f2345e59f830f982c586a | 1,702 | cpp | C++ | codeforces/F - Make Them Similar/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/F - Make Them Similar/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/F - Make Them Similar/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Nov/22/2019 01:29
* solution_verdict: Accepted language: GNU C++14
* run_time: 1154 ms memory_used: 22600 KB
* problem: https://codeforces.com/contest/1257/problem/F
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6;
int aa[N+2],bb[N+2];
map<vector<int>,int>mp;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int tt=(1<<30)-1,a,b;b=tt;
for(int i=0;i<15;i++)b^=(1<<i);a=b^tt;
int n;cin>>n;
for(int i=1;i<=n;i++)
{
int x;cin>>x;aa[i]=x&a;
for(int j=15;j<30;j++)
if(x&(1<<j))bb[i]|=(1<<(j-15));
}
for(int i=0;i<(1<<15);i++)
{
vector<int>v;
for(int j=1;j<=n;j++)
v.push_back(__builtin_popcount((i^bb[j])));
mp[v]=i;
}
for(int i=0;i<(1<<15);i++)
{
int mx=0;vector<int>now;
for(int j=1;j<=n;j++)
{
mx=max(mx,__builtin_popcount((i^aa[j])));
now.push_back(__builtin_popcount((i^aa[j])));
}
for(int m=mx;m<=30;m++)
{
vector<int>v;
for(auto x:now)
v.push_back(m-x);
if(mp.find(v)!=mp.end())
{
auto it=mp.find(v);
int ans=i;
for(int p=0;p<15;p++)
{
if((it->second&(1<<p)))
ans|=(1<<(15+p));
}
cout<<ans<<endl,exit(0);
}
}
}
cout<<-1<<endl;
return 0;
} | 28.366667 | 111 | 0.402468 | [
"vector"
] |
7855a80bf148a67d5fe976d7420ff7af9bf621af | 30,123 | cpp | C++ | ace/tao/tests/rtcorba/Policy_Combinations/server.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | ace/tao/tests/rtcorba/Policy_Combinations/server.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | ace/tao/tests/rtcorba/Policy_Combinations/server.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | // server.cpp,v 1.5 2001/09/19 23:35:40 irfan Exp
#include "ace/Get_Opt.h"
#include "testS.h"
#include "tao/ORB_Core.h"
#include "tao/RTPortableServer/RTPortableServer.h"
#include "../check_supported_priorities.cpp"
class test_i :
public POA_test,
public PortableServer::RefCountServantBase
{
public:
test_i (CORBA::ORB_ptr orb,
PortableServer::POA_ptr poa,
CORBA::Short server_priority,
CORBA::Short client_priority);
CORBA::Short method (CORBA::Environment &ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException));
void prioritized_method (CORBA::Environment &ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException));
void shutdown (CORBA::Environment &ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException));
PortableServer::POA_ptr _default_POA (CORBA_Environment &ACE_TRY_ENV);
private:
CORBA::ORB_var orb_;
PortableServer::POA_var poa_;
CORBA::Short server_priority_;
CORBA::Short client_priority_;
};
test_i::test_i (CORBA::ORB_ptr orb,
PortableServer::POA_ptr poa,
CORBA::Short server_priority,
CORBA::Short client_priority)
: orb_ (CORBA::ORB::_duplicate (orb)),
poa_ (PortableServer::POA::_duplicate (poa)),
server_priority_ (server_priority),
client_priority_ (client_priority)
{
}
CORBA::Short
test_i::method (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException))
{
ACE_DEBUG ((LM_DEBUG,
"test_i::method\n"));
return this->client_priority_;
}
void
test_i::prioritized_method (CORBA::Environment &ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException))
{
CORBA::Object_var object =
this->orb_->resolve_initial_references ("RTCurrent",
ACE_TRY_ENV);
ACE_CHECK;
RTCORBA::Current_var current =
RTCORBA::Current::_narrow (object.in (),
ACE_TRY_ENV);
ACE_CHECK;
CORBA::Short priority =
current->the_priority (ACE_TRY_ENV);
ACE_CHECK;
ACE_DEBUG ((LM_DEBUG,
"test_i::prioritized_method: client = %d server = %d (should be %d)\n",
this->client_priority_,
priority,
this->server_priority_));
ACE_ASSERT (this->server_priority_ == priority);
}
void
test_i::shutdown (CORBA::Environment &ACE_TRY_ENV)
ACE_THROW_SPEC ((CORBA::SystemException))
{
ACE_DEBUG ((LM_DEBUG,
"test_i::shutdown\n"));
this->orb_->shutdown (0,
ACE_TRY_ENV);
ACE_CHECK;
}
PortableServer::POA_ptr
test_i::_default_POA (CORBA_Environment &)
{
return PortableServer::POA::_duplicate (this->poa_.in ());
}
static CORBA::Short server_priority;
static CORBA::Short client_priority;
static CORBA::ULong stacksize = 0;
static CORBA::ULong static_threads = 2;
static CORBA::ULong dynamic_threads = 0;
static RTCORBA::Priority default_thread_priority;
static CORBA::Boolean allow_request_buffering = 0;
static CORBA::ULong max_buffered_requests = 0;
static CORBA::ULong max_request_buffer_size = 0;
static CORBA::Boolean allow_borrowing = 0;
static int
parse_args (int argc, char **argv)
{
ACE_Get_Opt get_opts (argc, argv, "s:c:");
int c;
while ((c = get_opts ()) != -1)
switch (c)
{
case 's':
::server_priority = ::atoi (get_opts.optarg);
break;
case 'c':
::client_priority = ::atoi (get_opts.optarg);
break;
case '?':
default:
ACE_ERROR_RETURN ((LM_ERROR,
"usage: %s "
"-s server priority "
"-c client priority "
"\n",
argv [0]),
-1);
}
return 0;
}
static void
write_iors_to_file (CORBA::Object_ptr object,
CORBA::ORB_ptr orb,
const char *filename,
CORBA::Environment &ACE_TRY_ENV)
{
FILE *file =
ACE_OS::fopen (filename, "w");
ACE_ASSERT (file != 0);
CORBA::String_var ior =
orb->object_to_string (object,
ACE_TRY_ENV);
ACE_CHECK;
u_int result = 0;
result =
ACE_OS::fprintf (file,
"%s",
ior.in ());
ACE_ASSERT (result == ACE_OS::strlen (ior.in ()));
ACE_UNUSED_ARG (result);
ACE_OS::fclose (file);
}
class server
{
public:
server (CORBA::ORB_ptr orb,
RTCORBA::RTORB_ptr rt_orb,
PortableServer::POA_ptr root_poa,
PortableServer::POAManager_ptr poa_manager);
void test_root_poa (CORBA::Environment &ACE_TRY_ENV);
void test_child_poa (CORBA::Environment &ACE_TRY_ENV);
typedef void (server::*test_function) (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV);
void test_default_pool_poa (CORBA::Short server_priority,
CORBA::Short client_priority,
server::test_function function,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV);
void test_bands_poa (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
server::test_function function,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV);
void test_no_lanes_poa (CORBA::Short server_priority,
CORBA::Short client_priority,
server::test_function function,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV);
void test_lanes_poa (CORBA::Short server_priority,
CORBA::Short client_priority,
server::test_function function,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV);
void test_no_bands_client_propagated_poa (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV);
void test_bands_client_propagated_poa (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV);
void test_no_bands_server_declared_poa (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV);
void test_bands_server_declared_poa (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV);
void test_default_pool_no_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV);
void test_no_lanes_no_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV);
void test_lanes_no_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV);
void test_default_pool_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV);
void test_no_lanes_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV);
void test_lanes_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV);
void test_default_pool_no_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV);
void test_no_lanes_no_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV);
void test_lanes_no_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV);
void test_default_pool_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV);
void test_no_lanes_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV);
void test_lanes_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV);
private:
CORBA::ORB_var orb_;
RTCORBA::RTORB_var rt_orb_;
PortableServer::POA_var root_poa_;
PortableServer::POAManager_var poa_manager_;
};
server::server (CORBA::ORB_ptr orb,
RTCORBA::RTORB_ptr rt_orb,
PortableServer::POA_ptr root_poa,
PortableServer::POAManager_ptr poa_manager)
: orb_ (CORBA::ORB::_duplicate (orb)),
rt_orb_ (RTCORBA::RTORB::_duplicate (rt_orb)),
root_poa_ (PortableServer::POA::_duplicate (root_poa)),
poa_manager_ (PortableServer::POAManager::_duplicate (poa_manager))
{
}
void
server::test_root_poa (CORBA::Environment &ACE_TRY_ENV)
{
test_i *servant = 0;
ACE_NEW_THROW_EX (servant,
test_i (this->orb_.in (),
this->root_poa_.in (),
TAO_INVALID_PRIORITY,
TAO_INVALID_PRIORITY),
CORBA::NO_MEMORY ());
ACE_CHECK;
PortableServer::ServantBase_var safe_servant (servant);
test_var test =
servant->_this (ACE_TRY_ENV);
ACE_CHECK;
write_iors_to_file (test.in (),
this->orb_.in (),
"root",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_child_poa (CORBA::Environment &ACE_TRY_ENV)
{
CORBA::PolicyList policies;
policies.length (1);
policies[policies.length () - 1] =
this->root_poa_->create_implicit_activation_policy (PortableServer::IMPLICIT_ACTIVATION,
ACE_TRY_ENV);
ACE_CHECK;
PortableServer::POA_var poa =
this->root_poa_->create_POA ("child",
this->poa_manager_.in (),
policies,
ACE_TRY_ENV);
ACE_CHECK;
test_i *servant = 0;
ACE_NEW_THROW_EX (servant,
test_i (this->orb_.in (),
poa.in (),
TAO_INVALID_PRIORITY,
TAO_INVALID_PRIORITY),
CORBA::NO_MEMORY ());
ACE_CHECK;
PortableServer::ServantBase_var safe_servant (servant);
test_var test =
servant->_this (ACE_TRY_ENV);
ACE_CHECK;
write_iors_to_file (test.in (),
this->orb_.in (),
"child",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_default_pool_poa (CORBA::Short server_priority,
CORBA::Short client_priority,
server::test_function function,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV)
{
CORBA::PolicyList empty_policies;
(this->*function) (empty_policies,
server_priority,
client_priority,
test_name,
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_bands_poa (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
server::test_function function,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV)
{
RTCORBA::PriorityBands bands;
bands.length (3);
bands[0].low = default_thread_priority;
bands[0].high = default_thread_priority;
bands[1].low = ::server_priority - 1;
bands[1].high = ::server_priority + 1;
bands[2].low = ::client_priority - 1;
bands[2].high = ::client_priority + 1;
policies.length (policies.length () + 1);
policies[policies.length () - 1] =
this->rt_orb_->create_priority_banded_connection_policy (bands,
ACE_TRY_ENV);
ACE_CHECK;
(this->*function) (policies,
server_priority,
client_priority,
test_name,
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_no_lanes_poa (CORBA::Short server_priority,
CORBA::Short client_priority,
server::test_function function,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV)
{
RTCORBA::ThreadpoolId threadpool_id =
this->rt_orb_->create_threadpool (stacksize,
static_threads,
dynamic_threads,
default_thread_priority,
allow_request_buffering,
max_buffered_requests,
max_request_buffer_size,
ACE_TRY_ENV);
ACE_CHECK;
CORBA::Policy_var threadpool_policy =
this->rt_orb_->create_threadpool_policy (threadpool_id,
ACE_TRY_ENV);
ACE_CHECK;
CORBA::PolicyList policies;
policies.length (1);
policies[0] =
threadpool_policy;
(this->*function) (policies,
server_priority,
client_priority,
test_name,
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_lanes_poa (CORBA::Short server_priority,
CORBA::Short client_priority,
server::test_function function,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV)
{
RTCORBA::ThreadpoolLanes lanes;
lanes.length (3);
lanes[0].lane_priority = ::client_priority;
lanes[0].static_threads = static_threads;
lanes[0].dynamic_threads = dynamic_threads;
lanes[1].lane_priority = ::server_priority;
lanes[1].static_threads = static_threads;
lanes[1].dynamic_threads = dynamic_threads;
lanes[2].lane_priority = default_thread_priority;
lanes[2].static_threads = static_threads;
lanes[2].dynamic_threads = dynamic_threads;
RTCORBA::ThreadpoolId threadpool_id =
this->rt_orb_->create_threadpool_with_lanes (stacksize,
lanes,
allow_borrowing,
allow_request_buffering,
max_buffered_requests,
max_request_buffer_size,
ACE_TRY_ENV);
ACE_CHECK;
CORBA::Policy_var threadpool_policy =
this->rt_orb_->create_threadpool_policy (threadpool_id,
ACE_TRY_ENV);
ACE_CHECK;
CORBA::PolicyList policies;
policies.length (1);
policies[0] =
threadpool_policy;
(this->*function) (policies,
server_priority,
client_priority,
test_name,
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_no_bands_client_propagated_poa (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV)
{
policies.length (policies.length () + 1);
policies[policies.length () - 1] =
this->rt_orb_->create_priority_model_policy (RTCORBA::CLIENT_PROPAGATED,
default_thread_priority,
ACE_TRY_ENV);
ACE_CHECK;
PortableServer::POA_var poa =
this->root_poa_->create_POA (test_name,
this->poa_manager_.in (),
policies,
ACE_TRY_ENV);
ACE_CHECK;
RTPortableServer::POA_var rt_poa =
RTPortableServer::POA::_narrow (poa.in (),
ACE_TRY_ENV);
ACE_CHECK;
test_i *servant = 0;
ACE_NEW_THROW_EX (servant,
test_i (this->orb_.in (),
poa.in (),
server_priority,
client_priority),
CORBA::NO_MEMORY ());
ACE_CHECK;
PortableServer::ServantBase_var safe_servant (servant);
PortableServer::ObjectId_var id =
rt_poa->activate_object (servant,
ACE_TRY_ENV);
ACE_CHECK;
CORBA::Object_var object =
poa->id_to_reference (id.in (),
ACE_TRY_ENV);
ACE_CHECK;
write_iors_to_file (object.in (),
this->orb_.in (),
test_name,
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_bands_client_propagated_poa (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV)
{
this->test_bands_poa (policies,
server_priority,
client_priority,
&server::test_no_bands_client_propagated_poa,
test_name,
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_default_pool_no_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_default_pool_poa (::client_priority + 1,
::client_priority + 1,
&server::test_no_bands_client_propagated_poa,
"default_pool_no_bands_client_propagated",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_no_lanes_no_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_no_lanes_poa (::client_priority - 1,
::client_priority - 1,
&server::test_no_bands_client_propagated_poa,
"no_lanes_no_bands_client_propagated",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_lanes_no_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_lanes_poa (::client_priority,
::client_priority,
&server::test_no_bands_client_propagated_poa,
"lanes_no_bands_client_propagated",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_default_pool_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_default_pool_poa (::client_priority + 1,
::client_priority + 1,
&server::test_bands_client_propagated_poa,
"default_pool_bands_client_propagated",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_no_lanes_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_no_lanes_poa (::client_priority - 1,
::client_priority - 1,
&server::test_bands_client_propagated_poa,
"no_lanes_bands_client_propagated",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_lanes_bands_client_propagated_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_lanes_poa (::client_priority,
::client_priority + 1,
&server::test_bands_client_propagated_poa,
"lanes_bands_client_propagated",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_no_bands_server_declared_poa (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV)
{
policies.length (policies.length () + 1);
policies[policies.length () - 1] =
this->rt_orb_->create_priority_model_policy (RTCORBA::SERVER_DECLARED,
default_thread_priority,
ACE_TRY_ENV);
ACE_CHECK;
PortableServer::POA_var poa =
this->root_poa_->create_POA (test_name,
this->poa_manager_.in (),
policies,
ACE_TRY_ENV);
ACE_CHECK;
RTPortableServer::POA_var rt_poa =
RTPortableServer::POA::_narrow (poa.in (),
ACE_TRY_ENV);
ACE_CHECK;
test_i *servant = 0;
ACE_NEW_THROW_EX (servant,
test_i (this->orb_.in (),
poa.in (),
server_priority,
client_priority),
CORBA::NO_MEMORY ());
ACE_CHECK;
PortableServer::ServantBase_var safe_servant (servant);
PortableServer::ObjectId_var id =
rt_poa->activate_object_with_priority (servant,
::server_priority,
ACE_TRY_ENV);
ACE_CHECK;
CORBA::Object_var object =
poa->id_to_reference (id.in (),
ACE_TRY_ENV);
ACE_CHECK;
write_iors_to_file (object.in (),
this->orb_.in (),
test_name,
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_bands_server_declared_poa (CORBA::PolicyList &policies,
CORBA::Short server_priority,
CORBA::Short client_priority,
const char *test_name,
CORBA::Environment &ACE_TRY_ENV)
{
this->test_bands_poa (policies,
server_priority,
client_priority,
&server::test_no_bands_server_declared_poa,
test_name,
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_default_pool_no_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_default_pool_poa (::server_priority,
::client_priority + 1,
&server::test_no_bands_server_declared_poa,
"default_pool_no_bands_server_declared",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_no_lanes_no_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_no_lanes_poa (::server_priority,
::client_priority - 1,
&server::test_no_bands_server_declared_poa,
"no_lanes_no_bands_server_declared",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_lanes_no_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_lanes_poa (::server_priority,
::client_priority + 1,
&server::test_no_bands_server_declared_poa,
"lanes_no_bands_server_declared",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_default_pool_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_default_pool_poa (::server_priority,
::client_priority - 1,
&server::test_bands_server_declared_poa,
"default_pool_bands_server_declared",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_no_lanes_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_no_lanes_poa (::server_priority,
::client_priority + 1,
&server::test_bands_server_declared_poa,
"no_lanes_bands_server_declared",
ACE_TRY_ENV);
ACE_CHECK;
}
void
server::test_lanes_bands_server_declared_poa (CORBA::Environment &ACE_TRY_ENV)
{
this->test_lanes_poa (::server_priority,
::client_priority - 1,
&server::test_bands_server_declared_poa,
"lanes_bands_server_declared",
ACE_TRY_ENV);
ACE_CHECK;
}
int
main (int argc, char **argv)
{
// Make sure we can support multiple priorities that are required
// for this test.
check_supported_priorities ();
ACE_TRY_NEW_ENV
{
CORBA::ORB_var orb =
CORBA::ORB_init (argc,
argv,
0,
ACE_TRY_ENV);
ACE_TRY_CHECK;
CORBA::Object_var object =
orb->resolve_initial_references ("RTORB",
ACE_TRY_ENV);
ACE_TRY_CHECK;
RTCORBA::RTORB_var rt_orb =
RTCORBA::RTORB::_narrow (object.in (),
ACE_TRY_ENV);
ACE_TRY_CHECK;
// The following sets the current thread to the lowest priority
// for this scheduling policy. This will give us the biggest
// range on NT since the default priority is 0 where as the
// lowest priority is -15.
ACE_hthread_t current_thread;
ACE_Thread::self (current_thread);
long sched_policy =
orb->orb_core ()->orb_params ()->sched_policy ();
int minimum_priority =
ACE_Sched_Params::priority_min (sched_policy);
int result =
ACE_Thread::setprio (current_thread,
minimum_priority);
if (result != 0)
return result;
object =
orb->resolve_initial_references ("RTCurrent",
ACE_TRY_ENV);
ACE_TRY_CHECK;
RTCORBA::Current_var current =
RTCORBA::Current::_narrow (object.in (),
ACE_TRY_ENV);
ACE_TRY_CHECK;
default_thread_priority =
current->the_priority (ACE_TRY_ENV);
ACE_TRY_CHECK;
client_priority =
default_thread_priority + 2;
server_priority =
default_thread_priority + 5;
result =
parse_args (argc, argv);
if (result != 0)
return result;
object =
orb->resolve_initial_references ("RootPOA",
ACE_TRY_ENV);
ACE_TRY_CHECK;
PortableServer::POA_var root_poa =
PortableServer::POA::_narrow (object.in (),
ACE_TRY_ENV);
ACE_TRY_CHECK;
PortableServer::POAManager_var poa_manager =
root_poa->the_POAManager (ACE_TRY_ENV);
ACE_TRY_CHECK;
server server (orb.in (),
rt_orb.in (),
root_poa.in (),
poa_manager.in ());
server.test_root_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_child_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_default_pool_no_bands_client_propagated_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_default_pool_no_bands_server_declared_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_no_lanes_no_bands_client_propagated_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_no_lanes_no_bands_server_declared_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_lanes_no_bands_client_propagated_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_lanes_no_bands_server_declared_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_default_pool_bands_client_propagated_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_default_pool_bands_server_declared_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_no_lanes_bands_client_propagated_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_no_lanes_bands_server_declared_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_lanes_bands_client_propagated_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
server.test_lanes_bands_server_declared_poa (ACE_TRY_ENV);
ACE_TRY_CHECK;
poa_manager->activate (ACE_TRY_ENV);
ACE_TRY_CHECK;
orb->run (ACE_TRY_ENV);
ACE_TRY_CHECK;
orb->destroy (ACE_TRY_ENV);
ACE_TRY_CHECK;
}
ACE_CATCHANY
{
ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "Exception caught");
return -1;
}
ACE_ENDTRY;
return 0;
}
| 33.358804 | 93 | 0.542642 | [
"object"
] |
7859f14ad1d45f2dcfc804a1f34d719502ec5c33 | 660 | hpp | C++ | src/resourceManager.hpp | ondralukes/OpenGLCraft | 8384fc70c02dddcf593a2e6aab6c1cd7d0ba38a3 | [
"MIT"
] | 1 | 2020-01-27T18:11:13.000Z | 2020-01-27T18:11:13.000Z | src/resourceManager.hpp | ondralukes/OpenGLCraft | 8384fc70c02dddcf593a2e6aab6c1cd7d0ba38a3 | [
"MIT"
] | 12 | 2020-01-22T09:16:29.000Z | 2020-02-10T21:37:50.000Z | src/resourceManager.hpp | ondralukes/OpenGLCraft | 8384fc70c02dddcf593a2e6aab6c1cd7d0ba38a3 | [
"MIT"
] | null | null | null | #ifndef RES_MGR_H
#define RES_MGR_H
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include "loadObj.hpp"
#include "loadTexture.hpp"
struct texture_t {
GLuint id;
char name[128];
};
struct obj_t {
std::vector<glm::vec3> * vertices;
std::vector<glm::vec2> * uvs;
char name[128];
};
class ResourceManager{
public:
static GLuint getTexture(const char * path, bool filtering = true);
static std::vector<texture_t> textures;
static std::vector<glm::vec3> * getObjVertices(const char * path);
static std::vector<glm::vec2> * getObjUVs(const char * path);
static std::vector<obj_t> objs;
};
#endif
| 20 | 71 | 0.689394 | [
"vector"
] |
7860a55c438599d39cc56fb8ea1f01490a765e2f | 661 | hpp | C++ | Sources/Animations/Skin/VertexWeights.hpp | CarysT/Acid | ab81fd13ab288ceaa152e0f64f6d97daf032fc19 | [
"MIT"
] | 977 | 2019-05-23T01:53:42.000Z | 2022-03-30T04:22:41.000Z | Sources/Animations/Skin/VertexWeights.hpp | CarysT/Acid | ab81fd13ab288ceaa152e0f64f6d97daf032fc19 | [
"MIT"
] | 44 | 2019-06-02T17:30:32.000Z | 2022-03-27T14:22:40.000Z | Sources/Animations/Skin/VertexWeights.hpp | CarysT/Acid | ab81fd13ab288ceaa152e0f64f6d97daf032fc19 | [
"MIT"
] | 121 | 2019-05-23T05:18:01.000Z | 2022-03-27T21:59:23.000Z | #pragma once
#include <cstdint>
#include <vector>
#include "Export.hpp"
namespace acid {
class ACID_EXPORT VertexWeights {
public:
void AddJointEffect(uint32_t jointId, float jointWeight);
void LimitJointNumber(uint32_t max);
void FillEmptyWeights(uint32_t max);
float SaveTopWeights(std::vector<float> &topWeightsArray);
void RefillWeightList(const std::vector<float> &topWeights, float total);
void RemoveExcessJointIds(uint32_t max);
const std::vector<uint32_t> &GetJointIds() const { return jointIds; }
const std::vector<float> &GetWeights() const { return weights; }
private:
std::vector<uint32_t> jointIds;
std::vector<float> weights;
};
}
| 25.423077 | 74 | 0.765507 | [
"vector"
] |
7861ae997da2ee2c95f24e7f696af2ff2f22b16e | 7,375 | cc | C++ | src/modules/audio_processing/agc2/interpolated_gain_curve_unittest.cc | ilya-fedin/tg_owt | d5c3d43b959c7e9e7d8004b9b7fdadd12ce7d589 | [
"BSD-3-Clause"
] | 344 | 2016-07-03T11:45:20.000Z | 2022-03-19T16:54:10.000Z | src/modules/audio_processing/agc2/interpolated_gain_curve_unittest.cc | ilya-fedin/tg_owt | d5c3d43b959c7e9e7d8004b9b7fdadd12ce7d589 | [
"BSD-3-Clause"
] | 59 | 2020-08-24T09:17:42.000Z | 2022-02-27T23:33:37.000Z | src/modules/audio_processing/agc2/interpolated_gain_curve_unittest.cc | ilya-fedin/tg_owt | d5c3d43b959c7e9e7d8004b9b7fdadd12ce7d589 | [
"BSD-3-Clause"
] | 278 | 2016-04-26T07:37:12.000Z | 2022-01-24T10:09:44.000Z | /*
* Copyright (c) 2018 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/audio_processing/agc2/interpolated_gain_curve.h"
#include <array>
#include <type_traits>
#include <vector>
#include "api/array_view.h"
#include "common_audio/include/audio_util.h"
#include "modules/audio_processing/agc2/agc2_common.h"
#include "modules/audio_processing/agc2/compute_interpolated_gain_curve.h"
#include "modules/audio_processing/agc2/limiter_db_gain_curve.h"
#include "modules/audio_processing/logging/apm_data_dumper.h"
#include "rtc_base/checks.h"
#include "rtc_base/gunit.h"
namespace webrtc {
namespace {
constexpr double kLevelEpsilon = 1e-2 * kMaxAbsFloatS16Value;
constexpr float kInterpolatedGainCurveTolerance = 1.f / 32768.f;
ApmDataDumper apm_data_dumper(0);
static_assert(std::is_trivially_destructible<LimiterDbGainCurve>::value, "");
const LimiterDbGainCurve limiter;
} // namespace
TEST(GainController2InterpolatedGainCurve, CreateUse) {
InterpolatedGainCurve igc(&apm_data_dumper, "");
const auto levels = test::LinSpace(
kLevelEpsilon, DbfsToFloatS16(limiter.max_input_level_db() + 1), 500);
for (const auto level : levels) {
EXPECT_GE(igc.LookUpGainToApply(level), 0.0f);
}
}
TEST(GainController2InterpolatedGainCurve, CheckValidOutput) {
InterpolatedGainCurve igc(&apm_data_dumper, "");
const auto levels = test::LinSpace(
kLevelEpsilon, limiter.max_input_level_linear() * 2.0, 500);
for (const auto level : levels) {
SCOPED_TRACE(std::to_string(level));
const float gain = igc.LookUpGainToApply(level);
EXPECT_LE(0.0f, gain);
EXPECT_LE(gain, 1.0f);
}
}
TEST(GainController2InterpolatedGainCurve, CheckMonotonicity) {
InterpolatedGainCurve igc(&apm_data_dumper, "");
const auto levels = test::LinSpace(
kLevelEpsilon, limiter.max_input_level_linear() + kLevelEpsilon + 0.5,
500);
float prev_gain = igc.LookUpGainToApply(0.0f);
for (const auto level : levels) {
const float gain = igc.LookUpGainToApply(level);
EXPECT_GE(prev_gain, gain);
prev_gain = gain;
}
}
TEST(GainController2InterpolatedGainCurve, CheckApproximation) {
InterpolatedGainCurve igc(&apm_data_dumper, "");
const auto levels = test::LinSpace(
kLevelEpsilon, limiter.max_input_level_linear() - kLevelEpsilon, 500);
for (const auto level : levels) {
SCOPED_TRACE(std::to_string(level));
EXPECT_LT(
std::fabs(limiter.GetGainLinear(level) - igc.LookUpGainToApply(level)),
kInterpolatedGainCurveTolerance);
}
}
TEST(GainController2InterpolatedGainCurve, CheckRegionBoundaries) {
InterpolatedGainCurve igc(&apm_data_dumper, "");
const std::vector<double> levels{
{kLevelEpsilon, limiter.knee_start_linear() + kLevelEpsilon,
limiter.limiter_start_linear() + kLevelEpsilon,
limiter.max_input_level_linear() + kLevelEpsilon}};
for (const auto level : levels) {
igc.LookUpGainToApply(level);
}
const auto stats = igc.get_stats();
EXPECT_EQ(1ul, stats.look_ups_identity_region);
EXPECT_EQ(1ul, stats.look_ups_knee_region);
EXPECT_EQ(1ul, stats.look_ups_limiter_region);
EXPECT_EQ(1ul, stats.look_ups_saturation_region);
}
TEST(GainController2InterpolatedGainCurve, CheckIdentityRegion) {
constexpr size_t kNumSteps = 10;
InterpolatedGainCurve igc(&apm_data_dumper, "");
const auto levels =
test::LinSpace(kLevelEpsilon, limiter.knee_start_linear(), kNumSteps);
for (const auto level : levels) {
SCOPED_TRACE(std::to_string(level));
EXPECT_EQ(1.0f, igc.LookUpGainToApply(level));
}
const auto stats = igc.get_stats();
EXPECT_EQ(kNumSteps - 1, stats.look_ups_identity_region);
EXPECT_EQ(1ul, stats.look_ups_knee_region);
EXPECT_EQ(0ul, stats.look_ups_limiter_region);
EXPECT_EQ(0ul, stats.look_ups_saturation_region);
}
TEST(GainController2InterpolatedGainCurve, CheckNoOverApproximationKnee) {
constexpr size_t kNumSteps = 10;
InterpolatedGainCurve igc(&apm_data_dumper, "");
const auto levels =
test::LinSpace(limiter.knee_start_linear() + kLevelEpsilon,
limiter.limiter_start_linear(), kNumSteps);
for (const auto level : levels) {
SCOPED_TRACE(std::to_string(level));
// Small tolerance added (needed because comparing a float with a double).
EXPECT_LE(igc.LookUpGainToApply(level),
limiter.GetGainLinear(level) + 1e-7);
}
const auto stats = igc.get_stats();
EXPECT_EQ(0ul, stats.look_ups_identity_region);
EXPECT_EQ(kNumSteps - 1, stats.look_ups_knee_region);
EXPECT_EQ(1ul, stats.look_ups_limiter_region);
EXPECT_EQ(0ul, stats.look_ups_saturation_region);
}
TEST(GainController2InterpolatedGainCurve, CheckNoOverApproximationBeyondKnee) {
constexpr size_t kNumSteps = 10;
InterpolatedGainCurve igc(&apm_data_dumper, "");
const auto levels = test::LinSpace(
limiter.limiter_start_linear() + kLevelEpsilon,
limiter.max_input_level_linear() - kLevelEpsilon, kNumSteps);
for (const auto level : levels) {
SCOPED_TRACE(std::to_string(level));
// Small tolerance added (needed because comparing a float with a double).
EXPECT_LE(igc.LookUpGainToApply(level),
limiter.GetGainLinear(level) + 1e-7);
}
const auto stats = igc.get_stats();
EXPECT_EQ(0ul, stats.look_ups_identity_region);
EXPECT_EQ(0ul, stats.look_ups_knee_region);
EXPECT_EQ(kNumSteps, stats.look_ups_limiter_region);
EXPECT_EQ(0ul, stats.look_ups_saturation_region);
}
TEST(GainController2InterpolatedGainCurve,
CheckNoOverApproximationWithSaturation) {
constexpr size_t kNumSteps = 3;
InterpolatedGainCurve igc(&apm_data_dumper, "");
const auto levels = test::LinSpace(
limiter.max_input_level_linear() + kLevelEpsilon,
limiter.max_input_level_linear() + kLevelEpsilon + 0.5, kNumSteps);
for (const auto level : levels) {
SCOPED_TRACE(std::to_string(level));
EXPECT_LE(igc.LookUpGainToApply(level), limiter.GetGainLinear(level));
}
const auto stats = igc.get_stats();
EXPECT_EQ(0ul, stats.look_ups_identity_region);
EXPECT_EQ(0ul, stats.look_ups_knee_region);
EXPECT_EQ(0ul, stats.look_ups_limiter_region);
EXPECT_EQ(kNumSteps, stats.look_ups_saturation_region);
}
TEST(GainController2InterpolatedGainCurve, CheckApproximationParams) {
test::InterpolatedParameters parameters =
test::ComputeInterpolatedGainCurveApproximationParams();
InterpolatedGainCurve igc(&apm_data_dumper, "");
for (size_t i = 0; i < kInterpolatedGainCurveTotalPoints; ++i) {
// The tolerance levels are chosen to account for deviations due
// to computing with single precision floating point numbers.
EXPECT_NEAR(igc.approximation_params_x_[i],
parameters.computed_approximation_params_x[i], 0.9f);
EXPECT_NEAR(igc.approximation_params_m_[i],
parameters.computed_approximation_params_m[i], 0.00001f);
EXPECT_NEAR(igc.approximation_params_q_[i],
parameters.computed_approximation_params_q[i], 0.001f);
}
}
} // namespace webrtc
| 36.151961 | 80 | 0.749424 | [
"vector"
] |
78634dd53c2fe9eefa5439ed39697a9aec68f244 | 1,356 | cc | C++ | third_party/blink/renderer/modules/vr/vr_pose.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | third_party/blink/renderer/modules/vr/vr_pose.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | third_party/blink/renderer/modules/vr/vr_pose.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/vr/vr_pose.h"
namespace blink {
namespace {
DOMFloat32Array* MojoArrayToFloat32Array(
const base::Optional<WTF::Vector<float>>& vec) {
if (!vec)
return nullptr;
return DOMFloat32Array::Create(&(vec.value().front()), vec.value().size());
}
} // namespace
VRPose::VRPose() = default;
void VRPose::SetPose(const device::mojom::blink::VRPosePtr& state) {
if (state.is_null())
return;
orientation_ = MojoArrayToFloat32Array(state->orientation);
position_ = MojoArrayToFloat32Array(state->position);
angular_velocity_ = MojoArrayToFloat32Array(state->angularVelocity);
linear_velocity_ = MojoArrayToFloat32Array(state->linearVelocity);
angular_acceleration_ = MojoArrayToFloat32Array(state->angularAcceleration);
linear_acceleration_ = MojoArrayToFloat32Array(state->linearAcceleration);
}
void VRPose::Trace(blink::Visitor* visitor) {
visitor->Trace(orientation_);
visitor->Trace(position_);
visitor->Trace(angular_velocity_);
visitor->Trace(linear_velocity_);
visitor->Trace(angular_acceleration_);
visitor->Trace(linear_acceleration_);
ScriptWrappable::Trace(visitor);
}
} // namespace blink
| 29.478261 | 78 | 0.758112 | [
"vector"
] |
7864f155a1e0914372b06ac0164ea993904ddd68 | 1,649 | cpp | C++ | 012/012.cpp | joeymich/Project-Euler | a061f6ecc2afa9f95f3727380443dfc6e8d43db0 | [
"MIT"
] | 1 | 2022-03-26T07:05:21.000Z | 2022-03-26T07:05:21.000Z | 012/012.cpp | joeymich/Project-Euler | a061f6ecc2afa9f95f3727380443dfc6e8d43db0 | [
"MIT"
] | null | null | null | 012/012.cpp | joeymich/Project-Euler | a061f6ecc2afa9f95f3727380443dfc6e8d43db0 | [
"MIT"
] | null | null | null | // Problem 12 -- Highly divisible triangular number
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
vector<int> prime_factors(unsigned int n)
{
vector<int> primes;
while (n % 2 == 0) {
primes.push_back(2);
n /= 2;
}
for (unsigned int i = 3; i < sqrt(n); i += 2) {
while (n % i == 0) {
primes.push_back(i);
n /= i;
}
}
if (n > 3)
primes.push_back(n);
return primes;
}
vector<int> exponents_from_primes(vector<int> primes)
{
vector<int> exponents;
unsigned int count = 1;
if (primes.size() == 1) {
exponents.push_back(1);
return exponents;
}
for (unsigned int i = 1; i < primes.size(); i++) {
if (primes[i] == primes[i - 1])
count++;
else {
exponents.push_back(count);
count = 1;
}
if (count == 1 && i == primes.size() - 1)
exponents.push_back(count);
}
return exponents;
}
int factors_from_exponents(vector<int> exponents)
{
unsigned int factors = 1;
for (unsigned int i = 0; i < exponents.size(); i++)
factors *= (exponents[i] += 1);
return factors;
}
int num_divisors(int n)
{
return factors_from_exponents(exponents_from_primes(prime_factors(n)));
}
int main()
{
unsigned long long tri_num = 0;
unsigned long long nat_num = 0;
unsigned long long solution;
while(true) {
nat_num++;
tri_num += nat_num;
if (num_divisors(tri_num) > 500) {
solution = tri_num;
break;
}
}
cout << solution << "\n";
} | 22.589041 | 75 | 0.542147 | [
"vector"
] |
78652e9cc398da52fdacece2b4b2689e504923b4 | 17,662 | cxx | C++ | panda/src/express/virtualFileMountRamdisk.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/express/virtualFileMountRamdisk.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/express/virtualFileMountRamdisk.cxx | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file virtualFileMountRamdisk.cxx
* @author drose
* @date 2011-09-19
*/
#include "virtualFileMountRamdisk.h"
#include "subStream.h"
#include "dcast.h"
TypeHandle VirtualFileMountRamdisk::_type_handle;
TypeHandle VirtualFileMountRamdisk::FileBase::_type_handle;
TypeHandle VirtualFileMountRamdisk::File::_type_handle;
TypeHandle VirtualFileMountRamdisk::Directory::_type_handle;
/**
*
*/
VirtualFileMountRamdisk::
VirtualFileMountRamdisk() : _root("") {
}
/**
* Returns true if the indicated file exists within the mount system.
*/
bool VirtualFileMountRamdisk::
has_file(const Filename &file) const {
_lock.lock();
PT(FileBase) f = _root.do_find_file(file);
_lock.unlock();
return (f != NULL);
}
/**
* Attempts to create the indicated file within the mount, if it does not
* already exist. Returns true on success (or if the file already exists), or
* false if it cannot be created.
*/
bool VirtualFileMountRamdisk::
create_file(const Filename &file) {
_lock.lock();
PT(File) f = _root.do_create_file(file);
_lock.unlock();
return (f != NULL);
}
/**
* Attempts to delete the indicated file or directory within the mount. This
* can remove a single file or an empty directory. It will not remove a
* nonempty directory. Returns true on success, false on failure.
*/
bool VirtualFileMountRamdisk::
delete_file(const Filename &file) {
_lock.lock();
PT(FileBase) f = _root.do_delete_file(file);
_lock.unlock();
return (f != NULL);
}
/**
* Attempts to rename the contents of the indicated file to the indicated
* file. Both filenames will be within the mount. Returns true on success,
* false on failure. If this returns false, this will be attempted again with
* a copy-and-delete operation.
*/
bool VirtualFileMountRamdisk::
rename_file(const Filename &orig_filename, const Filename &new_filename) {
_lock.lock();
PT(FileBase) orig_fb = _root.do_find_file(orig_filename);
if (orig_fb == NULL) {
_lock.unlock();
return false;
}
if (orig_fb->is_directory()) {
// Rename the directory.
Directory *orig_d = DCAST(Directory, orig_fb);
PT(Directory) new_d = _root.do_make_directory(new_filename);
if (new_d == NULL || !new_d->_files.empty()) {
_lock.unlock();
return false;
}
if (express_cat.is_debug()) {
express_cat.debug()
<< "Renaming ramdisk directory " << orig_filename << " to " << new_filename << "\n";
}
new_d->_files.swap(orig_d->_files);
_root.do_delete_file(orig_filename);
_lock.unlock();
return true;
}
// Rename the file.
File *orig_f = DCAST(File, orig_fb);
PT(File) new_f = _root.do_create_file(new_filename);
if (new_f == NULL) {
_lock.unlock();
return false;
}
if (express_cat.is_debug()) {
express_cat.debug()
<< "Renaming ramdisk file " << orig_filename << " to " << new_filename << "\n";
}
new_f->_data.str(orig_f->_data.str());
_root.do_delete_file(orig_filename);
_lock.unlock();
return true;
}
/**
* Attempts to copy the contents of the indicated file to the indicated file.
* Both filenames will be within the mount. Returns true on success, false on
* failure. If this returns false, the copy will be performed by explicit
* read-and-write operations.
*/
bool VirtualFileMountRamdisk::
copy_file(const Filename &orig_filename, const Filename &new_filename) {
_lock.lock();
PT(FileBase) orig_fb = _root.do_find_file(orig_filename);
if (orig_fb == NULL || orig_fb->is_directory()) {
_lock.unlock();
return false;
}
// Copy the file.
File *orig_f = DCAST(File, orig_fb);
PT(File) new_f = _root.do_create_file(new_filename);
if (new_f == NULL) {
_lock.unlock();
return false;
}
if (express_cat.is_debug()) {
express_cat.debug()
<< "Copying ramdisk file " << orig_filename << " to " << new_filename << "\n";
}
new_f->_data.str(orig_f->_data.str());
_lock.unlock();
return true;
}
/**
* Attempts to create the indicated file within the mount, if it does not
* already exist. Returns true on success, or false if it cannot be created.
* If the directory already existed prior to this call, may return either true
* or false.
*/
bool VirtualFileMountRamdisk::
make_directory(const Filename &file) {
_lock.lock();
PT(Directory) f = _root.do_make_directory(file);
_lock.unlock();
return (f != NULL);
}
/**
* Returns true if the indicated file exists within the mount system and is a
* directory.
*/
bool VirtualFileMountRamdisk::
is_directory(const Filename &file) const {
_lock.lock();
PT(FileBase) f = _root.do_find_file(file);
_lock.unlock();
return (f != NULL && f->is_directory());
}
/**
* Returns true if the indicated file exists within the mount system and is a
* regular file.
*/
bool VirtualFileMountRamdisk::
is_regular_file(const Filename &file) const {
_lock.lock();
PT(FileBase) f = _root.do_find_file(file);
_lock.unlock();
return (f != NULL && !f->is_directory());
}
/**
* Returns true if the named file or directory may be written to, false
* otherwise.
*/
bool VirtualFileMountRamdisk::
is_writable(const Filename &file) const {
return has_file(file);
}
/**
* Opens the file for reading, if it exists. Returns a newly allocated
* istream on success (which you should eventually delete when you are done
* reading). Returns NULL on failure.
*/
istream *VirtualFileMountRamdisk::
open_read_file(const Filename &file) const {
_lock.lock();
PT(FileBase) f = _root.do_find_file(file);
_lock.unlock();
if (f == (FileBase *)NULL || f->is_directory()) {
return NULL;
}
File *f2 = DCAST(File, f);
return new ISubStream(&f2->_wrapper, 0, 0);
}
/**
* Opens the file for writing. Returns a newly allocated ostream on success
* (which you should eventually delete when you are done writing). Returns
* NULL on failure.
*/
ostream *VirtualFileMountRamdisk::
open_write_file(const Filename &file, bool truncate) {
_lock.lock();
PT(File) f = _root.do_create_file(file);
_lock.unlock();
if (f == (File *)NULL) {
return NULL;
}
if (truncate) {
// Reset to an empty string.
f->_data.str(string());
// Instead of setting the time, we ensure that we always store a newer time.
// This is a workarround for the case that a file is written twice per
// second, since the timer only has a one second precision. The proper
// solution to fix this would be to switch to a higher precision
// timer everywhere.
f->_timestamp = max(f->_timestamp + 1, time(NULL));
}
return new OSubStream(&f->_wrapper, 0, 0);
}
/**
* Works like open_write_file(), but the file is opened in append mode. Like
* open_write_file, the returned pointer should eventually be passed to
* close_write_file().
*/
ostream *VirtualFileMountRamdisk::
open_append_file(const Filename &file) {
_lock.lock();
PT(File) f = _root.do_create_file(file);
_lock.unlock();
if (f == (File *)NULL) {
return NULL;
}
return new OSubStream(&f->_wrapper, 0, 0, true);
}
/**
* Opens the file for writing. Returns a newly allocated iostream on success
* (which you should eventually delete when you are done writing). Returns
* NULL on failure.
*/
iostream *VirtualFileMountRamdisk::
open_read_write_file(const Filename &file, bool truncate) {
_lock.lock();
PT(File) f = _root.do_create_file(file);
_lock.unlock();
if (f == (File *)NULL) {
return NULL;
}
if (truncate) {
// Reset to an empty string.
f->_data.str(string());
// See open_write_file
f->_timestamp = max(f->_timestamp + 1, time(NULL));
}
return new SubStream(&f->_wrapper, 0, 0);
}
/**
* Works like open_read_write_file(), but the file is opened in append mode.
* Like open_read_write_file, the returned pointer should eventually be passed
* to close_read_write_file().
*/
iostream *VirtualFileMountRamdisk::
open_read_append_file(const Filename &file) {
_lock.lock();
PT(FileBase) f = _root.do_find_file(file);
_lock.unlock();
if (f == (FileBase *)NULL || f->is_directory()) {
return NULL;
}
File *f2 = DCAST(File, f);
return new SubStream(&f2->_wrapper, 0, 0, true);
}
/**
* Returns the current size on disk (or wherever it is) of the already-open
* file. Pass in the stream that was returned by open_read_file(); some
* implementations may require this stream to determine the size.
*/
streamsize VirtualFileMountRamdisk::
get_file_size(const Filename &file, istream *stream) const {
_lock.lock();
PT(FileBase) f = _root.do_find_file(file);
_lock.unlock();
if (f == (FileBase *)NULL || f->is_directory()) {
return 0;
}
File *f2 = DCAST(File, f);
return f2->_data.str().length();
}
/**
* Returns the current size on disk (or wherever it is) of the file before it
* has been opened.
*/
streamsize VirtualFileMountRamdisk::
get_file_size(const Filename &file) const {
_lock.lock();
PT(FileBase) f = _root.do_find_file(file);
_lock.unlock();
if (f == (FileBase *)NULL || f->is_directory()) {
return 0;
}
File *f2 = DCAST(File, f);
return f2->_data.str().length();
}
/**
* Returns a time_t value that represents the time the file was last modified,
* to within whatever precision the operating system records this information
* (on a Windows95 system, for instance, this may only be accurate to within 2
* seconds).
*
* If the timestamp cannot be determined, either because it is not supported
* by the operating system or because there is some error (such as file not
* found), returns 0.
*/
time_t VirtualFileMountRamdisk::
get_timestamp(const Filename &file) const {
_lock.lock();
PT(FileBase) f = _root.do_find_file(file);
if (f.is_null()) {
_lock.unlock();
return 0;
}
time_t timestamp = f->_timestamp;
_lock.unlock();
return timestamp;
}
/**
* Fills the given vector up with the list of filenames that are local to this
* directory, if the filename is a directory. Returns true if successful, or
* false if the file is not a directory or cannot be read.
*/
bool VirtualFileMountRamdisk::
scan_directory(vector_string &contents, const Filename &dir) const {
_lock.lock();
PT(FileBase) f = _root.do_find_file(dir);
if (f == (FileBase *)NULL || !f->is_directory()) {
_lock.unlock();
return false;
}
Directory *f2 = DCAST(Directory, f);
bool result = f2->do_scan_directory(contents);
_lock.unlock();
return result;
}
/**
* See Filename::atomic_compare_and_exchange_contents().
*/
bool VirtualFileMountRamdisk::
atomic_compare_and_exchange_contents(const Filename &file, string &orig_contents,
const string &old_contents,
const string &new_contents) {
_lock.lock();
PT(FileBase) f = _root.do_find_file(file);
if (f == (FileBase *)NULL || f->is_directory()) {
_lock.unlock();
return false;
}
bool retval = false;
File *f2 = DCAST(File, f);
orig_contents = f2->_data.str();
if (orig_contents == old_contents) {
f2->_data.str(new_contents);
f2->_timestamp = time(NULL);
retval = true;
}
_lock.unlock();
return retval;
}
/**
* See Filename::atomic_read_contents().
*/
bool VirtualFileMountRamdisk::
atomic_read_contents(const Filename &file, string &contents) const {
_lock.lock();
PT(FileBase) f = _root.do_find_file(file);
if (f == (FileBase *)NULL || f->is_directory()) {
_lock.unlock();
return false;
}
File *f2 = DCAST(File, f);
contents = f2->_data.str();
_lock.unlock();
return true;
}
/**
*
*/
void VirtualFileMountRamdisk::
output(ostream &out) const {
out << "VirtualFileMountRamdisk";
}
/**
*
*/
VirtualFileMountRamdisk::FileBase::
~FileBase() {
}
/**
*
*/
bool VirtualFileMountRamdisk::FileBase::
is_directory() const {
return false;
}
/**
*
*/
bool VirtualFileMountRamdisk::Directory::
is_directory() const {
return true;
}
/**
* Recursively search for the file with the indicated name in this directory
* hierarchy.
*/
PT(VirtualFileMountRamdisk::FileBase) VirtualFileMountRamdisk::Directory::
do_find_file(const string &filename) const {
size_t slash = filename.find('/');
if (slash == string::npos) {
// Search for a file within the local directory.
FileBase tfile(filename);
tfile.local_object();
Files::const_iterator fi = _files.find(&tfile);
if (fi != _files.end()) {
return (*fi);
}
return NULL;
}
// A nested directory. Search for the directory name, then recurse.
string dirname = filename.substr(0, slash);
string remainder = filename.substr(slash + 1);
FileBase tfile(dirname);
tfile.local_object();
Files::const_iterator fi = _files.find(&tfile);
if (fi != _files.end()) {
PT(FileBase) file = (*fi);
if (file->is_directory()) {
return DCAST(Directory, file.p())->do_find_file(remainder);
}
}
return NULL;
}
/**
* Recursively search for the file with the indicated name in this directory
* hierarchy. If not found, creates a new file.
*/
PT(VirtualFileMountRamdisk::File) VirtualFileMountRamdisk::Directory::
do_create_file(const string &filename) {
size_t slash = filename.find('/');
if (slash == string::npos) {
// Search for a file within the local directory.
FileBase tfile(filename);
tfile.local_object();
Files::iterator fi = _files.find(&tfile);
if (fi != _files.end()) {
PT(FileBase) file = (*fi);
if (!file->is_directory()) {
return DCAST(File, file.p());
}
// Cannot create: a directory by the same name already exists.
return NULL;
}
// Create a new file.
if (express_cat.is_debug()) {
express_cat.debug()
<< "Making ramdisk file " << filename << "\n";
}
PT(File) file = new File(filename);
_files.insert(file.p());
_timestamp = time(NULL);
return file;
}
// A nested directory. Search for the directory name, then recurse.
string dirname = filename.substr(0, slash);
string remainder = filename.substr(slash + 1);
FileBase tfile(dirname);
tfile.local_object();
Files::iterator fi = _files.find(&tfile);
if (fi != _files.end()) {
PT(FileBase) file = (*fi);
if (file->is_directory()) {
return DCAST(Directory, file.p())->do_create_file(remainder);
}
}
return NULL;
}
/**
* Recursively search for the file with the indicated name in this directory
* hierarchy. If not found, creates a new directory.
*/
PT(VirtualFileMountRamdisk::Directory) VirtualFileMountRamdisk::Directory::
do_make_directory(const string &filename) {
size_t slash = filename.find('/');
if (slash == string::npos) {
// Search for a file within the local directory.
FileBase tfile(filename);
tfile.local_object();
Files::iterator fi = _files.find(&tfile);
if (fi != _files.end()) {
PT(FileBase) file = (*fi);
if (file->is_directory()) {
return DCAST(Directory, file.p());
}
// Cannot create: a file by the same name already exists.
return NULL;
}
// Create a new directory.
if (express_cat.is_debug()) {
express_cat.debug()
<< "Making ramdisk directory " << filename << "\n";
}
PT(Directory) file = new Directory(filename);
_files.insert(file.p());
_timestamp = time(NULL);
return file;
}
// A nested directory. Search for the directory name, then recurse.
string dirname = filename.substr(0, slash);
string remainder = filename.substr(slash + 1);
FileBase tfile(dirname);
tfile.local_object();
Files::iterator fi = _files.find(&tfile);
if (fi != _files.end()) {
PT(FileBase) file = (*fi);
if (file->is_directory()) {
return DCAST(Directory, file.p())->do_make_directory(remainder);
}
}
return NULL;
}
/**
* Recursively search for the file with the indicated name in this directory
* hierarchy, and removes it. Returns the removed FileBase object.
*/
PT(VirtualFileMountRamdisk::FileBase) VirtualFileMountRamdisk::Directory::
do_delete_file(const string &filename) {
size_t slash = filename.find('/');
if (slash == string::npos) {
// Search for a file within the local directory.
FileBase tfile(filename);
tfile.local_object();
Files::iterator fi = _files.find(&tfile);
if (fi != _files.end()) {
PT(FileBase) file = (*fi);
if (file->is_directory()) {
Directory *dir = DCAST(Directory, file.p());
if (!dir->_files.empty()) {
// Can't delete a nonempty directory.
return NULL;
}
}
_files.erase(fi);
_timestamp = time(NULL);
return file;
}
return NULL;
}
// A nested directory. Search for the directory name, then recurse.
string dirname = filename.substr(0, slash);
string remainder = filename.substr(slash + 1);
FileBase tfile(dirname);
tfile.local_object();
Files::iterator fi = _files.find(&tfile);
if (fi != _files.end()) {
PT(FileBase) file = (*fi);
if (file->is_directory()) {
return DCAST(Directory, file.p())->do_delete_file(remainder);
}
}
return NULL;
}
/**
*
*/
bool VirtualFileMountRamdisk::Directory::
do_scan_directory(vector_string &contents) const {
Files::const_iterator fi;
for (fi = _files.begin(); fi != _files.end(); ++fi) {
FileBase *file = (*fi);
contents.push_back(file->_basename);
}
return true;
}
| 27.006116 | 92 | 0.669913 | [
"object",
"vector",
"3d"
] |
786a58a1e858ace175907756182ee077b1c3911e | 963 | cc | C++ | content/browser/frame_host/navigator_delegate.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/frame_host/navigator_delegate.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | content/browser/frame_host/navigator_delegate.cc | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 "content/browser/frame_host/navigator_delegate.h"
namespace content {
bool NavigatorDelegate::CanOverscrollContent() const {
return false;
}
bool NavigatorDelegate::ShouldTransferNavigation(
bool is_main_frame_navigation) {
return true;
}
bool NavigatorDelegate::ShouldPreserveAbortedURLs() {
return false;
}
std::vector<std::unique_ptr<NavigationThrottle>>
NavigatorDelegate::CreateThrottlesForNavigation(
NavigationHandle* navigation_handle) {
return std::vector<std::unique_ptr<NavigationThrottle>>();
}
std::unique_ptr<NavigationUIData> NavigatorDelegate::GetNavigationUIData(
NavigationHandle* navigation_handle) {
return nullptr;
}
void NavigatorDelegate::AdjustPreviewsStateForNavigation(
PreviewsState* previews_state) {}
} // namespace content
| 26.027027 | 73 | 0.788162 | [
"vector"
] |
786b57ab351f7973d1d27d50ea2a66b525f8b223 | 659 | hpp | C++ | gearoenix/render/texture/gx-rnd-txt-texture-cube.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 35 | 2018-01-07T02:34:38.000Z | 2022-02-09T05:19:03.000Z | gearoenix/render/texture/gx-rnd-txt-texture-cube.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 111 | 2017-09-20T09:12:36.000Z | 2020-12-27T12:52:03.000Z | gearoenix/render/texture/gx-rnd-txt-texture-cube.hpp | Hossein-Noroozpour/gearoenix | c8fa8b8946c03c013dad568d6d7a97d81097c051 | [
"BSD-Source-Code"
] | 5 | 2020-02-11T11:17:37.000Z | 2021-01-08T17:55:43.000Z | #ifndef GEAROENIX_RENDER_TEXTURE_CUBE_HPP
#define GEAROENIX_RENDER_TEXTURE_CUBE_HPP
#include "gx-rnd-txt-texture.hpp"
namespace gearoenix::render::texture {
class TextureCube : public Texture {
GX_GET_VAL_PRT(std::size_t, aspect, 0)
protected:
TextureCube(
core::Id id,
std::string name,
TextureFormat texture_format,
const SamplerInfo& sample_info,
engine::Engine* engine) noexcept;
public:
~TextureCube() noexcept override;
void write_gx3d(
const std::shared_ptr<system::stream::Stream>& s,
const core::sync::EndCaller<core::sync::EndCallerIgnore>& c) noexcept override;
};
}
#endif
| 27.458333 | 87 | 0.705615 | [
"render"
] |
786c26070fc1f685e7ad59a0a327a51932d26cc4 | 907 | cpp | C++ | code/Interleaving String.cpp | htfy96/leetcode-solutions | 4736e87958d7e5aea3cbd999f88c7a86de13205a | [
"Apache-2.0"
] | 1 | 2021-02-21T15:43:13.000Z | 2021-02-21T15:43:13.000Z | code/Interleaving String.cpp | htfy96/leetcode-solutions | 4736e87958d7e5aea3cbd999f88c7a86de13205a | [
"Apache-2.0"
] | null | null | null | code/Interleaving String.cpp | htfy96/leetcode-solutions | 4736e87958d7e5aea3cbd999f88c7a86de13205a | [
"Apache-2.0"
] | 1 | 2018-12-13T07:14:09.000Z | 2018-12-13T07:14:09.000Z | class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
vector<bool> v((s1.size() + 1) * (s2.size() + 1) );
if (s3.empty())
return true;
const int BASE = s2.size() + 1;
v[0] = true;
bool ans = false;
for (int i=0; i<=s1.size(); ++i)
for (int j=0; j<=s2.size(); ++j)
if ((i || j) && i+j<=s3.size())
{
if (i && s1[i-1] == s3[i+j-1])
v[i * BASE + j] = v[(i-1) * BASE + j] | v[i * BASE + j];
if (j && s2[j-1] == s3[i+j-1])
v[i * BASE + j] = v[i * BASE + j-1] | v[i * BASE + j];
if (i + j == s3.size() && i == s1.size() && j == s2.size() && (i || s1.empty()) && (j || s2.empty()))
ans |= v[i* BASE + j];
}
return ans;
}
}; | 39.434783 | 121 | 0.342889 | [
"vector"
] |
7879367830216cdd875f9f95f95e2a88f282ac64 | 8,494 | cc | C++ | paddle/fluid/operators/reduce_op.cc | ghevinn/Paddle | 544159c3de2f74a38a5795c635a2f1bda170379f | [
"ECL-2.0",
"Apache-2.0"
] | 4 | 2019-04-28T13:29:41.000Z | 2022-01-09T16:54:20.000Z | paddle/fluid/operators/reduce_op.cc | ghevinn/Paddle | 544159c3de2f74a38a5795c635a2f1bda170379f | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2018-04-11T10:25:51.000Z | 2018-04-12T01:17:22.000Z | paddle/fluid/operators/reduce_op.cc | ghevinn/Paddle | 544159c3de2f74a38a5795c635a2f1bda170379f | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2018-04-25T03:44:51.000Z | 2018-04-25T03:44:51.000Z | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include "paddle/fluid/operators/reduce_op.h"
namespace paddle {
namespace operators {
using framework::Tensor;
class ReduceOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"),
"Input(X) of ReduceOp should not be null.");
PADDLE_ENFORCE(ctx->HasOutput("Out"),
"Output(Out) of ReduceOp should not be null.");
auto x_dims = ctx->GetInputDim("X");
auto x_rank = x_dims.size();
PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported.");
int dim = ctx->Attrs().Get<int>("dim");
if (dim < 0) dim = x_rank + dim;
PADDLE_ENFORCE_LT(
dim, x_rank,
"The dim should be in the range [-rank(input), rank(input)).");
bool reduce_all = ctx->Attrs().Get<bool>("reduce_all");
bool keep_dim = ctx->Attrs().Get<bool>("keep_dim");
if (reduce_all) {
if (keep_dim)
ctx->SetOutputDim(
"Out", framework::make_ddim(std::vector<int64_t>(x_rank, 1)));
else
ctx->SetOutputDim("Out", {1});
} else {
auto dims_vector = vectorize(x_dims);
if (keep_dim || x_rank == 1) {
dims_vector[dim] = 1;
} else {
dims_vector.erase(dims_vector.begin() + dim);
}
auto out_dims = framework::make_ddim(dims_vector);
ctx->SetOutputDim("Out", out_dims);
if (dim != 0) {
// Only pass LoD when not reducing on the first dim.
ctx->ShareLoD("X", /*->*/ "Out");
}
}
}
};
class ReduceGradOp : public framework::OperatorWithKernel {
public:
using framework::OperatorWithKernel::OperatorWithKernel;
void InferShape(framework::InferShapeContext *ctx) const override {
PADDLE_ENFORCE(ctx->HasInput("X"), "Input(X) should not be null.");
PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
"Input(Out@GRAD) should not be null.");
auto x_dims = ctx->GetInputDim("X");
auto x_rank = x_dims.size();
PADDLE_ENFORCE_LE(x_rank, 6, "Tensors with rank at most 6 are supported.");
int dim = ctx->Attrs().Get<int>("dim");
if (dim < 0) dim = x_rank + dim;
PADDLE_ENFORCE_LT(
dim, x_rank,
"The dim should be in the range [-rank(input), rank(input)).");
auto x_grad_name = framework::GradVarName("X");
if (ctx->HasOutput(x_grad_name)) {
ctx->SetOutputDim(x_grad_name, x_dims);
ctx->ShareLoD("X", /*->*/ x_grad_name);
}
}
};
class ReduceOpMaker : public framework::OpProtoAndCheckerMaker {
public:
ReduceOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: OpProtoAndCheckerMaker(proto, op_checker) {
AddInput("X",
"(Tensor) The input tensor. Tensors with rank at most 6 are "
"supported.");
AddOutput("Out", "(Tensor) The result tensor.");
AddAttr<int>(
"dim",
"(int, default 0) The dimension to reduce. "
"Must be in the range [-rank(input), rank(input)). "
"If `dim < 0`, the dim to reduce is `rank + dim`. "
"Note that reducing on the first dim will make the LoD info lost.")
.SetDefault(0);
AddAttr<bool>("keep_dim",
"(bool, default false) "
"If true, retain the reduced dimension with length 1.")
.SetDefault(false);
AddAttr<bool>("reduce_all",
"(bool, default false) "
"If true, output a scalar reduced along all dimensions.")
.SetDefault(false);
comment_ = R"DOC(
{ReduceOp} Operator.
This operator computes the {reduce} of input tensor along the given dimension.
The result tensor has 1 fewer dimension than the input unless keep_dim is true.
If reduce_all is true, just reduce along all dimensions and output a scalar.
)DOC";
AddComment(comment_);
}
protected:
std::string comment_;
void Replace(std::string &src, std::string from, std::string to) {
std::size_t len_from = std::strlen(from.c_str());
std::size_t len_to = std::strlen(to.c_str());
for (std::size_t pos = src.find(from); pos != std::string::npos;
pos = src.find(from, pos + len_to)) {
src.replace(pos, len_from, to);
}
}
void SetComment(std::string name, std::string op) {
Replace(comment_, "{ReduceOp}", name);
Replace(comment_, "{reduce}", op);
}
};
class ReduceSumOpMaker : public ReduceOpMaker {
public:
ReduceSumOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: ReduceOpMaker(proto, op_checker) {
SetComment("ReduceSum", "sum");
AddComment(comment_);
}
};
class ReduceMeanOpMaker : public ReduceOpMaker {
public:
ReduceMeanOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: ReduceOpMaker(proto, op_checker) {
SetComment("ReduceMean", "mean");
AddComment(comment_);
}
};
class ReduceMaxOpMaker : public ReduceOpMaker {
public:
ReduceMaxOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: ReduceOpMaker(proto, op_checker) {
SetComment("ReduceMax", "max");
AddComment(comment_);
}
};
class ReduceMinOpMaker : public ReduceOpMaker {
public:
ReduceMinOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: ReduceOpMaker(proto, op_checker) {
SetComment("ReduceMin", "min");
AddComment(comment_);
}
};
class ReduceProdOpMaker : public ReduceOpMaker {
public:
ReduceProdOpMaker(OpProto *proto, OpAttrChecker *op_checker)
: ReduceOpMaker(proto, op_checker) {
SetComment("ReduceProd", "production");
AddComment(comment_);
}
};
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators;
REGISTER_OP(reduce_sum, ops::ReduceOp, ops::ReduceSumOpMaker, reduce_sum_grad,
ops::ReduceGradOp);
REGISTER_OP(reduce_mean, ops::ReduceOp, ops::ReduceMeanOpMaker,
reduce_mean_grad, ops::ReduceGradOp);
REGISTER_OP(reduce_max, ops::ReduceOp, ops::ReduceMaxOpMaker, reduce_max_grad,
ops::ReduceGradOp);
REGISTER_OP(reduce_min, ops::ReduceOp, ops::ReduceMinOpMaker, reduce_min_grad,
ops::ReduceGradOp);
REGISTER_OP(reduce_prod, ops::ReduceOp, ops::ReduceProdOpMaker,
reduce_prod_grad, ops::ReduceGradOp);
#define REGISTER_REDUCE_CPU_KERNEL(reduce_type, functor, grad_functor) \
REGISTER_OP_CPU_KERNEL(reduce_type, \
ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
float, ops::functor>, \
ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
double, ops::functor>, \
ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
int, ops::functor>, \
ops::ReduceKernel<paddle::platform::CPUDeviceContext, \
int64_t, ops::functor>); \
REGISTER_OP_CPU_KERNEL( \
reduce_type##_grad, \
ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, float, \
ops::grad_functor>, \
ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, double, \
ops::grad_functor>, \
ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, int, \
ops::grad_functor>, \
ops::ReduceGradKernel<paddle::platform::CPUDeviceContext, int64_t, \
ops::grad_functor>);
FOR_EACH_KERNEL_FUNCTOR(REGISTER_REDUCE_CPU_KERNEL);
| 37.418502 | 80 | 0.615964 | [
"vector"
] |
787a3db5b654d602f7dcecda54684dfcee187d07 | 15,029 | cpp | C++ | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/bluetooth/BluetoothA2dpSink.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 7 | 2017-07-13T10:34:54.000Z | 2021-04-16T05:40:35.000Z | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/bluetooth/BluetoothA2dpSink.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | null | null | null | Sources/Elastos/Frameworks/Droid/Base/Core/src/elastos/droid/bluetooth/BluetoothA2dpSink.cpp | jingcao80/Elastos | d0f39852356bdaf3a1234743b86364493a0441bc | [
"Apache-2.0"
] | 9 | 2017-07-13T12:33:20.000Z | 2021-06-19T02:46:48.000Z | //=========================================================================
// Copyright (C) 2012 The Elastos 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 "Elastos.CoreLibrary.Utility.h"
#include "elastos/droid/bluetooth/BluetoothA2dpSink.h"
#include "elastos/droid/bluetooth/CBluetoothAdapter.h"
#include "elastos/droid/content/CIntent.h"
#include "elastos/droid/os/Process.h"
#include "elastos/core/AutoLock.h"
#include <elastos/core/StringUtils.h>
#include <elastos/utility/logging/Logger.h>
using Elastos::Droid::Content::EIID_IServiceConnection;
using Elastos::Droid::Content::IIntent;
using Elastos::Droid::Content::CIntent;
using Elastos::Droid::Content::Pm::IPackageManager;
using Elastos::Droid::Os::EIID_IBinder;
using Elastos::Droid::Os::IUserHandle;
using Elastos::Droid::Os::Process;
using Elastos::Core::AutoLock;
using Elastos::Core::StringUtils;
using Elastos::Utility::CArrayList;
using Elastos::Utility::Logging::Logger;
namespace Elastos {
namespace Droid {
namespace Bluetooth {
//=====================================================================
// BluetoothA2dpSink::BluetoothStateChangeCallbackStub
//=====================================================================
CAR_INTERFACE_IMPL_2(BluetoothA2dpSink::BluetoothStateChangeCallbackStub, Object, IIBluetoothStateChangeCallback, IBinder);
BluetoothA2dpSink::BluetoothStateChangeCallbackStub::BluetoothStateChangeCallbackStub()
{
}
ECode BluetoothA2dpSink::BluetoothStateChangeCallbackStub::constructor(
/* [in] */ IInterface* owner)
{
mOwner = (BluetoothA2dpSink*)(IBluetoothA2dpSink::Probe(owner));
return NOERROR;
}
ECode BluetoothA2dpSink::BluetoothStateChangeCallbackStub::OnBluetoothStateChange(
/* [in] */ Boolean up)
{
if (DBG) Logger::D(TAG, "onBluetoothStateChange: up=%d", up);
if (!up) {
if (VDBG) Logger::D(TAG,"Unbinding service...");
{
AutoLock lock(mOwner->mConnection);
//try {
mOwner->mService = NULL;
mOwner->mContext->UnbindService(mOwner->mConnection);
//} catch (Exception re) {
// Log.e(TAG,"",re);
//}
}
} else {
{
AutoLock lock(mOwner->mConnection);
//try {
if (mOwner->mService == NULL) {
if (VDBG) Logger::D(TAG,"Binding service...");
Boolean bindResult;
mOwner->DoBind(&bindResult);
}
//} catch (Exception re) {
// Log.e(TAG,"",re);
//}
}
}
return NOERROR;
}
//=====================================================================
// BluetoothA2dpSink::InnerServiceConnection
//=====================================================================
CAR_INTERFACE_IMPL(BluetoothA2dpSink::InnerServiceConnection, Object, IServiceConnection);
BluetoothA2dpSink::InnerServiceConnection::InnerServiceConnection()
{
}
BluetoothA2dpSink::InnerServiceConnection::InnerServiceConnection(
/* [in] */ IBluetoothA2dpSink* owner)
{
mOwner = (BluetoothA2dpSink*)owner;
}
ECode BluetoothA2dpSink::InnerServiceConnection::OnServiceConnected(
/* [in] */ IComponentName* className,
/* [in] */ IBinder* service)
{
if (DBG) Logger::D(TAG, "Proxy object connected");
mOwner->mService = IIBluetoothA2dpSink::Probe(service);
if (mOwner->mServiceListener != NULL) {
mOwner->mServiceListener->OnServiceConnected(IBluetoothProfile::A2DP_SINK,
mOwner);
}
return NOERROR;
}
ECode BluetoothA2dpSink::InnerServiceConnection::OnServiceDisconnected(
/* [in] */ IComponentName* className)
{
if (DBG) Logger::D(TAG, "Proxy object disconnected");
mOwner->mService = NULL;
if (mOwner->mServiceListener != NULL) {
mOwner->mServiceListener->OnServiceDisconnected(IBluetoothProfile::A2DP_SINK);
}
return NOERROR;
}
//=====================================================================
// BluetoothA2dpSink
//=====================================================================
const String BluetoothA2dpSink::TAG("BluetoothA2dpSink");
const Boolean BluetoothA2dpSink::DBG = TRUE;
const Boolean BluetoothA2dpSink::VDBG = FALSE;
CAR_INTERFACE_IMPL_2(BluetoothA2dpSink, Object, IBluetoothA2dpSink, IBluetoothProfile);
BluetoothA2dpSink::BluetoothA2dpSink()
{
}
BluetoothA2dpSink::~BluetoothA2dpSink()
{
Close();
}
BluetoothA2dpSink::BluetoothA2dpSink(
/* [in] */ IContext* context,
/* [in] */ IBluetoothProfileServiceListener* l)
{
mContext = context;
mServiceListener = l;
mAdapter = CBluetoothAdapter::GetDefaultAdapter();
AutoPtr<IIBluetoothManager> mgr = ((CBluetoothAdapter*)mAdapter.Get())->GetBluetoothManager();
if (mgr != NULL) {
//try {
mgr->RegisterStateChangeCallback(mBluetoothStateChangeCallback);
//} catch (RemoteException e) {
// Log.e(TAG,"",e);
//}
}
Boolean bindResult;
DoBind(&bindResult);
}
ECode BluetoothA2dpSink::DoBind(
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
AutoPtr<IIntent> intent;
CIntent::New(String("IBluetoothA2dpSink")/*IBluetoothA2dpSink.class.getName()*/, (IIntent**)&intent);
AutoPtr<IComponentName> comp;
AutoPtr<IPackageManager> pm;
mContext->GetPackageManager((IPackageManager**)&pm);
intent->ResolveSystemService(pm, 0, (IComponentName**)&comp);
intent->SetComponent(comp);
AutoPtr<IUserHandle> userHandle;
Process::MyUserHandle((IUserHandle**)&userHandle);
Boolean succeeded = FALSE;
if (comp == NULL || !(mContext->BindServiceAsUser(intent, mConnection, 0,
userHandle, &succeeded), succeeded)) {
Logger::E(TAG, "Could not bind to Bluetooth A2DP Service with ");// + intent;
*result = FALSE;
return NOERROR;
}
*result = TRUE;
return NOERROR;
}
ECode BluetoothA2dpSink::Close()
{
mServiceListener = NULL;
AutoPtr<IIBluetoothManager> mgr = ((CBluetoothAdapter*)mAdapter.Get())->GetBluetoothManager();
if (mgr != NULL) {
//try {
mgr->UnregisterStateChangeCallback(mBluetoothStateChangeCallback);
//} catch (Exception e) {
// Log.e(TAG,"",e);
//}
}
{
AutoLock lock(mConnection);
if (mService != NULL) {
//try {
mService = NULL;
mContext->UnbindService(mConnection);
//} catch (Exception re) {
// Log.e(TAG,"",re);
//}
}
}
return NOERROR;
}
ECode BluetoothA2dpSink::Connect(
/* [in] */ IBluetoothDevice* device,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
if (DBG) Logger::D(TAG, "connect( device )");
if (mService != NULL && IsEnabled() &&
IsValidDevice(device)) {
//try {
return mService->Connect(device, result);
//} catch (RemoteException e) {
// Log.e(TAG, "Stack:" + Log.getStackTraceString(new Throwable()));
// return false;
//}
}
if (mService == NULL) Logger::W(TAG, "Proxy not attached to service");
*result = FALSE;
return NOERROR;
}
ECode BluetoothA2dpSink::Disconnect(
/* [in] */ IBluetoothDevice* device,
/* [out] */ Boolean* result)
{
VALIDATE_NOT_NULL(result);
if (DBG) Logger::D(TAG, "disconnect( device )");
if (mService != NULL && IsEnabled() &&
IsValidDevice(device)) {
//try {
return mService->Disconnect(device, result);
//} catch (RemoteException e) {
// Log.e(TAG, "Stack:" + Log.getStackTraceString(new Throwable()));
// return false;
//}
}
if (mService == NULL) Logger::W(TAG, "Proxy not attached to service");
*result = FALSE;
return NOERROR;
}
ECode BluetoothA2dpSink::GetConnectedDevices(
/* [out] */ IList** result)
{
VALIDATE_NOT_NULL(result);
if (VDBG) Logger::D(TAG, "getConnectedDevices()");
if (mService != NULL && IsEnabled()) {
//try {
return mService->GetConnectedDevices(result);
//} catch (RemoteException e) {
// Log.e(TAG, "Stack:" + Log.getStackTraceString(new Throwable()));
// return new ArrayList<BluetoothDevice>();
//}
}
if (mService == NULL) Logger::W(TAG, "Proxy not attached to service");
AutoPtr<IList> list;
CArrayList::New((IList**)&list);
*result = list;
REFCOUNT_ADD(*result);
return NOERROR;
}
ECode BluetoothA2dpSink::GetDevicesMatchingConnectionStates(
/* [in] */ ArrayOf<Int32>* states,
/* [out] */ IList** result)
{
VALIDATE_NOT_NULL(result);
if (VDBG) Logger::D(TAG, "getDevicesMatchingStates()");
if (mService != NULL && IsEnabled()) {
//try {
return mService->GetDevicesMatchingConnectionStates(states, result);
//} catch (RemoteException e) {
// Log.e(TAG, "Stack:" + Log.getStackTraceString(new Throwable()));
// return new ArrayList<BluetoothDevice>();
//}
}
if (mService == NULL) Logger::W(TAG, "Proxy not attached to service");
AutoPtr<IList> list;
CArrayList::New((IList**)&list);
*result = list;
REFCOUNT_ADD(*result);
return NOERROR;
}
ECode BluetoothA2dpSink::GetConnectionState(
/* [in] */ IBluetoothDevice* device,
/* [out] */ Int32* result)
{
VALIDATE_NOT_NULL(result);
if (VDBG) Logger::D(TAG, "getState(device)");
if (mService != NULL && IsEnabled()
&& IsValidDevice(device)) {
//try {
return mService->GetConnectionState(device, result);
//} catch (RemoteException e) {
// Log.e(TAG, "Stack:" + Log.getStackTraceString(new Throwable()));
// return BluetoothProfile.STATE_DISCONNECTED;
//}
}
if (mService == NULL) Logger::W(TAG, "Proxy not attached to service");
*result = IBluetoothProfile::STATE_DISCONNECTED;
return NOERROR;
}
ECode BluetoothA2dpSink::GetAudioConfig(
/* [in] */ IBluetoothDevice* device,
/* [out] */ IBluetoothAudioConfig** result)
{
VALIDATE_NOT_NULL(result);
if (VDBG) Logger::D(TAG, "getAudioConfig( device )");
if (mService != NULL && IsEnabled()
&& IsValidDevice(device)) {
//try {
return mService->GetAudioConfig(device, result);
//} catch (RemoteException e) {
// Log.e(TAG, "Stack:" + Log.getStackTraceString(new Throwable()));
// return null;
//}
}
if (mService == NULL) Logger::W(TAG, "Proxy not attached to service");
*result = NULL;
return NOERROR;
}
ECode BluetoothA2dpSink::SetPriority(
/* [in] */ IBluetoothDevice* device,
/* [in] */ Int32 priority,
/* [out] */ Boolean* result)
{
String str;
IObject::Probe(device)->ToString(&str);
if (VDBG) Logger::D(TAG, String("setPriority(") + str + ", " + StringUtils::ToString(priority) + ")");
*result = FALSE;
if (mService != NULL && IsEnabled()
&& IsValidDevice(device)) {
if (priority != IBluetoothProfile::PRIORITY_OFF &&
priority != IBluetoothProfile::PRIORITY_ON){
return NOERROR;
}
// try {
if (FAILED(mService->SetPriority(device, priority, result))) {
Logger::E(TAG, "SetPriority: Remote invoke error");
}
// } catch (RemoteException e) {
// Log.e(TAG, "Stack:" + Log.getStackTraceString(new Throwable()));
// *result = false;
// return NOERROR;
// }
}
if (mService == NULL)
Logger::W(TAG, "Proxy not attached to service");
return NOERROR;
}
ECode BluetoothA2dpSink::GetPriority(
/* [in] */ IBluetoothDevice* device,
/* [out] */ Int32* priority)
{
String str;
IObject::Probe(device)->ToString(&str);
if (VDBG) Logger::D(TAG, String("GetPriority(") + str);
if (mService != NULL && IsEnabled() && IsValidDevice(device)) {
// try {
if (FAILED(mService->GetPriority(device, priority))) {
Logger::E(TAG, "GetPriority: Remote invoke error");
*priority = IBluetoothProfile::PRIORITY_OFF;
}
// } catch (RemoteException e) {
// Log.e(TAG, "Stack:" + Log.getStackTraceString(new Throwable()));
// return BluetoothProfile.PRIORITY_OFF;
// }
}
if (mService == NULL)
Logger::W(TAG, "Proxy not attached to service");
*priority = IBluetoothProfile::PRIORITY_OFF;
return NOERROR;
}
ECode BluetoothA2dpSink::IsA2dpPlaying(
/* [in] */ IBluetoothDevice* device,
/* [out] */ Boolean* result)
{
*result = FALSE;
if (mService != NULL && IsEnabled() && IsValidDevice(device)) {
// try {
if (FAILED(mService->IsA2dpPlaying(device, result))) {
Logger::E(TAG, "IsA2dpPlaying: Remote invoke error");
}
// } catch (RemoteException e) {
// Log.e(TAG, "Stack:" + Log.getStackTraceString(new Throwable()));
// return false;
// }
}
if (mService == NULL)
Logger::W(TAG, "Proxy not attached to service");
return NOERROR;
}
String BluetoothA2dpSink::StateToString(
/* [in] */ Int32 state)
{
switch (state) {
case STATE_DISCONNECTED:
return String("disconnected");
case STATE_CONNECTING:
return String("connecting");
case STATE_CONNECTED:
return String("connected");
case STATE_DISCONNECTING:
return String("disconnecting");
case STATE_PLAYING:
return String("playing");
case STATE_NOT_PLAYING:
return String("not playing");
default:
return String("<unknown state ") + StringUtils::ToString(state) + String(">");
}
return String("");
}
Boolean BluetoothA2dpSink::IsEnabled()
{
Int32 state;
if ((mAdapter->GetState(&state), state) == IBluetoothAdapter::STATE_ON) return TRUE;
return FALSE;
}
Boolean BluetoothA2dpSink::IsValidDevice(
/* [in] */ IBluetoothDevice* device)
{
if (device == NULL) return FALSE;
String address;
device->GetAddress(&address);
if (CBluetoothAdapter::CheckBluetoothAddress(address)) return TRUE;
return FALSE;
}
void BluetoothA2dpSink::Log(
/* [in] */ const String& msg)
{
Logger::D(TAG, msg.string());
}
} // namespace Bluetooth
} // namespace Droid
} // namespace Elastos
| 32.251073 | 123 | 0.600971 | [
"object"
] |
787a41f2fa4934a24d86f6cbf875733446cd5665 | 1,539 | hpp | C++ | shared/image8.hpp | industry-advance/nin10kit | dbf81c62c0fa2f544cfd22b1f7d008a885c2b589 | [
"Apache-2.0"
] | 45 | 2015-03-26T17:14:55.000Z | 2022-03-29T20:27:32.000Z | shared/image8.hpp | industry-advance/nin10kit | dbf81c62c0fa2f544cfd22b1f7d008a885c2b589 | [
"Apache-2.0"
] | 35 | 2015-01-06T16:16:37.000Z | 2021-06-19T05:03:13.000Z | shared/image8.hpp | industry-advance/nin10kit | dbf81c62c0fa2f544cfd22b1f7d008a885c2b589 | [
"Apache-2.0"
] | 5 | 2017-03-26T04:48:02.000Z | 2020-07-10T22:55:49.000Z | #ifndef IMAGE8_HPP
#define IMAGE8_HPP
#include <Magick++.h>
#include <memory>
#include <vector>
#include "color.hpp"
#include "image.hpp"
#include "scene.hpp"
#include "palette.hpp"
class Image16Bpp;
/** 8 Bit Image with palette
* Used for GBA mode 4
*/
class Image8Bpp : public Image
{
public:
Image8Bpp(const Image16Bpp& image, std::shared_ptr<Palette> global_palette = nullptr);
void WriteData(std::ostream& file) const;
void WriteCommonExport(std::ostream& file) const;
void WriteExport(std::ostream& file) const;
virtual bool HasPalette() const {return true;}
unsigned char At(int x, int y) const {return pixels[y * width + x];}
Magick::Image ToMagick() const;
std::vector<unsigned char> pixels;
/** Palette this image uses */
std::shared_ptr<Palette> palette;
private:
/** If true also export palette. */
bool export_shared_info;
};
/** Represents a set of 8 bit images that share a palette
* Used for GBA mode 4 in batch mode
*/
class Image8BppScene : public Scene
{
public:
Image8BppScene(const std::vector<Image16Bpp>& images, const std::string& name, std::shared_ptr<Palette> global_palette = nullptr);
const Image8Bpp& GetImage(int index) const;
void WriteData(std::ostream& file) const;
void WriteExport(std::ostream& file) const;
std::shared_ptr<Palette> palette;
private:
/** If true also export palette. */
bool export_shared_info;
};
#endif
| 29.037736 | 138 | 0.660169 | [
"vector"
] |
788129509985f01a9ce0c568af3072c50d6b2a3b | 5,892 | hpp | C++ | src/petuum_ps_common/include/configs.hpp | zuowang/bosen | 1c823287787b324776fd16ecb3c96f0ec58a989b | [
"BSD-3-Clause"
] | 1 | 2018-01-26T14:29:00.000Z | 2018-01-26T14:29:00.000Z | src/petuum_ps_common/include/configs.hpp | zuowang/bosen | 1c823287787b324776fd16ecb3c96f0ec58a989b | [
"BSD-3-Clause"
] | null | null | null | src/petuum_ps_common/include/configs.hpp | zuowang/bosen | 1c823287787b324776fd16ecb3c96f0ec58a989b | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <inttypes.h>
#include <stdint.h>
#include <map>
#include <vector>
#include <string>
#include <petuum_ps_common/include/host_info.hpp>
#include <petuum_ps_common/include/constants.hpp>
namespace petuum {
enum ConsistencyModel {
/**
* Stale synchronous parallel.
*/
SSP = 0,
/**
* SSP with server push
* Assumes that all clients have the same number of bg threads.
*/
SSPPush = 1,
SSPAggr = 2,
LocalOOC = 6
};
enum UpdateSortPolicy {
FIFO = 0,
Random = 1,
RelativeMagnitude = 2,
FIFO_N_ReMag = 3
};
struct RowOpLogType {
static const int32_t kDenseRowOpLog = 0;
static const int32_t kSparseRowOpLog = 1;
static const int32_t kSparseVectorRowOpLog = 2;
};
enum OpLogType {
Sparse = 0,
AppendOnly = 1,
Dense = 2
};
enum AppendOnlyOpLogType {
Inc = 0,
BatchInc = 1,
DenseBatchInc = 2
};
enum ProcessStorageType {
BoundedDense = 0,
BoundedSparse = 1
};
struct TableGroupConfig {
TableGroupConfig():
stats_path(""),
num_comm_channels_per_client(1),
num_tables(1),
num_total_clients(1),
num_local_app_threads(2),
aggressive_clock(false),
aggressive_cpu(false),
snapshot_clock(-1),
resume_clock(-1),
update_sort_policy(Random),
bg_idle_milli(2),
bandwidth_mbps(40),
oplog_push_upper_bound_kb(100),
oplog_push_staleness_tolerance(2),
thread_oplog_batch_size(100*1000*1000),
server_row_candidate_factor(5) { }
std::string stats_path;
// ================= Global Parameters ===================
// Global parameters have to be the same across all processes.
/**
* Total number of servers in the system.
* Global parameters have to be the same across all processes.
*/
int32_t num_comm_channels_per_client;
/**
* Total number of tables the PS will have. Each init thread must make
* num_tables CreateTable() calls.
* Global parameters have to be the same across all processes.
*/
int32_t num_tables;
/**
* Total number of clients in the system.
* Global parameters have to be the same across all processes.
*/
int32_t num_total_clients;
// ===================== Local Parameters ===================
// Local parameters can differ between processes, but have to sum up to global
// parameters.
/**
* Number of local applications threads, including init thread.
* Local parameters can differ between processes, but have to sum up to global
* parameters.
*/
int32_t num_local_app_threads;
/**
* mapping server ID to host info.
*/
std::map<int32_t, HostInfo> host_map;
/**
* My client id.
*/
int32_t client_id;
/**
* If set to true, oplog send is triggered on every Clock() call.
* If set to false, oplog is only sent if the process clock (representing all
* app threads) has advanced.
* Aggressive clock may reduce memory footprint and improve the per-clock
* convergence rate in the cost of performance.
* Default is false (suggested).
*/
bool aggressive_clock;
ConsistencyModel consistency_model;
int32_t aggressive_cpu;
/**
* In Async+pushing,
*/
int32_t server_ring_size;
int32_t snapshot_clock;
int32_t resume_clock;
std::string snapshot_dir;
std::string resume_dir;
std::string ooc_path_prefix;
UpdateSortPolicy update_sort_policy;
/**
* In number of milliseconds.
* If the bg thread wakes up and finds there's no work to do,
* it goes back to sleep for this much time or until it receives
* a message.
*/
long bg_idle_milli;
/**
* Bandwidth in Megabits per second
*/
double bandwidth_mbps;
/**
* upper bound on update message size in kilobytes
*/
size_t oplog_push_upper_bound_kb;
int32_t oplog_push_staleness_tolerance;
size_t thread_oplog_batch_size;
size_t server_push_row_threshold;
long server_idle_milli;
long server_row_candidate_factor;
};
/**
* TableInfo is shared between client and server.
*/
struct TableInfo {
TableInfo():
table_staleness(0),
row_type(-1),
row_capacity(0),
oplog_dense_serialized(false),
row_oplog_type(1),
dense_row_oplog_capacity(0) { }
/**
* table_staleness is used for SSP and ClockVAP.
*/
int32_t table_staleness;
/**
* A table can only have one type of row. The row_type is defined when
* calling TableGroup::RegisterRow().
*/
int32_t row_type;
/**
* row_capacity can mean different thing for different row_type. For example
* in vector-backed dense row it is the max number of columns. This
* parameter is ignored for sparse row.
*/
size_t row_capacity;
bool oplog_dense_serialized;
int32_t row_oplog_type;
size_t dense_row_oplog_capacity;
};
/**
* ClientTableConfig is used by client only.
*/
struct ClientTableConfig {
ClientTableConfig():
process_cache_capacity(0),
thread_cache_capacity(1),
oplog_capacity(0),
oplog_type(Dense),
append_only_oplog_type(Inc),
append_only_buff_capacity(10*k1_Mi),
per_thread_append_only_buff_pool_size(3),
bg_apply_append_oplog_freq(1),
process_storage_type(BoundedSparse),
no_oplog_replay(false) { }
TableInfo table_info;
/**
* In # of rows.
*/
size_t process_cache_capacity;
/**
* In # of rows.
*/
size_t thread_cache_capacity;
/**
* Estimated upper bound # of pending oplogs in terms of # of rows. For SSP
* this is the # of rows all threads collectively touches in a Clock().
*/
size_t oplog_capacity;
OpLogType oplog_type;
AppendOnlyOpLogType append_only_oplog_type;
size_t append_only_buff_capacity;
/**
* per partition
*/
size_t per_thread_append_only_buff_pool_size;
int32_t bg_apply_append_oplog_freq;
ProcessStorageType process_storage_type;
bool no_oplog_replay;
};
} // namespace petuum
| 21.661765 | 80 | 0.684997 | [
"vector"
] |
7884a658cc0d278dfdfc5a16d4dfec6c60ab8b14 | 8,572 | cpp | C++ | Libs/Kernel/src/Position.cpp | n8vm/OpenVisus | dab633f6ecf13ffcf9ac2ad47d51e48902d4aaef | [
"Unlicense"
] | 1 | 2019-04-30T12:11:24.000Z | 2019-04-30T12:11:24.000Z | Libs/Kernel/src/Position.cpp | tjhei/OpenVisus | f0c3bf21cb0c02f303025a8efb68b8c36701a9fd | [
"Unlicense"
] | null | null | null | Libs/Kernel/src/Position.cpp | tjhei/OpenVisus | f0c3bf21cb0c02f303025a8efb68b8c36701a9fd | [
"Unlicense"
] | null | null | null | /*-----------------------------------------------------------------------------
Copyright(c) 2010 - 2018 ViSUS L.L.C.,
Scientific Computing and Imaging Institute of the University of Utah
ViSUS L.L.C., 50 W.Broadway, Ste. 300, 84101 - 2044 Salt Lake City, UT
University of Utah, 72 S Central Campus Dr, Room 3750, 84112 Salt Lake City, UT
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.
For additional information about this project contact : pascucci@acm.org
For support : support@visus.net
-----------------------------------------------------------------------------*/
#include <Visus/Position.h>
namespace Visus {
//////////////////////////////////////////////////
Position Position::withoutTransformation() const
{
if (!this->valid())
return Position::invalid();
Matrix T = getTransformation();
Box3d box = getBox();
Box3d ret = Box3d::invalid();
for (int I = 0; I<8; I++)
ret.addPoint(T * box.getPoint(I));
return Position(ret);
}
//////////////////////////////////////////////////
Position Position::shrink(const Box3d& dst_box,const LinearMap& map,Position position)
{
const int unit_box_edges[12][2]=
{
{0,1}, {1,2}, {2,3}, {3,0},
{4,5}, {5,6}, {6,7}, {7,4},
{0,4}, {1,5}, {2,6}, {3,7}
};
if (!position.valid())
return position;
const LinearMap& T2(map);
MatrixMap T1(position.getTransformation());
Box3d src_rvalue=position.getBox();
Box3d shrinked_rvalue= Box3d::invalid();
#define DIRECT(T2,T1,value) (T2.applyDirectMap(T1.applyDirectMap(value)))
#define INVERSE(T2,T1,value) (T1.applyInverseMap(T2.applyInverseMap(value)))
int query_dim=position.getBox().minsize()>0? 3 : 2;
if (query_dim==2)
{
int slice_axis=-1;
if (src_rvalue.p1.x==src_rvalue.p2.x) {if (slice_axis>=0) return Position::invalid();slice_axis=0;}
if (src_rvalue.p1.y==src_rvalue.p2.y) {if (slice_axis>=0) return Position::invalid();slice_axis=1;}
if (src_rvalue.p1.z==src_rvalue.p2.z) {if (slice_axis>=0) return Position::invalid();slice_axis=2;}
VisusAssert(slice_axis>=0);
VisusAssert(src_rvalue.p1[slice_axis]==src_rvalue.p2[slice_axis]);
double slice_pos=src_rvalue.p1[slice_axis];
Plane slice_planes[3]={Plane(1,0,0,-slice_pos),Plane(0,1,0,-slice_pos),Plane(0,0,1,-slice_pos)};
//how the plane is transformed by <T> (i.e. go to screen)
Plane slice_plane_in_screen=DIRECT(T2,T1,slice_planes[slice_axis]);
//point classification
double distances[8];
//points belonging to the plane
for (int I=0;I<8;I++)
{
Point3d p=dst_box.getPoint(I);
distances[I]=slice_plane_in_screen.getDistance(p);
if (!distances[I])
{
p=INVERSE(T2,T1,Point4d(p,1.0)).dropHomogeneousCoordinate();
p[slice_axis]=slice_pos; //I know it must implicitely be on the Z plane!
shrinked_rvalue.addPoint(p);
}
}
//split edges
for (int E=0;E<12;E++)
{
int i1=unit_box_edges[E][0];double h1=distances[i1];
int i2=unit_box_edges[E][1];double h2=distances[i2];
if ((h1>0 && h2<0) || (h1<0 && h2>0))
{
Point3d p1=dst_box.getPoint(i1);h1=fabs(h1);
Point3d p2=dst_box.getPoint(i2);h2=fabs(h2);
double alpha =h2/(h1+h2);
double beta =h1/(h1+h2);
Point3d p=INVERSE(T2,T1,Point4d(alpha*p1 + beta*p2,1.0)).dropHomogeneousCoordinate();
p[slice_axis]=slice_pos; //I know it must implicitely be on the Z plane!
shrinked_rvalue.addPoint(p);
}
}
}
else
{
auto isPointInsideHull=[](const Point3d& point,const std::vector<Plane>& planes)
{
const double epsilon = 1e-4;
bool bInside=true;
for (int I=0;bInside && I<(int)planes.size();I++)
bInside=planes[I].getDistance(point)<epsilon;
return bInside;
};
//see http://www.gamedev.net/community/forums/topic.asp?topic_id=224689
VisusAssert(query_dim==3);
//the first polyhedra (i.e. position)
Point3d V1[8]; for (int I=0;I<8;I++) V1[I]=src_rvalue.getPoint(I);
std::vector<Plane> H1=src_rvalue.getPlanes();
//the second polyhedra (transformed to be in the first polyhedra system, i.e. position)
Point3d V2[8];for (int I=0;I<8;I++)
V2[I]=INVERSE(T2,T1,Point4d(dst_box.getPoint(I),1.0)).dropHomogeneousCoordinate();
std::vector<Plane> H2=dst_box.getPlanes();
for (int H=0;H<6;H++)
H2[H]=INVERSE(T2,T1,H2[H]);
//point of the first (second) polyhedra inside second (first) polyhedra
for (int V=0;V<8;V++) {if (isPointInsideHull(V1[V],H2)) {shrinked_rvalue.addPoint(V1[V]);}}
for (int V=0;V<8;V++) {if (isPointInsideHull(V2[V],H1)) {shrinked_rvalue.addPoint(V2[V]);}}
//intersection of first polydra edges with second polyhedral planes
for (int H=0;H<6;H++)
{
double distances[8];
for (int V=0;V<8;V++) distances[V]=H2[H].getDistance(V1[V]);
for (int E=0;E<12;E++)
{
int i1=unit_box_edges[E][0];double h1=distances[i1];
int i2=unit_box_edges[E][1];double h2=distances[i2];
if ((h1>0 && h2<0) || (h1<0 && h2>0))
{
Point3d p1=V1[i1];h1=fabs(h1);
Point3d p2=V1[i2];h2=fabs(h2);
double alpha =h2/(h1+h2);
double beta =h1/(h1+h2);
Point3d p=alpha*p1+beta*p2;
if (isPointInsideHull(p,H2)) {shrinked_rvalue.addPoint(p);}
}
}
}
//intersection of second polyhedra edges with first polyhedral planes
for (int H=0;H<6;H++)
{
double distances[8];
for (int V=0;V<8;V++) distances[V]=H1[H].getDistance(V2[V]);
for (int E=0;E<12;E++)
{
int i1=unit_box_edges[E][0];double h1=distances[i1];
int i2=unit_box_edges[E][1];double h2=distances[i2];
if ((h1>0 && h2<0) || (h1<0 && h2>0))
{
Point3d p1=V2[i1];h1=fabs(h1);
Point3d p2=V2[i2];h2=fabs(h2);
double alpha =h2/(h1+h2);
double beta =h1/(h1+h2);
Point3d p=alpha*p1+beta*p2;
if (isPointInsideHull(p,H1)) {shrinked_rvalue.addPoint(p);}
}
}
}
}
if (shrinked_rvalue.valid())
shrinked_rvalue=shrinked_rvalue.getIntersection(src_rvalue);
return Position(position.getTransformation(),shrinked_rvalue);
#undef DIRECT
#undef INVERSE
}
//////////////////////////////////////////////////
void Position::writeToObjectStream(ObjectStream& ostream)
{
if (!valid())
return;
ostream.writeInline("pdim",cstring(pdim));
if (!T.isIdentity())
{
ostream.pushContext("T");
T.writeToObjectStream(ostream);
ostream.popContext("T");
}
ostream.pushContext("box");
this->box.writeToObjectStream(ostream);
ostream.popContext("box");
}
//////////////////////////////////////////////////
void Position::readFromObjectStream(ObjectStream& istream)
{
this->T=Matrix::identity();
this->pdim=cint(istream.readInline("pdim"));
if (istream.pushContext("T"))
{
this->T.readFromObjectStream(istream);
istream.popContext("T");
}
if (istream.pushContext("box"))
{
this->box.readFromObjectStream(istream);
istream.popContext("box");
}
}
} //namespace Visus
| 32.969231 | 103 | 0.633691 | [
"vector"
] |
78857be1ea9d52d6e22919df26a1a4c127db1de8 | 1,356 | cpp | C++ | p1865.cpp | sjnov11/Baekjoon-Online-Judge | a95df8a62e181d86a97d0e8969d139a3dae2be74 | [
"MIT"
] | null | null | null | p1865.cpp | sjnov11/Baekjoon-Online-Judge | a95df8a62e181d86a97d0e8969d139a3dae2be74 | [
"MIT"
] | null | null | null | p1865.cpp | sjnov11/Baekjoon-Online-Judge | a95df8a62e181d86a97d0e8969d139a3dae2be74 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
#define INF 99999999
vector<pair<int, int>> adj_list[501];
int main() {
cin.tie(NULL);
ios::sync_with_stdio(false);
int T;
cin >> T;
for (int tc = 1; tc <= T; tc++) {
int N, M, W;
cin >> N >> M >> W;
for (int i = 1; i <= 500; i++) {
adj_list[i].clear();
}
for (int i = 0; i < M; i++) {
int S, E, T;
cin >> S >> E >> T;
adj_list[S].push_back(make_pair(E, T));
adj_list[E].push_back(make_pair(S, T));
}
for (int i = 0; i < W; i++) {
int S, E, T;
cin >> S >> E >> T;
adj_list[S].push_back(make_pair(E, T*(-1)));
}
int dist[501];
for (int i = 1; i <= 500; i++) {
dist[i] = INF;
}
dist[1] = 0;
for (int i = 0; i < N - 1; i++) {
for (int u = 1; u <= N; u++) {
if (dist[u] == INF) continue;
for (auto edge : adj_list[u]) {
int v = edge.first;
int w = edge.second;
if (dist[v] > dist[u] + w)
dist[v] = dist[u] + w;
}
}
}
bool cycle = false;
for (int u = 1; u <= N; u++) {
if (dist[u] == INF) continue;
for (auto edge : adj_list[u]) {
int v = edge.first;
int w = edge.second;
if (dist[v] > dist[u] + w) {
//cout << "YES\n";
cycle = true;
break;
//return 0;
}
}
}
if (!cycle) {
cout << "NO\n";
}
else {
cout << "YES\n";
}
}
}
| 17.61039 | 47 | 0.465339 | [
"vector"
] |
7886b2d23d14d1d5a624d6f50e0303a2e131c77b | 15,454 | cc | C++ | quiche/spdy/core/hpack/hpack_header_table_test.cc | ktprime/quiche-1 | abf85ce22e1409a870b1bf470cb5a68cbdb28e50 | [
"BSD-3-Clause"
] | null | null | null | quiche/spdy/core/hpack/hpack_header_table_test.cc | ktprime/quiche-1 | abf85ce22e1409a870b1bf470cb5a68cbdb28e50 | [
"BSD-3-Clause"
] | null | null | null | quiche/spdy/core/hpack/hpack_header_table_test.cc | ktprime/quiche-1 | abf85ce22e1409a870b1bf470cb5a68cbdb28e50 | [
"BSD-3-Clause"
] | null | null | null | // 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 "quiche/spdy/core/hpack/hpack_header_table.h"
#include <algorithm>
#include <cstdint>
#include <set>
#include <string>
#include <vector>
#include "quiche/common/platform/api/quiche_test.h"
#include "quiche/spdy/core/hpack/hpack_constants.h"
#include "quiche/spdy/core/hpack/hpack_entry.h"
#include "quiche/spdy/core/hpack/hpack_static_table.h"
namespace spdy {
using std::distance;
namespace test {
class HpackHeaderTablePeer {
public:
explicit HpackHeaderTablePeer(HpackHeaderTable* table) : table_(table) {}
const HpackHeaderTable::DynamicEntryTable& dynamic_entries() {
return table_->dynamic_entries_;
}
const HpackHeaderTable::StaticEntryTable& static_entries() {
return table_->static_entries_;
}
const HpackEntry* GetFirstStaticEntry() {
return &table_->static_entries_.front();
}
const HpackEntry* GetLastStaticEntry() {
return &table_->static_entries_.back();
}
std::vector<HpackEntry*> EvictionSet(absl::string_view name,
absl::string_view value) {
HpackHeaderTable::DynamicEntryTable::iterator begin, end;
table_->EvictionSet(name, value, &begin, &end);
std::vector<HpackEntry*> result;
for (; begin != end; ++begin) {
result.push_back(begin->get());
}
return result;
}
size_t dynamic_table_insertions() {
return table_->dynamic_table_insertions_;
}
size_t EvictionCountForEntry(absl::string_view name,
absl::string_view value) {
return table_->EvictionCountForEntry(name, value);
}
size_t EvictionCountToReclaim(size_t reclaim_size) {
return table_->EvictionCountToReclaim(reclaim_size);
}
void Evict(size_t count) { return table_->Evict(count); }
private:
HpackHeaderTable* table_;
};
} // namespace test
namespace {
class HpackHeaderTableTest : public quiche::test::QuicheTest {
protected:
typedef std::vector<HpackEntry> HpackEntryVector;
HpackHeaderTableTest() : table_(), peer_(&table_) {}
// Returns an entry whose Size() is equal to the given one.
static HpackEntry MakeEntryOfSize(uint32_t size) {
EXPECT_GE(size, kHpackEntrySizeOverhead);
std::string name((size - kHpackEntrySizeOverhead) / 2, 'n');
std::string value(size - kHpackEntrySizeOverhead - name.size(), 'v');
HpackEntry entry(name, value);
EXPECT_EQ(size, entry.Size());
return entry;
}
// Returns a vector of entries whose total size is equal to the given
// one.
static HpackEntryVector MakeEntriesOfTotalSize(uint32_t total_size) {
EXPECT_GE(total_size, kHpackEntrySizeOverhead);
uint32_t entry_size = kHpackEntrySizeOverhead;
uint32_t remaining_size = total_size;
HpackEntryVector entries;
while (remaining_size > 0) {
EXPECT_LE(entry_size, remaining_size);
entries.push_back(MakeEntryOfSize(entry_size));
remaining_size -= entry_size;
entry_size = std::min(remaining_size, entry_size + 32);
}
return entries;
}
// Adds the given vector of entries to the given header table,
// expecting no eviction to happen.
void AddEntriesExpectNoEviction(const HpackEntryVector& entries) {
for (auto it = entries.begin(); it != entries.end(); ++it) {
HpackHeaderTable::DynamicEntryTable::iterator begin, end;
table_.EvictionSet(it->name(), it->value(), &begin, &end);
EXPECT_EQ(0, distance(begin, end));
const HpackEntry* entry = table_.TryAddEntry(it->name(), it->value());
EXPECT_NE(entry, static_cast<HpackEntry*>(nullptr));
}
}
HpackHeaderTable table_;
test::HpackHeaderTablePeer peer_;
};
TEST_F(HpackHeaderTableTest, StaticTableInitialization) {
EXPECT_EQ(0u, table_.size());
EXPECT_EQ(kDefaultHeaderTableSizeSetting, table_.max_size());
EXPECT_EQ(kDefaultHeaderTableSizeSetting, table_.settings_size_bound());
EXPECT_EQ(0u, peer_.dynamic_entries().size());
EXPECT_EQ(0u, peer_.dynamic_table_insertions());
// Static entries have been populated and inserted into the table & index.
const HpackHeaderTable::StaticEntryTable& static_entries =
peer_.static_entries();
EXPECT_EQ(kStaticTableSize, static_entries.size());
// HPACK indexing scheme is 1-based.
size_t index = 1;
for (const HpackEntry& entry : static_entries) {
EXPECT_EQ(index, table_.GetByNameAndValue(entry.name(), entry.value()));
index++;
}
}
TEST_F(HpackHeaderTableTest, BasicDynamicEntryInsertionAndEviction) {
EXPECT_EQ(kStaticTableSize, peer_.static_entries().size());
const HpackEntry* first_static_entry = peer_.GetFirstStaticEntry();
const HpackEntry* last_static_entry = peer_.GetLastStaticEntry();
const HpackEntry* entry = table_.TryAddEntry("header-key", "Header Value");
EXPECT_EQ("header-key", entry->name());
EXPECT_EQ("Header Value", entry->value());
// Table counts were updated appropriately.
EXPECT_EQ(entry->Size(), table_.size());
EXPECT_EQ(1u, peer_.dynamic_entries().size());
EXPECT_EQ(kStaticTableSize, peer_.static_entries().size());
EXPECT_EQ(62u, table_.GetByNameAndValue("header-key", "Header Value"));
// Index of static entries does not change.
EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry());
EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry());
// Evict |entry|. Table counts are again updated appropriately.
peer_.Evict(1);
EXPECT_EQ(0u, table_.size());
EXPECT_EQ(0u, peer_.dynamic_entries().size());
EXPECT_EQ(kStaticTableSize, peer_.static_entries().size());
// Index of static entries does not change.
EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry());
EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry());
}
TEST_F(HpackHeaderTableTest, EntryIndexing) {
const HpackEntry* first_static_entry = peer_.GetFirstStaticEntry();
const HpackEntry* last_static_entry = peer_.GetLastStaticEntry();
// Static entries are queryable by name & value.
EXPECT_EQ(1u, table_.GetByName(first_static_entry->name()));
EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(),
first_static_entry->value()));
// Create a mix of entries which duplicate names, and names & values of both
// dynamic and static entries.
table_.TryAddEntry(first_static_entry->name(), first_static_entry->value());
table_.TryAddEntry(first_static_entry->name(), "Value Four");
table_.TryAddEntry("key-1", "Value One");
table_.TryAddEntry("key-2", "Value Three");
table_.TryAddEntry("key-1", "Value Two");
table_.TryAddEntry("key-2", "Value Three");
table_.TryAddEntry("key-2", "Value Four");
// The following entry is identical to the one at index 68. The smaller index
// is returned by GetByNameAndValue().
EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(),
first_static_entry->value()));
EXPECT_EQ(67u,
table_.GetByNameAndValue(first_static_entry->name(), "Value Four"));
EXPECT_EQ(66u, table_.GetByNameAndValue("key-1", "Value One"));
EXPECT_EQ(64u, table_.GetByNameAndValue("key-1", "Value Two"));
// The following entry is identical to the one at index 65. The smaller index
// is returned by GetByNameAndValue().
EXPECT_EQ(63u, table_.GetByNameAndValue("key-2", "Value Three"));
EXPECT_EQ(62u, table_.GetByNameAndValue("key-2", "Value Four"));
// Index of static entries does not change.
EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry());
EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry());
// Querying by name returns the most recently added matching entry.
EXPECT_EQ(64u, table_.GetByName("key-1"));
EXPECT_EQ(62u, table_.GetByName("key-2"));
EXPECT_EQ(1u, table_.GetByName(first_static_entry->name()));
EXPECT_EQ(kHpackEntryNotFound, table_.GetByName("not-present"));
// Querying by name & value returns the lowest-index matching entry among
// static entries, and the highest-index one among dynamic entries.
EXPECT_EQ(66u, table_.GetByNameAndValue("key-1", "Value One"));
EXPECT_EQ(64u, table_.GetByNameAndValue("key-1", "Value Two"));
EXPECT_EQ(63u, table_.GetByNameAndValue("key-2", "Value Three"));
EXPECT_EQ(62u, table_.GetByNameAndValue("key-2", "Value Four"));
EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(),
first_static_entry->value()));
EXPECT_EQ(67u,
table_.GetByNameAndValue(first_static_entry->name(), "Value Four"));
EXPECT_EQ(kHpackEntryNotFound,
table_.GetByNameAndValue("key-1", "Not Present"));
EXPECT_EQ(kHpackEntryNotFound,
table_.GetByNameAndValue("not-present", "Value One"));
// Evict |entry1|. Queries for its name & value now return the static entry.
// |entry2| remains queryable.
peer_.Evict(1);
EXPECT_EQ(1u, table_.GetByNameAndValue(first_static_entry->name(),
first_static_entry->value()));
EXPECT_EQ(67u,
table_.GetByNameAndValue(first_static_entry->name(), "Value Four"));
// Evict |entry2|. Queries by its name & value are not found.
peer_.Evict(1);
EXPECT_EQ(kHpackEntryNotFound,
table_.GetByNameAndValue(first_static_entry->name(), "Value Four"));
// Index of static entries does not change.
EXPECT_EQ(first_static_entry, peer_.GetFirstStaticEntry());
EXPECT_EQ(last_static_entry, peer_.GetLastStaticEntry());
}
TEST_F(HpackHeaderTableTest, SetSizes) {
std::string key = "key", value = "value";
const HpackEntry* entry1 = table_.TryAddEntry(key, value);
const HpackEntry* entry2 = table_.TryAddEntry(key, value);
const HpackEntry* entry3 = table_.TryAddEntry(key, value);
// Set exactly large enough. No Evictions.
size_t max_size = entry1->Size() + entry2->Size() + entry3->Size();
table_.SetMaxSize(max_size);
EXPECT_EQ(3u, peer_.dynamic_entries().size());
// Set just too small. One eviction.
max_size = entry1->Size() + entry2->Size() + entry3->Size() - 1;
table_.SetMaxSize(max_size);
EXPECT_EQ(2u, peer_.dynamic_entries().size());
// Changing SETTINGS_HEADER_TABLE_SIZE.
EXPECT_EQ(kDefaultHeaderTableSizeSetting, table_.settings_size_bound());
// In production, the size passed to SetSettingsHeaderTableSize is never
// larger than table_.settings_size_bound().
table_.SetSettingsHeaderTableSize(kDefaultHeaderTableSizeSetting * 3 + 1);
EXPECT_EQ(kDefaultHeaderTableSizeSetting * 3 + 1, table_.max_size());
// SETTINGS_HEADER_TABLE_SIZE upper-bounds |table_.max_size()|,
// and will force evictions.
max_size = entry3->Size() - 1;
table_.SetSettingsHeaderTableSize(max_size);
EXPECT_EQ(max_size, table_.max_size());
EXPECT_EQ(max_size, table_.settings_size_bound());
EXPECT_EQ(0u, peer_.dynamic_entries().size());
}
TEST_F(HpackHeaderTableTest, EvictionCountForEntry) {
std::string key = "key", value = "value";
const HpackEntry* entry1 = table_.TryAddEntry(key, value);
const HpackEntry* entry2 = table_.TryAddEntry(key, value);
size_t entry3_size = HpackEntry::Size(key, value);
// Just enough capacity for third entry.
table_.SetMaxSize(entry1->Size() + entry2->Size() + entry3_size);
EXPECT_EQ(0u, peer_.EvictionCountForEntry(key, value));
EXPECT_EQ(1u, peer_.EvictionCountForEntry(key, value + "x"));
// No extra capacity. Third entry would force evictions.
table_.SetMaxSize(entry1->Size() + entry2->Size());
EXPECT_EQ(1u, peer_.EvictionCountForEntry(key, value));
EXPECT_EQ(2u, peer_.EvictionCountForEntry(key, value + "x"));
}
TEST_F(HpackHeaderTableTest, EvictionCountToReclaim) {
std::string key = "key", value = "value";
const HpackEntry* entry1 = table_.TryAddEntry(key, value);
const HpackEntry* entry2 = table_.TryAddEntry(key, value);
EXPECT_EQ(1u, peer_.EvictionCountToReclaim(1));
EXPECT_EQ(1u, peer_.EvictionCountToReclaim(entry1->Size()));
EXPECT_EQ(2u, peer_.EvictionCountToReclaim(entry1->Size() + 1));
EXPECT_EQ(2u, peer_.EvictionCountToReclaim(entry1->Size() + entry2->Size()));
}
// Fill a header table with entries. Make sure the entries are in
// reverse order in the header table.
TEST_F(HpackHeaderTableTest, TryAddEntryBasic) {
EXPECT_EQ(0u, table_.size());
EXPECT_EQ(table_.settings_size_bound(), table_.max_size());
HpackEntryVector entries = MakeEntriesOfTotalSize(table_.max_size());
// Most of the checks are in AddEntriesExpectNoEviction().
AddEntriesExpectNoEviction(entries);
EXPECT_EQ(table_.max_size(), table_.size());
EXPECT_EQ(table_.settings_size_bound(), table_.size());
}
// Fill a header table with entries, and then ramp the table's max
// size down to evict an entry one at a time. Make sure the eviction
// happens as expected.
TEST_F(HpackHeaderTableTest, SetMaxSize) {
HpackEntryVector entries =
MakeEntriesOfTotalSize(kDefaultHeaderTableSizeSetting / 2);
AddEntriesExpectNoEviction(entries);
for (auto it = entries.begin(); it != entries.end(); ++it) {
size_t expected_count = distance(it, entries.end());
EXPECT_EQ(expected_count, peer_.dynamic_entries().size());
table_.SetMaxSize(table_.size() + 1);
EXPECT_EQ(expected_count, peer_.dynamic_entries().size());
table_.SetMaxSize(table_.size());
EXPECT_EQ(expected_count, peer_.dynamic_entries().size());
--expected_count;
table_.SetMaxSize(table_.size() - 1);
EXPECT_EQ(expected_count, peer_.dynamic_entries().size());
}
EXPECT_EQ(0u, table_.size());
}
// Fill a header table with entries, and then add an entry just big
// enough to cause eviction of all but one entry. Make sure the
// eviction happens as expected and the long entry is inserted into
// the table.
TEST_F(HpackHeaderTableTest, TryAddEntryEviction) {
HpackEntryVector entries = MakeEntriesOfTotalSize(table_.max_size());
AddEntriesExpectNoEviction(entries);
// The first entry in the dynamic table.
const HpackEntry* survivor_entry = peer_.dynamic_entries().front().get();
HpackEntry long_entry =
MakeEntryOfSize(table_.max_size() - survivor_entry->Size());
// All dynamic entries but the first are to be evicted.
EXPECT_EQ(peer_.dynamic_entries().size() - 1,
peer_.EvictionSet(long_entry.name(), long_entry.value()).size());
table_.TryAddEntry(long_entry.name(), long_entry.value());
EXPECT_EQ(2u, peer_.dynamic_entries().size());
EXPECT_EQ(63u, table_.GetByNameAndValue(survivor_entry->name(),
survivor_entry->value()));
EXPECT_EQ(62u,
table_.GetByNameAndValue(long_entry.name(), long_entry.value()));
}
// Fill a header table with entries, and then add an entry bigger than
// the entire table. Make sure no entry remains in the table.
TEST_F(HpackHeaderTableTest, TryAddTooLargeEntry) {
HpackEntryVector entries = MakeEntriesOfTotalSize(table_.max_size());
AddEntriesExpectNoEviction(entries);
const HpackEntry long_entry = MakeEntryOfSize(table_.max_size() + 1);
// All entries are to be evicted.
EXPECT_EQ(peer_.dynamic_entries().size(),
peer_.EvictionSet(long_entry.name(), long_entry.value()).size());
const HpackEntry* new_entry =
table_.TryAddEntry(long_entry.name(), long_entry.value());
EXPECT_EQ(new_entry, static_cast<HpackEntry*>(nullptr));
EXPECT_EQ(0u, peer_.dynamic_entries().size());
}
} // namespace
} // namespace spdy
| 39.323155 | 80 | 0.720784 | [
"vector"
] |
7889b54426a15aab1b93d8cfeed5ca57823c7e55 | 8,833 | cpp | C++ | Src/BsImguiInputs.cpp | guestnone/bsfImgui | 1c736547a4decd36e9203b9c8acba62858a9be58 | [
"MIT"
] | 14 | 2019-07-10T16:50:51.000Z | 2020-12-31T14:51:52.000Z | Src/BsImguiInputs.cpp | guestnone/bsfImgui | 1c736547a4decd36e9203b9c8acba62858a9be58 | [
"MIT"
] | 1 | 2019-09-23T14:26:44.000Z | 2019-09-23T14:26:44.000Z | Src/BsImguiInputs.cpp | guestnone/bsfImgui | 1c736547a4decd36e9203b9c8acba62858a9be58 | [
"MIT"
] | 4 | 2019-08-08T11:39:02.000Z | 2020-12-31T14:51:54.000Z | #include "imgui.h"
#include "ImGuizmo.h"
#include "./BsImgui.h"
#include "BsPrerequisites.h"
#include "Input/BsInputFwd.h"
#include "Platform/BsPlatform.h"
#include "Platform/BsCursor.h"
#include "Input/BsInput.h"
#include "BsApplication.h"
// utility operator for osstream debugging.
std::ostream& operator<<(std::ostream& s, const ImVec2& vec) {
s << vec.x << " " << vec.y;
return s;
}
namespace bs {
// forward declare
void updateImguiInputs();
enum BsfClientApi {
BsfClientApi_Unknown,
BsfClientApi_OpenGL,
BsfClientApi_Vulkan
};
// static bool g_MousePressed[3] = {false, false, false};
static CursorType g_MouseCursors[ImGuiMouseCursor_COUNT] = {};
static float g_Time = 0.0;
// kinda a hack to copy our local mouswheel to the io at a specific time
// instead of as part of event since it keeps getting reset between frames...
// if other inputs are failing to be captured, we'll likely need to store
// local static variable, and then copy over during the imguiUpdateInputs
// which is called before the start of each frame. *shrug*.
static float gMouseWheel = 0.f;
static INT32 displayTop{0};
static INT32 displayLeft{0};
static const char* ImGui_ImplBsf_GetClipboardText(void* user_data) {
return Platform::copyFromClipboard().c_str();
}
static void ImGui_ImplBsf_SetClipboardText(void* user_data, const char* text) {
Platform::copyToClipboard(text);
}
void connectInputs();
static void initCursorMap() {
g_MouseCursors[ImGuiMouseCursor_Arrow] = CursorType::Arrow;
g_MouseCursors[ImGuiMouseCursor_TextInput] = CursorType::IBeam;
g_MouseCursors[ImGuiMouseCursor_ResizeAll] = CursorType::ArrowDrag;
g_MouseCursors[ImGuiMouseCursor_ResizeNS] = CursorType::SizeNS;
g_MouseCursors[ImGuiMouseCursor_ResizeEW] = CursorType::SizeWE;
g_MouseCursors[ImGuiMouseCursor_ResizeNESW] = CursorType::SizeNESW;
g_MouseCursors[ImGuiMouseCursor_ResizeNWSE] = CursorType::SizeNWSE;
g_MouseCursors[ImGuiMouseCursor_Hand] = CursorType::Deny;
}
void initInputs() {
// Setup back-end capabilities flags
ImGuiIO& io = ImGui::GetIO();
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor
// GetMouseCursor()
// values (optional)
io.BackendFlags |=
ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos
// requests (optional, rarely used)
io.BackendPlatformName = "imgui_impl_bsf";
// Keyboard mapping. ImGui will use those indices to peek into the
// io.KeysDown[] array.
io.KeyMap[ImGuiKey_Tab] = BC_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = BC_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = BC_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = BC_UP;
io.KeyMap[ImGuiKey_DownArrow] = BC_DOWN;
io.KeyMap[ImGuiKey_PageUp] = BC_PGUP;
io.KeyMap[ImGuiKey_PageDown] = BC_PGDOWN;
io.KeyMap[ImGuiKey_Home] = BC_HOME;
io.KeyMap[ImGuiKey_End] = BC_END;
io.KeyMap[ImGuiKey_Insert] = BC_INSERT;
io.KeyMap[ImGuiKey_Delete] = BC_DELETE;
io.KeyMap[ImGuiKey_Backspace] = BC_BACK;
io.KeyMap[ImGuiKey_Space] = BC_SPACE;
io.KeyMap[ImGuiKey_Enter] = BC_RETURN;
io.KeyMap[ImGuiKey_Escape] = BC_ESCAPE;
io.KeyMap[ImGuiKey_A] = BC_A;
io.KeyMap[ImGuiKey_C] = BC_C;
io.KeyMap[ImGuiKey_V] = BC_V;
io.KeyMap[ImGuiKey_X] = BC_X;
io.KeyMap[ImGuiKey_Y] = BC_Y;
io.KeyMap[ImGuiKey_Z] = BC_Z;
io.SetClipboardTextFn = ImGui_ImplBsf_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplBsf_GetClipboardText;
initCursorMap();
connectInputs();
}
bool initImgui() {
initInputs();
updateImguiInputs();
ImGui::NewFrame();
// make empty render.
ImGui::Render();
ImGui::NewFrame();
ImGuizmo::BeginFrame();
return true;
}
static void ImGui_ImplBsf_UpdateMouseCursor() {
ImGuiIO& io = ImGui::GetIO();
if ((io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)) return;
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (imgui_cursor == ImGuiMouseCursor_None || io.MouseDrawCursor) {
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
gCursor().hide();
} else {
// Show OS mouse cursor
gCursor().setCursor(g_MouseCursors[imgui_cursor]);
gCursor().show();
}
// kinda a hack to copy our local mouswheel to the io
// at a specific time instead of as part of event
// since it keeps getting reset between frames...
io.MouseWheel = gMouseWheel;
gMouseWheel = 0.f;
}
static HEvent g_OnPointerMovedConn;
static HEvent g_OnPointerPressedConn;
static HEvent g_OnPointerReleasedConn;
static HEvent g_OnPointerDoubleClick;
static HEvent g_OnTextInputConn;
static HEvent g_OnButtonUp;
static HEvent g_OnButtonDown;
void onPointerMoved(const PointerEvent& event) {
ImGuiIO& io = ImGui::GetIO();
io.MousePos.x = event.screenPos.x - displayLeft;
io.MousePos.y = event.screenPos.y - displayTop;
if (event.mouseWheelScrollAmount > 0) {
gMouseWheel += 1;
} else if (event.mouseWheelScrollAmount < 0) {
gMouseWheel -= 1;
}
}
void onPointerPressed(const PointerEvent& event) {
ImGuiIO& io = ImGui::GetIO();
io.MouseDown[0] = event.buttonStates[0];
io.MouseDown[1] = event.buttonStates[1];
io.MouseDown[2] = event.buttonStates[2];
}
void onPointerReleased(const PointerEvent& event) {
ImGuiIO& io = ImGui::GetIO();
io.MouseDown[0] = event.buttonStates[0];
io.MouseDown[1] = event.buttonStates[1];
io.MouseDown[2] = event.buttonStates[2];
}
void onPointerDoubleClick(const PointerEvent& event) {
// doesn't seem to be necessary to track, since imgui has its own logic for
// identifying double-clicks I think.
}
void onCharInput(const TextInputEvent& event) {
// io.KeysDown[]
ImGuiIO& io = ImGui::GetIO();
io.AddInputCharacter(event.textChar);
}
void onButtonUp(const ButtonEvent& event) {
ImGuiIO& io = ImGui::GetIO();
if (!event.isKeyboard()) return;
if (event.isUsed()) return;
ButtonCode key = event.buttonCode;
IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown));
io.KeysDown[key] = false;
if(event.buttonCode == BC_LSHIFT || event.buttonCode == BC_RSHIFT) {
io.KeyShift = false;
}
if(event.buttonCode == BC_LCONTROL || event.buttonCode == BC_RCONTROL) {
io.KeyCtrl = false;
}
}
void onButtonDown(const ButtonEvent& event) {
ImGuiIO& io = ImGui::GetIO();
if (!event.isKeyboard()) return;
if (event.isUsed()) return;
ButtonCode key = event.buttonCode;
IM_ASSERT(key >= 0 && key < IM_ARRAYSIZE(io.KeysDown));
io.KeysDown[key] = true;
if(event.buttonCode == BC_LSHIFT || event.buttonCode == BC_RSHIFT) {
io.KeyShift = true;
}
if(event.buttonCode == BC_LCONTROL || event.buttonCode == BC_RCONTROL) {
io.KeyCtrl = true;
}
}
void disconnectImgui() {
g_OnPointerMovedConn.disconnect();
g_OnPointerPressedConn.disconnect();
g_OnPointerReleasedConn.disconnect();
g_OnPointerDoubleClick.disconnect();
g_OnTextInputConn.disconnect();
g_OnButtonUp.disconnect();
g_OnButtonDown.disconnect();
}
void connectInputs() {
g_OnPointerMovedConn = gInput().onPointerMoved.connect(&onPointerMoved);
g_OnPointerPressedConn = gInput().onPointerPressed.connect(&onPointerPressed);
g_OnPointerReleasedConn =
gInput().onPointerReleased.connect(&onPointerReleased);
g_OnPointerDoubleClick =
gInput().onPointerDoubleClick.connect(&onPointerDoubleClick);
g_OnTextInputConn = gInput().onCharInput.connect(&onCharInput);
g_OnButtonUp = gInput().onButtonUp.connect(&onButtonUp);
g_OnButtonDown = gInput().onButtonDown.connect(&onButtonDown);
}
void updateImguiInputs() {
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.Fonts->IsBuilt() &&
"Font atlas not built! It is generally built by the renderer "
"back-end. Missing call to renderer _NewFrame() function? e.g. "
"ImGui_ImplOpenGL3_NewFrame().");
int w, h;
int display_w, display_h;
SPtr<RenderWindow> primaryWindow = gCoreApplication().getPrimaryWindow();
const auto& properties = primaryWindow->getProperties();
w = properties.width;
h = properties.height;
// get frame buffer size ?
display_w = properties.width;
display_h = properties.height;
displayLeft = properties.left;
displayTop = properties.top;
io.DisplaySize = ImVec2((float)w, (float)h);
// update imguizmo's rectangle reference.
ImGuizmo::SetRect(0, 0, io.DisplaySize.x, io.DisplaySize.y);
if (w > 0 && h > 0)
io.DisplayFramebufferScale =
ImVec2((float)display_w / w, (float)display_h / h);
float current_time = gTime().getTime();
// std::cout << "current time " << current_time << " " << g_Time << std::endl;
io.DeltaTime =
g_Time > 0.0 ? (current_time - g_Time) : (1.0f / 60.0f);
if (io.DeltaTime == 0.0) io.DeltaTime = 1.f / 60.f;
g_Time = current_time;
ImGui_ImplBsf_UpdateMouseCursor();
}
} // namespace bs | 31.322695 | 80 | 0.714367 | [
"render"
] |
7894c952151ae42f6b90ebfd5030b4c0c08814c2 | 6,776 | cpp | C++ | src/QJsonRpc/JsonRpcServer.cpp | BitcoinNero/REPO1 | dfa3e667bfd4b8f051173b2c113ab51095f54212 | [
"MIT"
] | null | null | null | src/QJsonRpc/JsonRpcServer.cpp | BitcoinNero/REPO1 | dfa3e667bfd4b8f051173b2c113ab51095f54212 | [
"MIT"
] | null | null | null | src/QJsonRpc/JsonRpcServer.cpp | BitcoinNero/REPO1 | dfa3e667bfd4b8f051173b2c113ab51095f54212 | [
"MIT"
] | null | null | null | // Copyright (c) 2015-2017, The Bytecoin developers
//
// This file is part of Bytecoin.
//
// Bytecoin is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Bytecoin 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 Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#include <QJsonArray>
#include <QJsonParseError>
#include <QTcpSocket>
#include "QTextStream"
#include "JsonRpcServer.h"
#include "JsonRpcNotification.h"
#include "JsonRpcObjectFactory.h"
#include "JsonRpcResponse.h"
#include "JsonRpcRequest.h"
namespace QJsonRpc {
JsonRpcServer::JsonRpcServer(QObject* _parent) : QTcpServer(_parent), m_handler(nullptr) {
connect(this, &JsonRpcServer::acceptError, this, &JsonRpcServer::onAcceptError);
connect(this, &JsonRpcServer::newConnection, this, &JsonRpcServer::onNewConnection);
}
JsonRpcServer::~JsonRpcServer() {
}
void JsonRpcServer::setHandler(QObject* _jsonRpcHandler) {
m_handler = _jsonRpcHandler;
}
void JsonRpcServer::sendNotification(const JsonRpcNotification& _notification) {
Q_ASSERT(_notification.isValid());
QList<QTcpSocket*> clients = findChildren<QTcpSocket*>();
for (QTcpSocket* socket : clients) {
sendObject(socket, _notification);
}
}
void JsonRpcServer::onAcceptError(QAbstractSocket::SocketError _socketError) {
}
void JsonRpcServer::onNewConnection() {
QTcpSocket* socket = nextPendingConnection();
while (socket != nullptr) {
qDebug("[JsonRpcServer] New connection from %s", qPrintable(socket->peerAddress().toString()));
connect(socket, &QTcpSocket::disconnected, this, &JsonRpcServer::onSocketDisconneced);
connect(socket, static_cast<void(QTcpSocket::*)(QAbstractSocket::SocketError)>(&QTcpSocket::error),
this, &JsonRpcServer::onSocketError);
connect(socket, &QTcpSocket::readyRead, this, &JsonRpcServer::onSocketReadyRead);
socket = nextPendingConnection();
}
}
void JsonRpcServer::onSocketDisconneced() {
qDebug("[JsonRpcServer] Connection from %s closed", qPrintable(reinterpret_cast<QTcpSocket*>(sender())->peerAddress().toString()));
sender()->deleteLater();
}
void JsonRpcServer::onSocketError(QAbstractSocket::SocketError _socketError) {
QTcpSocket* socket = reinterpret_cast<QTcpSocket*>(sender());
qWarning("[JsonRpcServer] Connection error: %s", qPrintable(socket->errorString()));
sender()->deleteLater();
}
void JsonRpcServer::onSocketReadyRead() {
Q_ASSERT(m_handler != nullptr);
QTcpSocket* socket = reinterpret_cast<QTcpSocket*>(sender());
QTextStream readStream(socket);
while (!readStream.atEnd()) {
QByteArray data = readStream.readLine().toUtf8();
QJsonParseError parseError;
QJsonDocument jsonDocument = QJsonDocument::fromJson(data, &parseError);
if (parseError.error != QJsonParseError::NoError) {
sendError(socket, JsonRpcObject::JSON_RPC_PARSE_ERROR, JsonRpcObject::JSON_RPC_PARSE_ERROR_MESSAGE, parseError.errorString());
continue;
}
if (jsonDocument.isArray()) {
QJsonArray requestArray = jsonDocument.array();
if (requestArray.isEmpty()) {
sendError(socket, JsonRpcObject::JSON_RPC_INVALID_REQUEST_ERROR, JsonRpcObject::JSON_RPC_INVALID_REQUEST_ERROR_MESSAGE, QString());
continue;
}
QJsonArray responseArray;
for (const QJsonValue& request : requestArray) {
QJsonValue responseJsonValue = processJsonValue(request);
if (!responseJsonValue.isNull()) {
responseArray.append(responseJsonValue);
}
}
if (!responseArray.isEmpty()) {
sendJson(socket, responseArray);
}
} else if (jsonDocument.isObject()) {
QJsonValue responseJsonValue = processJsonValue(jsonDocument.object());
if (!responseJsonValue.isNull()) {
sendJson(socket, responseJsonValue);
}
}
}
}
QJsonValue JsonRpcServer::processJsonValue(const QJsonValue& _request) {
int errorCode = 0;
QString errorString;
QString errorData;
QScopedPointer<JsonRpcObject> jsonRpcObject(JsonRpcObjectFactory::createJsonRpcObject(_request, errorCode, errorString, errorData));
if (jsonRpcObject.isNull()) {
JsonRpcResponse errorResponse;
errorResponse.setError(errorCode, errorString, errorData);
return errorResponse.toJsonObject();
}
if (jsonRpcObject->isRequest()) {
const JsonRpcRequest& request = static_cast<JsonRpcRequest&>(*jsonRpcObject);
JsonRpcResponse response;
response.setId(request.getId());
qDebug("[JsonRpcServer] Invoking method: %s", qPrintable(request.getMethod()));
if (!QMetaObject::invokeMethod(m_handler, request.getMethod().toUtf8().constData(), Qt::DirectConnection,
Q_ARG(QJsonRpc::JsonRpcRequest, request), Q_RETURN_ARG(QJsonRpc::JsonRpcResponse&, response))) {
response.setError(JsonRpcObject::JSON_RPC_METHOD_NOT_FOUND_ERROR, JsonRpcObject::JSON_RPC_METHOD_NOT_FOUND_ERROR_MESSAGE,
QVariant());
return response.toJsonObject();
}
Q_ASSERT(response.isValid());
return response.toJsonObject();
} else if (jsonRpcObject->isNotification()) {
const JsonRpcNotification& notification = static_cast<JsonRpcNotification&>(*jsonRpcObject);
QMetaObject::invokeMethod(m_handler, notification.getMethod().toUtf8().constData(), Qt::DirectConnection,
Q_ARG(QJsonRpc::JsonRpcNotification, notification));
}
return QJsonValue();
}
void JsonRpcServer::sendError(QTcpSocket* _socket, int _errorCode, const QString& _errorMessage, const QString& _errorData) {
JsonRpcResponse errorResponse;
errorResponse.setId(QString::null);
errorResponse.setError(_errorCode, _errorMessage, _errorData);
sendObject(_socket, errorResponse);
}
void JsonRpcServer::sendObject(QTcpSocket* _socket, const JsonRpcObject& _object) {
Q_ASSERT(_object.isValid());
Q_ASSERT(_socket != nullptr);
QTextStream writeStream(_socket);
writeStream << _object.toString() << endl;
}
void JsonRpcServer::sendJson(QTcpSocket* _socket, const QJsonValue& _jsonValue) {
Q_ASSERT(_socket != nullptr);
QByteArray data;
if (_jsonValue.isArray()) {
data = QJsonDocument(_jsonValue.toArray()).toJson(QJsonDocument::Compact);
} else if (_jsonValue.isObject()) {
data = QJsonDocument(_jsonValue.toObject()).toJson(QJsonDocument::Compact);
}
QTextStream writeStream(_socket);
writeStream << data << endl;
}
}
| 37.644444 | 139 | 0.74085 | [
"object"
] |
7898f3097ca4e5d0e262b2f322f1bfb1ac2d7d44 | 752 | cpp | C++ | project/source/components/Light.cpp | zeroZshadow/rehover | 5219658b9877a9ea032a588aa95a6881ac37e92e | [
"Zlib",
"CC-BY-4.0",
"MIT"
] | 12 | 2017-12-01T17:39:27.000Z | 2021-06-24T10:46:38.000Z | project/source/components/Light.cpp | hoverguys/rehover | 5219658b9877a9ea032a588aa95a6881ac37e92e | [
"Zlib",
"CC-BY-4.0",
"MIT"
] | 18 | 2017-11-25T20:30:44.000Z | 2020-05-19T05:37:12.000Z | project/source/components/Light.cpp | zeroZshadow/rehover | 5219658b9877a9ea032a588aa95a6881ac37e92e | [
"Zlib",
"CC-BY-4.0",
"MIT"
] | 1 | 2017-11-15T10:41:15.000Z | 2017-11-15T10:41:15.000Z | #include "Light.h"
namespace Components {
void Light::Bind(unsigned short slot) {
GX_LoadLightObj(&lightobj, slot);
}
void PointLight::Setup(const Matrix& view, const Transform& transform) {
Vector pos = view.Multiply(transform.position);
GX_InitLightColor(&lightobj, color);
GX_InitLightPosv(&lightobj, &pos);
}
void DirectionalLight::Setup(const Matrix& view, const Transform& transform) {
Vector dir = view.MultiplySR(transform.forward);
GX_InitLightSpot(&lightobj, 180.0, GX_SP_OFF);
GX_InitSpecularDirv(&lightobj, &dir);
GX_InitLightDistAttn(&lightobj, 1, 1, GX_DA_OFF);
GX_InitLightAttn(&lightobj, 1, 0, 0, 1, 0.1, 0);
GX_InitLightColor(&lightobj, color);
GX_InitLightShininess(&lightobj, shininess);
}
} // namespace Components | 27.851852 | 78 | 0.753989 | [
"vector",
"transform"
] |
789badfd6aae289eb420308f1bfda182bce95c8f | 13,675 | cpp | C++ | vireo/scala/jni/vireo/mux.cpp | shahzadlone/vireo | 73e7176d0255a9506b009c9ab8cc532ecd86e98c | [
"MIT"
] | 890 | 2017-12-15T17:55:42.000Z | 2022-03-27T07:46:49.000Z | vireo/scala/jni/vireo/mux.cpp | shahzadlone/vireo | 73e7176d0255a9506b009c9ab8cc532ecd86e98c | [
"MIT"
] | 29 | 2017-12-16T21:49:08.000Z | 2021-09-08T23:04:10.000Z | vireo/scala/jni/vireo/mux.cpp | shahzadlone/vireo | 73e7176d0255a9506b009c9ab8cc532ecd86e98c | [
"MIT"
] | 88 | 2017-12-15T19:29:49.000Z | 2022-03-21T00:59:29.000Z | /*
* MIT License
*
* Copyright (c) 2017 Twitter
*
* 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 <fstream>
#include <mutex>
#include "vireo/base_h.h"
#include "vireo/base_cpp.h"
#include "vireo/common/data.h"
#include "vireo/common/path.h"
#include "vireo/error/error.h"
#include "vireo/mux/mp2ts.h"
#include "vireo/mux/mp4.h"
#include "vireo/mux/webm.h"
#include "vireo/util/util.h"
#include "vireo/scala/jni/common/jni.h"
#include "vireo/scala/jni/vireo/mux.h"
#include "vireo/scala/jni/vireo/util.h"
using std::lock_guard;
using std::mutex;
using std::ofstream;
using namespace vireo;
// MP2TS Implementation
struct _JNIMP2TSEncodeStruct : public jni::Struct<common::Data32> {
unique_ptr<mux::MP2TS> encoder;
functional::Audio<encode::Sample> audio;
functional::Video<encode::Sample> video;
functional::Caption<encode::Sample> caption;
};
void JNICALL Java_com_twitter_vireo_mux_jni_MP2TS_jniInit(JNIEnv* env, jobject mp2ts_obj, jobject audio_obj, jobject video_obj, jobject caption_obj) {
jni::ExceptionHandler::SafeExecuteFunction(env, [&] {
auto jni_mp2ts = jni::Wrap(env, mp2ts_obj);
auto jni = new _JNIMP2TSEncodeStruct();
jni_mp2ts.set<jlong>("jni", (jlong)jni);
auto jni_audio = jni::Wrap(env, audio_obj);
auto audio_settings_obj = jni_audio.get("settings", "Ljava/lang/Object;");
auto audio_settings = audio_settings_obj ? jni::createAudioSettings(env, audio_settings_obj) : settings::Audio::None;
jni->audio = functional::Audio<encode::Sample>([env, jni, jni_audio](uint32_t index) {
jni::LocalFrame frame(env);
return jni::createFunc<encode::Sample>(env, jni_audio.call<jobject>("apply", "(I)Ljava/lang/Object;", (jint)index))();
}, (uint32_t)jni_audio.get<jint>("a"), (uint32_t)jni_audio.get<jint>("b"), audio_settings);
auto jni_video = jni::Wrap(env, video_obj);
auto video_settings_obj = jni_video.get("settings", "Ljava/lang/Object;");
auto video_settings = video_settings_obj ? jni::createVideoSettings(env, video_settings_obj) : settings::Video::None;
jni->video = functional::Video<encode::Sample>([env, jni, jni_video](uint32_t index) {
jni::LocalFrame frame(env);
return jni::createFunc<encode::Sample>(env, jni_video.call<jobject>("apply", "(I)Ljava/lang/Object;", (jint)index))();
}, (uint32_t)jni_video.get<jint>("a"), (uint32_t)jni_video.get<jint>("b"), video_settings);
auto jni_caption = jni::Wrap(env, caption_obj);
auto caption_settings_obj = jni_caption.get("settings", "Ljava/lang/Object;");
auto caption_settings = caption_settings_obj ? jni::createCaptionSettings(env, caption_settings_obj) : settings::Caption::None;
jni->caption = functional::Caption<encode::Sample>([env, jni, jni_caption](uint32_t index) {
jni::LocalFrame frame(env);
return jni::createFunc<encode::Sample>(env, jni_caption.call<jobject>("apply", "(I)Ljava/lang/Object;", (jint)index))();
}, (uint32_t)jni_caption.get<jint>("a"), (uint32_t)jni_caption.get<jint>("b"), caption_settings);
}, [env, mp2ts_obj] {
Java_com_twitter_vireo_mux_jni_MP2TS_jniClose(env, mp2ts_obj);
});
}
void JNICALL Java_com_twitter_vireo_mux_jni_MP2TS_jniClose(JNIEnv* env, jobject mp2ts_obj) {
jni::ExceptionHandler::SafeExecuteFunction(env, [&] {
jni::Wrap jni_mp2ts(env, mp2ts_obj);
auto jni = (_JNIMP2TSEncodeStruct*)jni_mp2ts.get<jlong>("jni");
delete jni;
jni_mp2ts.set<jlong>("jni", 0);
});
}
static void _CreateMP2TSEncoder(JNIEnv* env, jobject mp2ts_obj) {
jni::Wrap jni_mp2ts(env, mp2ts_obj);
auto jni = (_JNIMP2TSEncodeStruct*)jni_mp2ts.get<jlong>("jni");
CHECK(jni && !jni->encoder);
jni->encoder.reset(new mux::MP2TS(jni->audio, jni->video, jni->caption));
}
jobject JNICALL Java_com_twitter_vireo_mux_jni_MP2TS_encode(JNIEnv* env, jobject mp2ts_obj, jlong _jni) {
return jni::ExceptionHandler::SafeExecuteFunctionAndReturn<jobject>(env, [&] {
auto jni = (_JNIMP2TSEncodeStruct*)_jni;
CHECK(jni);
if (!jni->encoder) {
_CreateMP2TSEncoder(env, mp2ts_obj);
}
auto data = (*jni->encoder)();
jobject byte_buffer_obj = env->NewDirectByteBuffer((void*)(data.data() + data.a()), (jlong)data.count());
auto jni_byte_data = jni::Wrap(env, "com/twitter/vireo/common/ByteData", "(Ljava/nio/ByteBuffer;)V", byte_buffer_obj);
jni->add_buffer_ref(move(data), jni_byte_data);
return *jni_byte_data;
}, NULL);
}
// MP4 Implementation
struct _JNIMP4EncodeStruct : public jni::Struct<common::Data32> {
unique_ptr<mux::MP4> encoder;
functional::Audio<encode::Sample> audio;
functional::Video<encode::Sample> video;
functional::Caption<encode::Sample> caption;
vector<common::EditBox> edit_boxes;
FileFormat file_format;
};
void JNICALL Java_com_twitter_vireo_mux_jni_MP4_jniInit(JNIEnv* env, jobject mp4_obj, jobject audio_obj, jobject video_obj, jobject caption_obj, jobject edit_boxes_obj, jbyte file_format) {
jni::ExceptionHandler::SafeExecuteFunction(env, [&] {
auto jni_mp4 = jni::Wrap(env, mp4_obj);
auto jni = new _JNIMP4EncodeStruct();
jni_mp4.set<jlong>("jni", (jlong)jni);
auto jni_audio = jni::Wrap(env, audio_obj);
const uint32_t audio_a = (uint32_t)jni_audio.get<jint>("a");
const uint32_t audio_b = (uint32_t)jni_audio.get<jint>("b");
auto audio_settings_obj = jni_audio.get("settings", "Ljava/lang/Object;");
auto audio_settings = audio_settings_obj ? jni::createAudioSettings(env, audio_settings_obj) : settings::Audio::None;
jni->audio = functional::Audio<encode::Sample>([env, jni, jni_audio = move(jni_audio)](uint32_t index) {
jni::LocalFrame frame(env);
return jni::createFunc<encode::Sample>(env, jni_audio.call<jobject>("apply", "(I)Ljava/lang/Object;", (jint)index))();
}, audio_a, audio_b, audio_settings);
auto jni_video = jni::Wrap(env, video_obj);
const uint32_t video_a = (uint32_t)jni_video.get<jint>("a");
const uint32_t video_b = (uint32_t)jni_video.get<jint>("b");
auto video_settings_obj = jni_video.get("settings", "Ljava/lang/Object;");
auto video_settings = video_settings_obj ? jni::createVideoSettings(env, video_settings_obj) : settings::Video::None;
jni->video = functional::Video<encode::Sample>([env, jni, jni_video = move(jni_video)](uint32_t index) {
jni::LocalFrame frame(env);
return jni::createFunc<encode::Sample>(env, jni_video.call<jobject>("apply", "(I)Ljava/lang/Object;", (jint)index))();
}, video_a, video_b, video_settings);
auto jni_caption = jni::Wrap(env, caption_obj);
const uint32_t caption_a = (uint32_t)jni_caption.get<jint>("a");
const uint32_t caption_b = (uint32_t)jni_caption.get<jint>("b");
auto caption_settings_obj = jni_caption.get("settings", "Ljava/lang/Object;");
auto caption_settings = caption_settings_obj ? jni::createCaptionSettings(env, caption_settings_obj) : settings::Caption::None;
jni->caption = functional::Caption<encode::Sample>([env, jni, jni_caption = move(jni_caption)](uint32_t index) {
jni::LocalFrame frame(env);
return jni::createFunc<encode::Sample>(env, jni_caption.call<jobject>("apply", "(I)Ljava/lang/Object;", (jint)index))();
}, caption_a, caption_b, caption_settings);
jni->edit_boxes = jni::createVectorFromSeq<common::EditBox>(env, edit_boxes_obj, function<common::EditBox(jobject)>([env](jobject edit_box_obj) -> common::EditBox {
auto jni_edit_box = jni::Wrap(env, edit_box_obj);
return common::EditBox((int64_t)jni_edit_box.get<jlong>("startPts"),
(uint64_t)jni_edit_box.get<jlong>("durationPts"),
1.0f,
(SampleType)jni_edit_box.get<jbyte>("sampleType"));
}));
jni->file_format = (FileFormat)file_format;
}, [env, mp4_obj] {
Java_com_twitter_vireo_mux_jni_MP4_jniClose(env, mp4_obj);
});
}
void JNICALL Java_com_twitter_vireo_mux_jni_MP4_jniClose(JNIEnv* env, jobject mp4_obj) {
jni::ExceptionHandler::SafeExecuteFunction(env, [&] {
jni::Wrap jni_mp4(env, mp4_obj);
auto jni = (_JNIMP4EncodeStruct*)jni_mp4.get<jlong>("jni");
delete jni;
jni_mp4.set<jlong>("jni", 0);
});
}
static void _CreateMP4Encoder(JNIEnv* env, jobject mp4_obj) {
jni::Wrap jni_mp4(env, mp4_obj);
auto jni = (_JNIMP4EncodeStruct*)jni_mp4.get<jlong>("jni");
CHECK(jni && !jni->encoder);
jni->encoder.reset(new mux::MP4(jni->audio, jni->video, jni->caption, jni->edit_boxes, jni->file_format));
}
jobject JNICALL Java_com_twitter_vireo_mux_jni_MP4_encode(JNIEnv* env, jobject mp4_obj, jlong _jni, jbyte file_format) {
return jni::ExceptionHandler::SafeExecuteFunctionAndReturn<jobject>(env, [&] {
auto jni = (_JNIMP4EncodeStruct*)_jni;
CHECK(jni);
if (!jni->encoder) {
_CreateMP4Encoder(env, mp4_obj);
}
auto data = (*jni->encoder)((FileFormat)file_format);
jobject byte_buffer_obj = env->NewDirectByteBuffer((void*)(data.data() + data.a()), (jlong)data.count());
auto jni_byte_data = jni::Wrap(env, "com/twitter/vireo/common/ByteData", "(Ljava/nio/ByteBuffer;)V", byte_buffer_obj);
jni->add_buffer_ref(move(data), jni_byte_data);
return *jni_byte_data;
}, NULL);
}
// WebM Implementation
struct _JNIWebMEncodeStruct : public jni::Struct<common::Data32> {
unique_ptr<mux::WebM> encoder;
functional::Audio<encode::Sample> audio;
functional::Video<encode::Sample> video;
};
void JNICALL Java_com_twitter_vireo_mux_jni_WebM_jniInit(JNIEnv* env, jobject webm_obj, jobject audio_obj, jobject video_obj) {
jni::ExceptionHandler::SafeExecuteFunction(env, [&] {
auto jni_webm = jni::Wrap(env, webm_obj);
auto jni = new _JNIWebMEncodeStruct();
jni_webm.set<jlong>("jni", (jlong)jni);
auto jni_audio = jni::Wrap(env, audio_obj);
const uint32_t audio_a = (uint32_t)jni_audio.get<jint>("a");
const uint32_t audio_b = (uint32_t)jni_audio.get<jint>("b");
auto audio_settings_obj = jni_audio.get("settings", "Ljava/lang/Object;");
auto audio_settings = audio_settings_obj ? jni::createAudioSettings(env, audio_settings_obj) : settings::Audio::None;
const uint32_t audio_count = (uint32_t)jni_audio.get<jint>("b");
jni->audio = functional::Audio<encode::Sample>([env, jni, audio_count, jni_audio = move(jni_audio)](uint32_t index) {
jni::LocalFrame frame(env);
return jni::createFunc<encode::Sample>(env, jni_audio.call<jobject>("apply", "(I)Ljava/lang/Object;", (jint)index))();
}, audio_a, audio_b, audio_settings);
auto jni_video = jni::Wrap(env, video_obj);
const uint32_t video_a = (uint32_t)jni_video.get<jint>("a");
const uint32_t video_b = (uint32_t)jni_video.get<jint>("b");
auto video_settings_obj = jni_video.get("settings", "Ljava/lang/Object;");
auto video_settings = video_settings_obj ? jni::createVideoSettings(env, video_settings_obj) : settings::Video::None;
const uint32_t video_count = (uint32_t)jni_video.get<jint>("b");
jni->video = functional::Video<encode::Sample>([env, jni, video_count, jni_video = move(jni_video)](uint32_t index) {
jni::LocalFrame frame(env);
return jni::createFunc<encode::Sample>(env, jni_video.call<jobject>("apply", "(I)Ljava/lang/Object;", (jint)index))();
}, video_a, video_b, video_settings);
}, [env, webm_obj] {
Java_com_twitter_vireo_mux_jni_WebM_jniClose(env, webm_obj);
});
}
void JNICALL Java_com_twitter_vireo_mux_jni_WebM_jniClose(JNIEnv* env, jobject webm_obj) {
jni::ExceptionHandler::SafeExecuteFunction(env, [&] {
jni::Wrap jni_webm(env, webm_obj);
auto jni = (_JNIWebMEncodeStruct*)jni_webm.get<jlong>("jni");
delete jni;
jni_webm.set<jlong>("jni", 0);
});
}
static void _CreateWebMEncoder(JNIEnv* env, jobject webm_obj) {
jni::Wrap jni_webm(env, webm_obj);
auto jni = (_JNIWebMEncodeStruct*)jni_webm.get<jlong>("jni");
CHECK(jni && !jni->encoder);
jni->encoder.reset(new mux::WebM(jni->audio, jni->video));
}
jobject JNICALL Java_com_twitter_vireo_mux_jni_WebM_encode(JNIEnv* env, jobject webm_obj, jlong _jni) {
return jni::ExceptionHandler::SafeExecuteFunctionAndReturn<jobject>(env, [&] {
auto jni = (_JNIWebMEncodeStruct*)_jni;
CHECK(jni);
if (!jni->encoder) {
_CreateWebMEncoder(env, webm_obj);
}
auto data = (*jni->encoder)();
jobject byte_buffer_obj = env->NewDirectByteBuffer((void*)(data.data() + data.a()), (jlong)data.count());
auto jni_byte_data = jni::Wrap(env, "com/twitter/vireo/common/ByteData", "(Ljava/nio/ByteBuffer;)V", byte_buffer_obj);
jni->add_buffer_ref(move(data), jni_byte_data);
return *jni_byte_data;
}, NULL);
}
| 44.112903 | 189 | 0.712102 | [
"object",
"vector"
] |
789fb59f3cb09aaf972309d87312629aa841cf31 | 5,264 | cpp | C++ | MEK_Engine/src/MEK/Application.cpp | mekot16/MEK_Engine | 9a246ec380b9e0f481d7c5958363dfbe9352bbd5 | [
"Apache-2.0"
] | null | null | null | MEK_Engine/src/MEK/Application.cpp | mekot16/MEK_Engine | 9a246ec380b9e0f481d7c5958363dfbe9352bbd5 | [
"Apache-2.0"
] | null | null | null | MEK_Engine/src/MEK/Application.cpp | mekot16/MEK_Engine | 9a246ec380b9e0f481d7c5958363dfbe9352bbd5 | [
"Apache-2.0"
] | null | null | null | #include "mekpch.h"
#include "Application.h"
#include "Input.h"
#include "MEK/Renderer/Renderer.h"
namespace MEK {
Application* Application::s_Instance = nullptr;
Application::Application()
{
MEK_CORE_ASSERT(!s_Instance, "Application already exists!");
s_Instance = this;
m_Window = std::unique_ptr<Window>(Window::Create());
// this is binding the OnEvent function defined in Application to be
// run as the callback function when an event happens in the window
m_Window->SetEventCallback(MEK_BIND_EVENT_FN(Application::OnEvent));
// don't like using 'new' (see unique_ptr and shared_ptr)
m_ImGuiLayer = new ImGuiLayer();
PushOverlay(m_ImGuiLayer);
// Drawing a triangle on screen
// Vertex Array
m_TriangleVertexArray.reset(VertexArray::Create());
float triangleVertices[3 * 7] = {
-0.5f, -0.5f, 0.0f, 0.8f, 0.3f, 0.8f, 1.0f,
0.5f, -0.5f, 0.0f, 0.7f, 0.7f, 0.2f, 1.0f,
0.0f, 0.5f, 0.0f, 0.2f, 0.7f, 0.9f, 1.0f
};
// Vertex Buffer
std::shared_ptr<VertexBuffer> triangleVB;
triangleVB.reset(VertexBuffer::Create(triangleVertices, sizeof(triangleVertices)));
BufferLayout layout = {
{ ShaderDataType::Float3, "a_Position"},
{ ShaderDataType::Float4, "a_Color"}
};
triangleVB->SetLayout(layout);
// important to do this after layout is created and set
m_TriangleVertexArray->AddVertexBuffer(triangleVB);
// Index Buffer
uint32_t triangleIndices[3] = { 0, 1, 2 };
std::shared_ptr<IndexBuffer> triangleIB;
triangleIB.reset(IndexBuffer::Create(triangleIndices, sizeof(triangleIndices) / sizeof(uint32_t)));
m_TriangleVertexArray->SetIndexBuffer(triangleIB);
// Shader
std::string vertexSrc = R"(
#version 330 core
layout(location = 0) in vec3 a_Position;
layout(location = 1) in vec4 a_Color;
out vec3 v_Position;
out vec4 v_Color;
void main()
{
v_Position = a_Position;
v_Color = a_Color;
gl_Position = vec4(a_Position, 1.0);
}
)";
std::string fragmentSrc = R"(
#version 330 core
layout(location = 0) out vec4 color;
in vec3 v_Position;
in vec4 v_Color;
void main()
{
color = vec4(v_Position * 0.5 + 0.5, 1.0);
color = v_Color;
}
)";
m_TriangleShader.reset(Shader::Create(vertexSrc, fragmentSrc));
// Drawing a square too //
m_SquareVA.reset(VertexArray::Create());
float squareVertices[3 * 4] = {
-0.75f, -0.75f, 0.0f,
0.75f, -0.75f, 0.0f,
0.75f, 0.75f, 0.0f,
-0.75f, 0.75f, 0.0f
};
std::shared_ptr<VertexBuffer> squareVB;
squareVB.reset(VertexBuffer::Create(squareVertices, sizeof(squareVertices)));
// define how the buffer is laid out
squareVB->SetLayout({
{ ShaderDataType::Float3, "a_Position" }
});
// this handles the vertex array
// important to do this after layout is created and set
m_SquareVA->AddVertexBuffer(squareVB);
// Index Buffer
uint32_t squareIndices[6] = { 0, 1, 2, 2, 3, 0 };
std::shared_ptr<IndexBuffer> squareIB;
squareIB.reset(IndexBuffer::Create(squareIndices, sizeof(squareIndices) / sizeof(uint32_t)));
m_SquareVA->SetIndexBuffer(squareIB);
// Shader for rectangle
std::string vertexRectSrc = R"(
#version 330 core
layout(location = 0) in vec3 a_Position;
out vec3 v_Position;
void main()
{
v_Position = a_Position;
gl_Position = vec4(a_Position, 1.0);
}
)";
std::string fragmentRectSrc = R"(
#version 330 core
layout(location = 0) out vec4 color;
in vec3 v_Position;
void main()
{
color = vec4(0.2, 0.3, 0.8, 1.0);
}
)";
m_RectShader.reset(Shader::Create(vertexRectSrc, fragmentRectSrc));
}
Application::~Application()
{
}
void Application::PushLayer(Layer* layer)
{
m_LayerStack.PushLayer(layer);
}
void Application::PushOverlay(Layer* layer)
{
m_LayerStack.PushOverlay(layer);
}
void Application::OnEvent(Event& e)
{
EventDispatcher dispatcher(e);
dispatcher.Dispatch<WindowCloseEvent>(MEK_BIND_EVENT_FN(Application::OnWindowClose));
// Uncomment to log events
//MEK_CORE_TRACE("{0}", e);
// start from top-most layer and iterate downward
// call OnEvent for each layer passed, until event is handled
for (auto it = m_LayerStack.end(); it != m_LayerStack.begin(); )
{
(*--it)->OnEvent(e);
if (e.Handled)
break;
}
}
void Application::Run()
{
while (m_Running)
{
RenderCommand::SetClearColor({ 0.1f, 0.1f, 0.1f, 1 });
RenderCommand::Clear();
//Renderer::BeginScene(camera, lights, environment);
Renderer::BeginScene();
// Can use brackets like this to keep render code organized
{
m_RectShader->Bind();
Renderer::Submit(m_SquareVA);
m_TriangleShader->Bind();
Renderer::Submit(m_TriangleVertexArray);
}
Renderer::EndScene();
// call OnUpdate for all Layers
for (Layer* layer : m_LayerStack)
layer->OnUpdate();
// TODO: this rendering will be done on the render thread
// call OnImGuiRender for all Layers between ImGui's Begin and End
m_ImGuiLayer->Begin();
for (Layer* layer : m_LayerStack)
layer->OnImGuiRender();
m_ImGuiLayer->End();
// call OnUpdate for Window
m_Window->OnUpdate();
}
}
bool Application::OnWindowClose(WindowCloseEvent& e)
{
m_Running = false;
return true;
}
} | 23.605381 | 101 | 0.676102 | [
"render"
] |
a192db0c333adebf59e4cde9fb2801892431a7be | 1,322 | cc | C++ | ppapi/thunk/ppb_view_dev_thunk.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 | ppapi/thunk/ppb_view_dev_thunk.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | ppapi/thunk/ppb_view_dev_thunk.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 (c) 2012 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.
// From dev/ppb_view_dev.idl modified Wed Jan 27 17:10:16 2016.
#include <stdint.h>
#include "base/logging.h"
#include "ppapi/c/dev/ppb_view_dev.h"
#include "ppapi/c/pp_errors.h"
#include "ppapi/shared_impl/tracked_callback.h"
#include "ppapi/thunk/enter.h"
#include "ppapi/thunk/ppapi_thunk_export.h"
#include "ppapi/thunk/ppb_view_api.h"
namespace ppapi {
namespace thunk {
namespace {
float GetDeviceScale(PP_Resource resource) {
VLOG(4) << "PPB_View_Dev::GetDeviceScale()";
EnterResource<PPB_View_API> enter(resource, true);
if (enter.failed())
return 0.0f;
return enter.object()->GetDeviceScale();
}
float GetCSSScale(PP_Resource resource) {
VLOG(4) << "PPB_View_Dev::GetCSSScale()";
EnterResource<PPB_View_API> enter(resource, true);
if (enter.failed())
return 0.0f;
return enter.object()->GetCSSScale();
}
const PPB_View_Dev_0_1 g_ppb_view_dev_thunk_0_1 = {&GetDeviceScale,
&GetCSSScale};
} // namespace
PPAPI_THUNK_EXPORT const PPB_View_Dev_0_1* GetPPB_View_Dev_0_1_Thunk() {
return &g_ppb_view_dev_thunk_0_1;
}
} // namespace thunk
} // namespace ppapi
| 26.979592 | 73 | 0.714826 | [
"object"
] |
a197cf85baf36cea8bbc68ad7e98feeebf1cf397 | 2,511 | hpp | C++ | include/codegen/include/UnityEngine/TestTools/SetUpTearDownCommand_--c.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/TestTools/SetUpTearDownCommand_--c.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/TestTools/SetUpTearDownCommand_--c.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:35 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.TestTools.SetUpTearDownCommand
#include "UnityEngine/TestTools/SetUpTearDownCommand.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<TResult, T>
template<typename TResult, typename T>
class Func_2;
}
// Forward declaring namespace: System::Reflection
namespace System::Reflection {
// Forward declaring type: MethodInfo
class MethodInfo;
}
// Completed forward declares
// Type namespace: UnityEngine.TestTools
namespace UnityEngine::TestTools {
// Autogenerated type: UnityEngine.TestTools.SetUpTearDownCommand/<>c
class SetUpTearDownCommand::$$c : public ::Il2CppObject {
public:
// Get static field: static public readonly UnityEngine.TestTools.SetUpTearDownCommand/<>c <>9
static UnityEngine::TestTools::SetUpTearDownCommand::$$c* _get_$$9();
// Set static field: static public readonly UnityEngine.TestTools.SetUpTearDownCommand/<>c <>9
static void _set_$$9(UnityEngine::TestTools::SetUpTearDownCommand::$$c* value);
// Get static field: static public System.Func`2<System.Reflection.MethodInfo,System.Boolean> <>9__1_0
static System::Func_2<System::Reflection::MethodInfo*, bool>* _get_$$9__1_0();
// Set static field: static public System.Func`2<System.Reflection.MethodInfo,System.Boolean> <>9__1_0
static void _set_$$9__1_0(System::Func_2<System::Reflection::MethodInfo*, bool>* value);
// static private System.Void .cctor()
// Offset: 0xE2C764
static void _cctor();
// System.Boolean <GetMethodsWithAttributeFromFixture>b__1_0(System.Reflection.MethodInfo x)
// Offset: 0xE2C7D4
bool $GetMethodsWithAttributeFromFixture$b__1_0(System::Reflection::MethodInfo* x);
// public System.Void .ctor()
// Offset: 0xE2C7CC
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static SetUpTearDownCommand::$$c* New_ctor();
}; // UnityEngine.TestTools.SetUpTearDownCommand/<>c
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TestTools::SetUpTearDownCommand::$$c*, "UnityEngine.TestTools", "SetUpTearDownCommand/<>c");
#pragma pack(pop)
| 45.654545 | 128 | 0.727599 | [
"object"
] |
a19a9310d185a214937a9f43576806e711213f19 | 3,731 | cpp | C++ | 3_3_Prediction/NaiveBayes/classifier.cpp | Alyxion/Udacity_SelfDrivingCarEngineerNd | 7da27ec7ee86fc65d07c9e1b316088be6975f2d3 | [
"MIT"
] | 7 | 2018-12-27T00:12:50.000Z | 2022-03-29T13:13:42.000Z | 3_3_Prediction/NaiveBayes/classifier.cpp | Alyxion/Udacity_SelfDrivingCarEngineerNd | 7da27ec7ee86fc65d07c9e1b316088be6975f2d3 | [
"MIT"
] | null | null | null | 3_3_Prediction/NaiveBayes/classifier.cpp | Alyxion/Udacity_SelfDrivingCarEngineerNd | 7da27ec7ee86fc65d07c9e1b316088be6975f2d3 | [
"MIT"
] | 8 | 2018-10-03T16:46:39.000Z | 2021-01-11T18:29:42.000Z | #include <iostream>
#include <sstream>
#include <fstream>
#include <math.h>
#include <vector>
#include "classifier.h"
using namespace std;
using Eigen::ArrayXd;
/**
* Initializes GNB
*/
GNB::GNB()
{
for(int actionIndex = 0; actionIndex<actionCount; ++actionIndex)
{
(means[actionIndex] = ArrayXd(4)) << 0,0,0,0;
(sds[actionIndex] = ArrayXd(4)) << 0,0,0,0;
priors[actionIndex] = 0.0;
}
}
GNB::~GNB() {}
void GNB::train(vector<vector<double>> data, vector<string> labels)
{
/*
Trains the classifier with N data points and labels.
INPUTS
data - array of N observations
- Each observation is a tuple with 4 values: s, d,
s_dot and d_dot.
- Example : [
[3.5, 0.1, 5.9, -0.02],
[8.0, -0.3, 3.0, 2.2],
...
]
labels - array of N labels
- Each label is one of "left", "keep", or "right".
*/
//For each label, compute ArrayXd of means, one for each data class (s, d, s_dot, d_dot).
//These will be used later to provide distributions for conditional probabilites.
//Means are stored in an ArrayXd of size 4.
float sizes[actionCount];
for(int i=0; i<actionCount; ++i)
{
sizes[i] = 0;
}
std::vector<int> actions;
//For each label, compute the numerators of the means for each class
//and the total number of data points given with that label.
for (int i=0; i<labels.size(); i++)
{
int action = -1;
int index = 0;
for(auto &cur: possible_labels)
{
if(cur==labels[i])
{
action = index;
break;
}
index++;
}
actions.push_back(action);
means[action] += ArrayXd::Map(data[i].data(), data[i].size()); //conversion of data[i] to ArrayXd
sizes[action] += 1;
}
//Compute the means. Each result is a ArrayXd of means (4 means, one for each class)..
for(int index=0; index<actionCount; ++index)
{
if(sizes[index]!=0)
{
means[index] = means[index]/sizes[index];
}
}
//Begin computation of standard deviations for each class/label combination.
ArrayXd data_point;
//Compute numerators of the standard deviations.
for (int i=0; i<labels.size(); i++)
{
auto action = actions[i];
data_point = ArrayXd::Map(data[i].data(), data[i].size());
sds[action] += (data_point - means[action])*(data_point - means[action]);
}
//compute standard deviations
for(int index=0; index<actionCount; ++index)
{
sds[index] = (sds[index]/sizes[index]).sqrt();
priors[index] = sizes[index]/labels.size();
}
}
string GNB::predict(vector<double> sample)
{
/*
Once trained, this method is called and expected to return
a predicted behavior for the given observation.
INPUTS
observation - a 4 tuple with s, d, s_dot, d_dot.
- Example: [3.5, 0.1, 8.5, -0.2]
OUTPUT
A label representing the best guess of the classifier. Can
be one of "left", "keep" or "right".
"""
# TODO - complete this
*/
//Calculate product of conditional probabilities for each label.
double probabilities[actionCount];
for(int action=0; action<actionCount; ++action)
{
probabilities[action] = 1.0;
for (int i=0; i<4; i++)
{
probabilities[action] *= (1.0/sqrt(2.0 * M_PI * pow(sds[action][i], 2))) * exp(-0.5*pow(sample[i] - means[action][i], 2)/pow(sds[action][i], 2));
}
probabilities[action] *= priors[action];
}
double max = probabilities[0];
double max_index = 0;
for (int i=1; i<actionCount; i++){
if (probabilities[i] > max) {
max = probabilities[i];
max_index = i;
}
}
return this -> possible_labels[max_index];
} | 23.916667 | 154 | 0.598499 | [
"vector"
] |
a19b702938a27dc148c5c4221f957775a148be79 | 74,641 | cc | C++ | test/cctest/test-ast-types.cc | radimkohout/v8-new | f6dc1d17efcc695a6f2dd7bcc50c0c6321747613 | [
"BSD-3-Clause"
] | 5 | 2015-03-04T17:49:04.000Z | 2017-04-17T10:10:13.000Z | test/cctest/test-ast-types.cc | radimkohout/v8-new | f6dc1d17efcc695a6f2dd7bcc50c0c6321747613 | [
"BSD-3-Clause"
] | null | null | null | test/cctest/test-ast-types.cc | radimkohout/v8-new | f6dc1d17efcc695a6f2dd7bcc50c0c6321747613 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <vector>
#include "src/crankshaft/hydrogen-types.h"
#include "src/factory.h"
#include "src/heap/heap.h"
#include "src/isolate.h"
// FIXME(mstarzinger, marja): This is weird, but required because of the missing
// (disallowed) include: src/factory.h -> src/objects-inl.h
#include "src/ast/ast-types.h"
#include "src/objects-inl.h"
// FIXME(mstarzinger, marja): This is weird, but required because of the missing
// (disallowed) include: src/feedback-vector.h ->
// src/feedback-vector-inl.h
#include "src/feedback-vector-inl.h"
#include "test/cctest/ast-types-fuzz.h"
#include "test/cctest/cctest.h"
using namespace v8::internal;
namespace {
// Testing auxiliaries (breaking the Type abstraction).
static bool IsInteger(double x) {
return nearbyint(x) == x && !i::IsMinusZero(x); // Allows for infinities.
}
static bool IsInteger(i::Object* x) {
return x->IsNumber() && IsInteger(x->Number());
}
typedef uint32_t bitset;
struct Tests {
typedef AstTypes::TypeVector::iterator TypeIterator;
typedef AstTypes::MapVector::iterator MapIterator;
typedef AstTypes::ValueVector::iterator ValueIterator;
Isolate* isolate;
HandleScope scope;
Zone zone;
AstTypes T;
Tests()
: isolate(CcTest::InitIsolateOnce()),
scope(isolate),
zone(isolate->allocator(), ZONE_NAME),
T(&zone, isolate, isolate->random_number_generator()) {}
bool IsBitset(AstType* type) { return type->IsBitsetForTesting(); }
bool IsUnion(AstType* type) { return type->IsUnionForTesting(); }
AstBitsetType::bitset AsBitset(AstType* type) {
return type->AsBitsetForTesting();
}
AstUnionType* AsUnion(AstType* type) { return type->AsUnionForTesting(); }
bool Equal(AstType* type1, AstType* type2) {
return type1->Equals(type2) &&
this->IsBitset(type1) == this->IsBitset(type2) &&
this->IsUnion(type1) == this->IsUnion(type2) &&
type1->NumClasses() == type2->NumClasses() &&
type1->NumConstants() == type2->NumConstants() &&
(!this->IsBitset(type1) ||
this->AsBitset(type1) == this->AsBitset(type2)) &&
(!this->IsUnion(type1) ||
this->AsUnion(type1)->LengthForTesting() ==
this->AsUnion(type2)->LengthForTesting());
}
void CheckEqual(AstType* type1, AstType* type2) {
CHECK(Equal(type1, type2));
}
void CheckSub(AstType* type1, AstType* type2) {
CHECK(type1->Is(type2));
CHECK(!type2->Is(type1));
if (this->IsBitset(type1) && this->IsBitset(type2)) {
CHECK(this->AsBitset(type1) != this->AsBitset(type2));
}
}
void CheckSubOrEqual(AstType* type1, AstType* type2) {
CHECK(type1->Is(type2));
if (this->IsBitset(type1) && this->IsBitset(type2)) {
CHECK((this->AsBitset(type1) | this->AsBitset(type2)) ==
this->AsBitset(type2));
}
}
void CheckUnordered(AstType* type1, AstType* type2) {
CHECK(!type1->Is(type2));
CHECK(!type2->Is(type1));
if (this->IsBitset(type1) && this->IsBitset(type2)) {
CHECK(this->AsBitset(type1) != this->AsBitset(type2));
}
}
void CheckOverlap(AstType* type1, AstType* type2) {
CHECK(type1->Maybe(type2));
CHECK(type2->Maybe(type1));
}
void CheckDisjoint(AstType* type1, AstType* type2) {
CHECK(!type1->Is(type2));
CHECK(!type2->Is(type1));
CHECK(!type1->Maybe(type2));
CHECK(!type2->Maybe(type1));
}
void IsSomeType() {
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* t = *it;
CHECK(1 ==
this->IsBitset(t) + t->IsClass() + t->IsConstant() + t->IsRange() +
this->IsUnion(t) + t->IsArray() + t->IsFunction() +
t->IsContext());
}
}
void Bitset() {
// None and Any are bitsets.
CHECK(this->IsBitset(T.None));
CHECK(this->IsBitset(T.Any));
CHECK(bitset(0) == this->AsBitset(T.None));
CHECK(bitset(0xfffffffeu) == this->AsBitset(T.Any));
// Union(T1, T2) is bitset for bitsets T1,T2
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* union12 = T.Union(type1, type2);
CHECK(!(this->IsBitset(type1) && this->IsBitset(type2)) ||
this->IsBitset(union12));
}
}
// Intersect(T1, T2) is bitset for bitsets T1,T2
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* intersect12 = T.Intersect(type1, type2);
CHECK(!(this->IsBitset(type1) && this->IsBitset(type2)) ||
this->IsBitset(intersect12));
}
}
// Union(T1, T2) is bitset if T2 is bitset and T1->Is(T2)
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* union12 = T.Union(type1, type2);
CHECK(!(this->IsBitset(type2) && type1->Is(type2)) ||
this->IsBitset(union12));
}
}
// Union(T1, T2) is bitwise disjunction for bitsets T1,T2
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* union12 = T.Union(type1, type2);
if (this->IsBitset(type1) && this->IsBitset(type2)) {
CHECK((this->AsBitset(type1) | this->AsBitset(type2)) ==
this->AsBitset(union12));
}
}
}
// Intersect(T1, T2) is bitwise conjunction for bitsets T1,T2 (modulo None)
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
if (this->IsBitset(type1) && this->IsBitset(type2)) {
AstType* intersect12 = T.Intersect(type1, type2);
bitset bits = this->AsBitset(type1) & this->AsBitset(type2);
CHECK(bits == this->AsBitset(intersect12));
}
}
}
}
void PointwiseRepresentation() {
// Check we can decompose type into semantics and representation and
// then compose it back to get an equivalent type.
int counter = 0;
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
counter++;
printf("Counter: %i\n", counter);
fflush(stdout);
AstType* type1 = *it1;
AstType* representation = T.Representation(type1);
AstType* semantic = T.Semantic(type1);
AstType* composed = T.Union(representation, semantic);
CHECK(type1->Equals(composed));
}
// Pointwiseness of Union.
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* representation1 = T.Representation(type1);
AstType* semantic1 = T.Semantic(type1);
AstType* representation2 = T.Representation(type2);
AstType* semantic2 = T.Semantic(type2);
AstType* direct_union = T.Union(type1, type2);
AstType* representation_union =
T.Union(representation1, representation2);
AstType* semantic_union = T.Union(semantic1, semantic2);
AstType* composed_union = T.Union(representation_union, semantic_union);
CHECK(direct_union->Equals(composed_union));
}
}
// Pointwiseness of Intersect.
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* representation1 = T.Representation(type1);
AstType* semantic1 = T.Semantic(type1);
AstType* representation2 = T.Representation(type2);
AstType* semantic2 = T.Semantic(type2);
AstType* direct_intersection = T.Intersect(type1, type2);
AstType* representation_intersection =
T.Intersect(representation1, representation2);
AstType* semantic_intersection = T.Intersect(semantic1, semantic2);
AstType* composed_intersection =
T.Union(representation_intersection, semantic_intersection);
CHECK(direct_intersection->Equals(composed_intersection));
}
}
// Pointwiseness of Is.
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* representation1 = T.Representation(type1);
AstType* semantic1 = T.Semantic(type1);
AstType* representation2 = T.Representation(type2);
AstType* semantic2 = T.Semantic(type2);
bool representation_is = representation1->Is(representation2);
bool semantic_is = semantic1->Is(semantic2);
bool direct_is = type1->Is(type2);
CHECK(direct_is == (semantic_is && representation_is));
}
}
}
void Class() {
// Constructor
for (MapIterator mt = T.maps.begin(); mt != T.maps.end(); ++mt) {
Handle<i::Map> map = *mt;
AstType* type = T.Class(map);
CHECK(type->IsClass());
}
// Map attribute
for (MapIterator mt = T.maps.begin(); mt != T.maps.end(); ++mt) {
Handle<i::Map> map = *mt;
AstType* type = T.Class(map);
CHECK(*map == *type->AsClass()->Map());
}
// Functionality & Injectivity: Class(M1) = Class(M2) iff M1 = M2
for (MapIterator mt1 = T.maps.begin(); mt1 != T.maps.end(); ++mt1) {
for (MapIterator mt2 = T.maps.begin(); mt2 != T.maps.end(); ++mt2) {
Handle<i::Map> map1 = *mt1;
Handle<i::Map> map2 = *mt2;
AstType* type1 = T.Class(map1);
AstType* type2 = T.Class(map2);
CHECK(Equal(type1, type2) == (*map1 == *map2));
}
}
}
void Constant() {
// Constructor
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
Handle<i::Object> value = *vt;
AstType* type = T.Constant(value);
CHECK(type->IsConstant());
}
// Value attribute
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
Handle<i::Object> value = *vt;
AstType* type = T.Constant(value);
CHECK(*value == *type->AsConstant()->Value());
}
// Functionality & Injectivity: Constant(V1) = Constant(V2) iff V1 = V2
for (ValueIterator vt1 = T.values.begin(); vt1 != T.values.end(); ++vt1) {
for (ValueIterator vt2 = T.values.begin(); vt2 != T.values.end(); ++vt2) {
Handle<i::Object> value1 = *vt1;
Handle<i::Object> value2 = *vt2;
AstType* type1 = T.Constant(value1);
AstType* type2 = T.Constant(value2);
CHECK(Equal(type1, type2) == (*value1 == *value2));
}
}
// Typing of numbers
Factory* fac = isolate->factory();
CHECK(T.Constant(fac->NewNumber(0))->Is(T.UnsignedSmall));
CHECK(T.Constant(fac->NewNumber(1))->Is(T.UnsignedSmall));
CHECK(T.Constant(fac->NewNumber(0x3fffffff))->Is(T.UnsignedSmall));
CHECK(T.Constant(fac->NewNumber(-1))->Is(T.Negative31));
CHECK(T.Constant(fac->NewNumber(-0x3fffffff))->Is(T.Negative31));
CHECK(T.Constant(fac->NewNumber(-0x40000000))->Is(T.Negative31));
CHECK(T.Constant(fac->NewNumber(0x40000000))->Is(T.Unsigned31));
CHECK(!T.Constant(fac->NewNumber(0x40000000))->Is(T.Unsigned30));
CHECK(T.Constant(fac->NewNumber(0x7fffffff))->Is(T.Unsigned31));
CHECK(!T.Constant(fac->NewNumber(0x7fffffff))->Is(T.Unsigned30));
CHECK(T.Constant(fac->NewNumber(-0x40000001))->Is(T.Negative32));
CHECK(!T.Constant(fac->NewNumber(-0x40000001))->Is(T.Negative31));
CHECK(T.Constant(fac->NewNumber(-0x7fffffff))->Is(T.Negative32));
CHECK(!T.Constant(fac->NewNumber(-0x7fffffff - 1))->Is(T.Negative31));
if (SmiValuesAre31Bits()) {
CHECK(!T.Constant(fac->NewNumber(0x40000000))->Is(T.UnsignedSmall));
CHECK(!T.Constant(fac->NewNumber(0x7fffffff))->Is(T.UnsignedSmall));
CHECK(!T.Constant(fac->NewNumber(-0x40000001))->Is(T.SignedSmall));
CHECK(!T.Constant(fac->NewNumber(-0x7fffffff - 1))->Is(T.SignedSmall));
} else {
CHECK(SmiValuesAre32Bits());
CHECK(T.Constant(fac->NewNumber(0x40000000))->Is(T.UnsignedSmall));
CHECK(T.Constant(fac->NewNumber(0x7fffffff))->Is(T.UnsignedSmall));
CHECK(T.Constant(fac->NewNumber(-0x40000001))->Is(T.SignedSmall));
CHECK(T.Constant(fac->NewNumber(-0x7fffffff - 1))->Is(T.SignedSmall));
}
CHECK(T.Constant(fac->NewNumber(0x80000000u))->Is(T.Unsigned32));
CHECK(!T.Constant(fac->NewNumber(0x80000000u))->Is(T.Unsigned31));
CHECK(T.Constant(fac->NewNumber(0xffffffffu))->Is(T.Unsigned32));
CHECK(!T.Constant(fac->NewNumber(0xffffffffu))->Is(T.Unsigned31));
CHECK(T.Constant(fac->NewNumber(0xffffffffu + 1.0))->Is(T.PlainNumber));
CHECK(!T.Constant(fac->NewNumber(0xffffffffu + 1.0))->Is(T.Integral32));
CHECK(T.Constant(fac->NewNumber(-0x7fffffff - 2.0))->Is(T.PlainNumber));
CHECK(!T.Constant(fac->NewNumber(-0x7fffffff - 2.0))->Is(T.Integral32));
CHECK(T.Constant(fac->NewNumber(0.1))->Is(T.PlainNumber));
CHECK(!T.Constant(fac->NewNumber(0.1))->Is(T.Integral32));
CHECK(T.Constant(fac->NewNumber(-10.1))->Is(T.PlainNumber));
CHECK(!T.Constant(fac->NewNumber(-10.1))->Is(T.Integral32));
CHECK(T.Constant(fac->NewNumber(10e60))->Is(T.PlainNumber));
CHECK(!T.Constant(fac->NewNumber(10e60))->Is(T.Integral32));
CHECK(T.Constant(fac->NewNumber(-1.0 * 0.0))->Is(T.MinusZero));
CHECK(T.Constant(fac->NewNumber(std::numeric_limits<double>::quiet_NaN()))
->Is(T.NaN));
CHECK(T.Constant(fac->NewNumber(V8_INFINITY))->Is(T.PlainNumber));
CHECK(!T.Constant(fac->NewNumber(V8_INFINITY))->Is(T.Integral32));
CHECK(T.Constant(fac->NewNumber(-V8_INFINITY))->Is(T.PlainNumber));
CHECK(!T.Constant(fac->NewNumber(-V8_INFINITY))->Is(T.Integral32));
}
void Range() {
// Constructor
for (ValueIterator i = T.integers.begin(); i != T.integers.end(); ++i) {
for (ValueIterator j = T.integers.begin(); j != T.integers.end(); ++j) {
double min = (*i)->Number();
double max = (*j)->Number();
if (min > max) std::swap(min, max);
AstType* type = T.Range(min, max);
CHECK(type->IsRange());
}
}
// Range attributes
for (ValueIterator i = T.integers.begin(); i != T.integers.end(); ++i) {
for (ValueIterator j = T.integers.begin(); j != T.integers.end(); ++j) {
double min = (*i)->Number();
double max = (*j)->Number();
if (min > max) std::swap(min, max);
AstType* type = T.Range(min, max);
CHECK(min == type->AsRange()->Min());
CHECK(max == type->AsRange()->Max());
}
}
// Functionality & Injectivity:
// Range(min1, max1) = Range(min2, max2) <=> min1 = min2 /\ max1 = max2
for (ValueIterator i1 = T.integers.begin(); i1 != T.integers.end(); ++i1) {
for (ValueIterator j1 = i1; j1 != T.integers.end(); ++j1) {
for (ValueIterator i2 = T.integers.begin(); i2 != T.integers.end();
++i2) {
for (ValueIterator j2 = i2; j2 != T.integers.end(); ++j2) {
double min1 = (*i1)->Number();
double max1 = (*j1)->Number();
double min2 = (*i2)->Number();
double max2 = (*j2)->Number();
if (min1 > max1) std::swap(min1, max1);
if (min2 > max2) std::swap(min2, max2);
AstType* type1 = T.Range(min1, max1);
AstType* type2 = T.Range(min2, max2);
CHECK(Equal(type1, type2) == (min1 == min2 && max1 == max2));
}
}
}
}
}
void Context() {
// Constructor
for (int i = 0; i < 20; ++i) {
AstType* type = T.Random();
AstType* context = T.Context(type);
CHECK(context->IsContext());
}
// Attributes
for (int i = 0; i < 20; ++i) {
AstType* type = T.Random();
AstType* context = T.Context(type);
CheckEqual(type, context->AsContext()->Outer());
}
// Functionality & Injectivity: Context(T1) = Context(T2) iff T1 = T2
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 20; ++j) {
AstType* type1 = T.Random();
AstType* type2 = T.Random();
AstType* context1 = T.Context(type1);
AstType* context2 = T.Context(type2);
CHECK(Equal(context1, context2) == Equal(type1, type2));
}
}
}
void Array() {
// Constructor
for (int i = 0; i < 20; ++i) {
AstType* type = T.Random();
AstType* array = T.Array1(type);
CHECK(array->IsArray());
}
// Attributes
for (int i = 0; i < 20; ++i) {
AstType* type = T.Random();
AstType* array = T.Array1(type);
CheckEqual(type, array->AsArray()->Element());
}
// Functionality & Injectivity: Array(T1) = Array(T2) iff T1 = T2
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 20; ++j) {
AstType* type1 = T.Random();
AstType* type2 = T.Random();
AstType* array1 = T.Array1(type1);
AstType* array2 = T.Array1(type2);
CHECK(Equal(array1, array2) == Equal(type1, type2));
}
}
}
void Function() {
// Constructors
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 20; ++j) {
for (int k = 0; k < 20; ++k) {
AstType* type1 = T.Random();
AstType* type2 = T.Random();
AstType* type3 = T.Random();
AstType* function0 = T.Function0(type1, type2);
AstType* function1 = T.Function1(type1, type2, type3);
AstType* function2 = T.Function2(type1, type2, type3);
CHECK(function0->IsFunction());
CHECK(function1->IsFunction());
CHECK(function2->IsFunction());
}
}
}
// Attributes
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 20; ++j) {
for (int k = 0; k < 20; ++k) {
AstType* type1 = T.Random();
AstType* type2 = T.Random();
AstType* type3 = T.Random();
AstType* function0 = T.Function0(type1, type2);
AstType* function1 = T.Function1(type1, type2, type3);
AstType* function2 = T.Function2(type1, type2, type3);
CHECK_EQ(0, function0->AsFunction()->Arity());
CHECK_EQ(1, function1->AsFunction()->Arity());
CHECK_EQ(2, function2->AsFunction()->Arity());
CheckEqual(type1, function0->AsFunction()->Result());
CheckEqual(type1, function1->AsFunction()->Result());
CheckEqual(type1, function2->AsFunction()->Result());
CheckEqual(type2, function0->AsFunction()->Receiver());
CheckEqual(type2, function1->AsFunction()->Receiver());
CheckEqual(T.Any, function2->AsFunction()->Receiver());
CheckEqual(type3, function1->AsFunction()->Parameter(0));
CheckEqual(type2, function2->AsFunction()->Parameter(0));
CheckEqual(type3, function2->AsFunction()->Parameter(1));
}
}
}
// Functionality & Injectivity: Function(Ts1) = Function(Ts2) iff Ts1 = Ts2
for (int i = 0; i < 20; ++i) {
for (int j = 0; j < 20; ++j) {
for (int k = 0; k < 20; ++k) {
AstType* type1 = T.Random();
AstType* type2 = T.Random();
AstType* type3 = T.Random();
AstType* function01 = T.Function0(type1, type2);
AstType* function02 = T.Function0(type1, type3);
AstType* function03 = T.Function0(type3, type2);
AstType* function11 = T.Function1(type1, type2, type2);
AstType* function12 = T.Function1(type1, type2, type3);
AstType* function21 = T.Function2(type1, type2, type2);
AstType* function22 = T.Function2(type1, type2, type3);
AstType* function23 = T.Function2(type1, type3, type2);
CHECK(Equal(function01, function02) == Equal(type2, type3));
CHECK(Equal(function01, function03) == Equal(type1, type3));
CHECK(Equal(function11, function12) == Equal(type2, type3));
CHECK(Equal(function21, function22) == Equal(type2, type3));
CHECK(Equal(function21, function23) == Equal(type2, type3));
}
}
}
}
void Of() {
// Constant(V)->Is(Of(V))
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
Handle<i::Object> value = *vt;
AstType* const_type = T.Constant(value);
AstType* of_type = T.Of(value);
CHECK(const_type->Is(of_type));
}
// If Of(V)->Is(T), then Constant(V)->Is(T)
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
Handle<i::Object> value = *vt;
AstType* type = *it;
AstType* const_type = T.Constant(value);
AstType* of_type = T.Of(value);
CHECK(!of_type->Is(type) || const_type->Is(type));
}
}
// If Constant(V)->Is(T), then Of(V)->Is(T) or T->Maybe(Constant(V))
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
Handle<i::Object> value = *vt;
AstType* type = *it;
AstType* const_type = T.Constant(value);
AstType* of_type = T.Of(value);
CHECK(!const_type->Is(type) || of_type->Is(type) ||
type->Maybe(const_type));
}
}
}
void NowOf() {
// Constant(V)->NowIs(NowOf(V))
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
Handle<i::Object> value = *vt;
AstType* const_type = T.Constant(value);
AstType* nowof_type = T.NowOf(value);
CHECK(const_type->NowIs(nowof_type));
}
// NowOf(V)->Is(Of(V))
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
Handle<i::Object> value = *vt;
AstType* nowof_type = T.NowOf(value);
AstType* of_type = T.Of(value);
CHECK(nowof_type->Is(of_type));
}
// If NowOf(V)->NowIs(T), then Constant(V)->NowIs(T)
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
Handle<i::Object> value = *vt;
AstType* type = *it;
AstType* const_type = T.Constant(value);
AstType* nowof_type = T.NowOf(value);
CHECK(!nowof_type->NowIs(type) || const_type->NowIs(type));
}
}
// If Constant(V)->NowIs(T),
// then NowOf(V)->NowIs(T) or T->Maybe(Constant(V))
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
Handle<i::Object> value = *vt;
AstType* type = *it;
AstType* const_type = T.Constant(value);
AstType* nowof_type = T.NowOf(value);
CHECK(!const_type->NowIs(type) || nowof_type->NowIs(type) ||
type->Maybe(const_type));
}
}
// If Constant(V)->Is(T),
// then NowOf(V)->Is(T) or T->Maybe(Constant(V))
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
Handle<i::Object> value = *vt;
AstType* type = *it;
AstType* const_type = T.Constant(value);
AstType* nowof_type = T.NowOf(value);
CHECK(!const_type->Is(type) || nowof_type->Is(type) ||
type->Maybe(const_type));
}
}
}
void MinMax() {
// If b is regular numeric bitset, then Range(b->Min(), b->Max())->Is(b).
// TODO(neis): Need to ignore representation for this to be true.
/*
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
if (this->IsBitset(type) && type->Is(T.Number) &&
!type->Is(T.None) && !type->Is(T.NaN)) {
AstType* range = T.Range(
isolate->factory()->NewNumber(type->Min()),
isolate->factory()->NewNumber(type->Max()));
CHECK(range->Is(type));
}
}
*/
// If b is regular numeric bitset, then b->Min() and b->Max() are integers.
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
if (this->IsBitset(type) && type->Is(T.Number) && !type->Is(T.NaN)) {
CHECK(IsInteger(type->Min()) && IsInteger(type->Max()));
}
}
// If b1 and b2 are regular numeric bitsets with b1->Is(b2), then
// b1->Min() >= b2->Min() and b1->Max() <= b2->Max().
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
if (this->IsBitset(type1) && type1->Is(type2) && type2->Is(T.Number) &&
!type1->Is(T.NaN) && !type2->Is(T.NaN)) {
CHECK(type1->Min() >= type2->Min());
CHECK(type1->Max() <= type2->Max());
}
}
}
// Lub(Range(x,y))->Min() <= x and y <= Lub(Range(x,y))->Max()
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
if (type->IsRange()) {
AstType* lub = AstBitsetType::NewForTesting(AstBitsetType::Lub(type));
CHECK(lub->Min() <= type->Min() && type->Max() <= lub->Max());
}
}
// Rangification: If T->Is(Range(-inf,+inf)) and T is inhabited, then
// T->Is(Range(T->Min(), T->Max())).
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
CHECK(!type->Is(T.Integer) || !type->IsInhabited() ||
type->Is(T.Range(type->Min(), type->Max())));
}
}
void BitsetGlb() {
// Lower: (T->BitsetGlb())->Is(T)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
AstType* glb = AstBitsetType::NewForTesting(AstBitsetType::Glb(type));
CHECK(glb->Is(type));
}
// Greatest: If T1->IsBitset() and T1->Is(T2), then T1->Is(T2->BitsetGlb())
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* glb2 = AstBitsetType::NewForTesting(AstBitsetType::Glb(type2));
CHECK(!this->IsBitset(type1) || !type1->Is(type2) || type1->Is(glb2));
}
}
// Monotonicity: T1->Is(T2) implies (T1->BitsetGlb())->Is(T2->BitsetGlb())
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* glb1 = AstBitsetType::NewForTesting(AstBitsetType::Glb(type1));
AstType* glb2 = AstBitsetType::NewForTesting(AstBitsetType::Glb(type2));
CHECK(!type1->Is(type2) || glb1->Is(glb2));
}
}
}
void BitsetLub() {
// Upper: T->Is(T->BitsetLub())
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
AstType* lub = AstBitsetType::NewForTesting(AstBitsetType::Lub(type));
CHECK(type->Is(lub));
}
// Least: If T2->IsBitset() and T1->Is(T2), then (T1->BitsetLub())->Is(T2)
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* lub1 = AstBitsetType::NewForTesting(AstBitsetType::Lub(type1));
CHECK(!this->IsBitset(type2) || !type1->Is(type2) || lub1->Is(type2));
}
}
// Monotonicity: T1->Is(T2) implies (T1->BitsetLub())->Is(T2->BitsetLub())
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* lub1 = AstBitsetType::NewForTesting(AstBitsetType::Lub(type1));
AstType* lub2 = AstBitsetType::NewForTesting(AstBitsetType::Lub(type2));
CHECK(!type1->Is(type2) || lub1->Is(lub2));
}
}
}
void Is1() {
// Least Element (Bottom): None->Is(T)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
CHECK(T.None->Is(type));
}
// Greatest Element (Top): T->Is(Any)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
CHECK(type->Is(T.Any));
}
// Bottom Uniqueness: T->Is(None) implies T = None
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
if (type->Is(T.None)) CheckEqual(type, T.None);
}
// Top Uniqueness: Any->Is(T) implies T = Any
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
if (T.Any->Is(type)) CheckEqual(type, T.Any);
}
// Reflexivity: T->Is(T)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
CHECK(type->Is(type));
}
// Transitivity: T1->Is(T2) and T2->Is(T3) implies T1->Is(T3)
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
CHECK(!(type1->Is(type2) && type2->Is(type3)) || type1->Is(type3));
}
}
}
// Antisymmetry: T1->Is(T2) and T2->Is(T1) iff T1 = T2
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
CHECK((type1->Is(type2) && type2->Is(type1)) == Equal(type1, type2));
}
}
// (In-)Compatibilities.
for (TypeIterator i = T.types.begin(); i != T.types.end(); ++i) {
for (TypeIterator j = T.types.begin(); j != T.types.end(); ++j) {
AstType* type1 = *i;
AstType* type2 = *j;
CHECK(!type1->Is(type2) || this->IsBitset(type2) ||
this->IsUnion(type2) || this->IsUnion(type1) ||
(type1->IsClass() && type2->IsClass()) ||
(type1->IsConstant() && type2->IsConstant()) ||
(type1->IsConstant() && type2->IsRange()) ||
(this->IsBitset(type1) && type2->IsRange()) ||
(type1->IsRange() && type2->IsRange()) ||
(type1->IsContext() && type2->IsContext()) ||
(type1->IsArray() && type2->IsArray()) ||
(type1->IsFunction() && type2->IsFunction()) ||
!type1->IsInhabited());
}
}
}
void Is2() {
// Class(M1)->Is(Class(M2)) iff M1 = M2
for (MapIterator mt1 = T.maps.begin(); mt1 != T.maps.end(); ++mt1) {
for (MapIterator mt2 = T.maps.begin(); mt2 != T.maps.end(); ++mt2) {
Handle<i::Map> map1 = *mt1;
Handle<i::Map> map2 = *mt2;
AstType* class_type1 = T.Class(map1);
AstType* class_type2 = T.Class(map2);
CHECK(class_type1->Is(class_type2) == (*map1 == *map2));
}
}
// Range(X1, Y1)->Is(Range(X2, Y2)) iff X1 >= X2 /\ Y1 <= Y2
for (ValueIterator i1 = T.integers.begin(); i1 != T.integers.end(); ++i1) {
for (ValueIterator j1 = i1; j1 != T.integers.end(); ++j1) {
for (ValueIterator i2 = T.integers.begin(); i2 != T.integers.end();
++i2) {
for (ValueIterator j2 = i2; j2 != T.integers.end(); ++j2) {
double min1 = (*i1)->Number();
double max1 = (*j1)->Number();
double min2 = (*i2)->Number();
double max2 = (*j2)->Number();
if (min1 > max1) std::swap(min1, max1);
if (min2 > max2) std::swap(min2, max2);
AstType* type1 = T.Range(min1, max1);
AstType* type2 = T.Range(min2, max2);
CHECK(type1->Is(type2) == (min1 >= min2 && max1 <= max2));
}
}
}
}
// Constant(V1)->Is(Constant(V2)) iff V1 = V2
for (ValueIterator vt1 = T.values.begin(); vt1 != T.values.end(); ++vt1) {
for (ValueIterator vt2 = T.values.begin(); vt2 != T.values.end(); ++vt2) {
Handle<i::Object> value1 = *vt1;
Handle<i::Object> value2 = *vt2;
AstType* const_type1 = T.Constant(value1);
AstType* const_type2 = T.Constant(value2);
CHECK(const_type1->Is(const_type2) == (*value1 == *value2));
}
}
// Context(T1)->Is(Context(T2)) iff T1 = T2
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* outer1 = *it1;
AstType* outer2 = *it2;
AstType* type1 = T.Context(outer1);
AstType* type2 = T.Context(outer2);
CHECK(type1->Is(type2) == outer1->Equals(outer2));
}
}
// Array(T1)->Is(Array(T2)) iff T1 = T2
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* element1 = *it1;
AstType* element2 = *it2;
AstType* type1 = T.Array1(element1);
AstType* type2 = T.Array1(element2);
CHECK(type1->Is(type2) == element1->Equals(element2));
}
}
// Function0(S1, T1)->Is(Function0(S2, T2)) iff S1 = S2 and T1 = T2
for (TypeIterator i = T.types.begin(); i != T.types.end(); ++i) {
for (TypeIterator j = T.types.begin(); j != T.types.end(); ++j) {
AstType* result1 = *i;
AstType* receiver1 = *j;
AstType* type1 = T.Function0(result1, receiver1);
AstType* result2 = T.Random();
AstType* receiver2 = T.Random();
AstType* type2 = T.Function0(result2, receiver2);
CHECK(type1->Is(type2) ==
(result1->Equals(result2) && receiver1->Equals(receiver2)));
}
}
// Range-specific subtyping
// If IsInteger(v) then Constant(v)->Is(Range(v, v)).
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
if (type->IsConstant() && IsInteger(*type->AsConstant()->Value())) {
CHECK(type->Is(T.Range(type->AsConstant()->Value()->Number(),
type->AsConstant()->Value()->Number())));
}
}
// If Constant(x)->Is(Range(min,max)) then IsInteger(v) and min <= x <= max.
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
if (type1->IsConstant() && type2->IsRange() && type1->Is(type2)) {
double x = type1->AsConstant()->Value()->Number();
double min = type2->AsRange()->Min();
double max = type2->AsRange()->Max();
CHECK(IsInteger(x) && min <= x && x <= max);
}
}
}
// Lub(Range(x,y))->Is(T.Union(T.Integral32, T.OtherNumber))
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
if (type->IsRange()) {
AstType* lub = AstBitsetType::NewForTesting(AstBitsetType::Lub(type));
CHECK(lub->Is(T.PlainNumber));
}
}
// Subtyping between concrete basic types
CheckUnordered(T.Boolean, T.Null);
CheckUnordered(T.Undefined, T.Null);
CheckUnordered(T.Boolean, T.Undefined);
CheckSub(T.SignedSmall, T.Number);
CheckSub(T.Signed32, T.Number);
CheckSubOrEqual(T.SignedSmall, T.Signed32);
CheckUnordered(T.SignedSmall, T.MinusZero);
CheckUnordered(T.Signed32, T.Unsigned32);
CheckSub(T.UniqueName, T.Name);
CheckSub(T.String, T.Name);
CheckSub(T.InternalizedString, T.String);
CheckSub(T.InternalizedString, T.UniqueName);
CheckSub(T.InternalizedString, T.Name);
CheckSub(T.Symbol, T.UniqueName);
CheckSub(T.Symbol, T.Name);
CheckUnordered(T.String, T.UniqueName);
CheckUnordered(T.String, T.Symbol);
CheckUnordered(T.InternalizedString, T.Symbol);
CheckSub(T.Object, T.Receiver);
CheckSub(T.Proxy, T.Receiver);
CheckSub(T.OtherObject, T.Object);
CheckSub(T.OtherUndetectable, T.Object);
CheckSub(T.OtherObject, T.Object);
CheckUnordered(T.Object, T.Proxy);
CheckUnordered(T.OtherObject, T.Undetectable);
// Subtyping between concrete structural types
CheckSub(T.ObjectClass, T.Object);
CheckSub(T.ArrayClass, T.OtherObject);
CheckSub(T.UninitializedClass, T.Internal);
CheckUnordered(T.ObjectClass, T.ArrayClass);
CheckUnordered(T.UninitializedClass, T.Null);
CheckUnordered(T.UninitializedClass, T.Undefined);
CheckSub(T.SmiConstant, T.SignedSmall);
CheckSub(T.SmiConstant, T.Signed32);
CheckSub(T.SmiConstant, T.Number);
CheckSub(T.ObjectConstant1, T.Object);
CheckSub(T.ObjectConstant2, T.Object);
CheckSub(T.ArrayConstant, T.Object);
CheckSub(T.ArrayConstant, T.OtherObject);
CheckSub(T.ArrayConstant, T.Receiver);
CheckSub(T.UninitializedConstant, T.Internal);
CheckUnordered(T.ObjectConstant1, T.ObjectConstant2);
CheckUnordered(T.ObjectConstant1, T.ArrayConstant);
CheckUnordered(T.UninitializedConstant, T.Null);
CheckUnordered(T.UninitializedConstant, T.Undefined);
CheckUnordered(T.ObjectConstant1, T.ObjectClass);
CheckUnordered(T.ObjectConstant2, T.ObjectClass);
CheckUnordered(T.ObjectConstant1, T.ArrayClass);
CheckUnordered(T.ObjectConstant2, T.ArrayClass);
CheckUnordered(T.ArrayConstant, T.ObjectClass);
CheckSub(T.NumberArray, T.OtherObject);
CheckSub(T.NumberArray, T.Receiver);
CheckSub(T.NumberArray, T.Object);
CheckUnordered(T.StringArray, T.AnyArray);
CheckSub(T.MethodFunction, T.Object);
CheckSub(T.NumberFunction1, T.Object);
CheckUnordered(T.SignedFunction1, T.NumberFunction1);
CheckUnordered(T.NumberFunction1, T.NumberFunction2);
}
void NowIs() {
// Least Element (Bottom): None->NowIs(T)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
CHECK(T.None->NowIs(type));
}
// Greatest Element (Top): T->NowIs(Any)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
CHECK(type->NowIs(T.Any));
}
// Bottom Uniqueness: T->NowIs(None) implies T = None
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
if (type->NowIs(T.None)) CheckEqual(type, T.None);
}
// Top Uniqueness: Any->NowIs(T) implies T = Any
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
if (T.Any->NowIs(type)) CheckEqual(type, T.Any);
}
// Reflexivity: T->NowIs(T)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
CHECK(type->NowIs(type));
}
// Transitivity: T1->NowIs(T2) and T2->NowIs(T3) implies T1->NowIs(T3)
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
CHECK(!(type1->NowIs(type2) && type2->NowIs(type3)) ||
type1->NowIs(type3));
}
}
}
// Antisymmetry: T1->NowIs(T2) and T2->NowIs(T1) iff T1 = T2
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
CHECK((type1->NowIs(type2) && type2->NowIs(type1)) ==
Equal(type1, type2));
}
}
// T1->Is(T2) implies T1->NowIs(T2)
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
CHECK(!type1->Is(type2) || type1->NowIs(type2));
}
}
// Constant(V1)->NowIs(Constant(V2)) iff V1 = V2
for (ValueIterator vt1 = T.values.begin(); vt1 != T.values.end(); ++vt1) {
for (ValueIterator vt2 = T.values.begin(); vt2 != T.values.end(); ++vt2) {
Handle<i::Object> value1 = *vt1;
Handle<i::Object> value2 = *vt2;
AstType* const_type1 = T.Constant(value1);
AstType* const_type2 = T.Constant(value2);
CHECK(const_type1->NowIs(const_type2) == (*value1 == *value2));
}
}
// Class(M1)->NowIs(Class(M2)) iff M1 = M2
for (MapIterator mt1 = T.maps.begin(); mt1 != T.maps.end(); ++mt1) {
for (MapIterator mt2 = T.maps.begin(); mt2 != T.maps.end(); ++mt2) {
Handle<i::Map> map1 = *mt1;
Handle<i::Map> map2 = *mt2;
AstType* class_type1 = T.Class(map1);
AstType* class_type2 = T.Class(map2);
CHECK(class_type1->NowIs(class_type2) == (*map1 == *map2));
}
}
// Constant(V)->NowIs(Class(M)) iff V has map M
for (MapIterator mt = T.maps.begin(); mt != T.maps.end(); ++mt) {
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
Handle<i::Map> map = *mt;
Handle<i::Object> value = *vt;
AstType* const_type = T.Constant(value);
AstType* class_type = T.Class(map);
CHECK((value->IsHeapObject() &&
i::HeapObject::cast(*value)->map() == *map) ==
const_type->NowIs(class_type));
}
}
// Class(M)->NowIs(Constant(V)) never
for (MapIterator mt = T.maps.begin(); mt != T.maps.end(); ++mt) {
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
Handle<i::Map> map = *mt;
Handle<i::Object> value = *vt;
AstType* const_type = T.Constant(value);
AstType* class_type = T.Class(map);
CHECK(!class_type->NowIs(const_type));
}
}
}
void Contains() {
// T->Contains(V) iff Constant(V)->Is(T)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
AstType* type = *it;
Handle<i::Object> value = *vt;
AstType* const_type = T.Constant(value);
CHECK(type->Contains(value) == const_type->Is(type));
}
}
}
void NowContains() {
// T->NowContains(V) iff Constant(V)->NowIs(T)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
AstType* type = *it;
Handle<i::Object> value = *vt;
AstType* const_type = T.Constant(value);
CHECK(type->NowContains(value) == const_type->NowIs(type));
}
}
// T->Contains(V) implies T->NowContains(V)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
AstType* type = *it;
Handle<i::Object> value = *vt;
CHECK(!type->Contains(value) || type->NowContains(value));
}
}
// NowOf(V)->Is(T) implies T->NowContains(V)
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
AstType* type = *it;
Handle<i::Object> value = *vt;
AstType* nowof_type = T.Of(value);
CHECK(!nowof_type->NowIs(type) || type->NowContains(value));
}
}
}
void Maybe() {
// T->Maybe(Any) iff T inhabited
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
CHECK(type->Maybe(T.Any) == type->IsInhabited());
}
// T->Maybe(None) never
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
CHECK(!type->Maybe(T.None));
}
// Reflexivity upto Inhabitation: T->Maybe(T) iff T inhabited
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
CHECK(type->Maybe(type) == type->IsInhabited());
}
// Symmetry: T1->Maybe(T2) iff T2->Maybe(T1)
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
CHECK(type1->Maybe(type2) == type2->Maybe(type1));
}
}
// T1->Maybe(T2) implies T1, T2 inhabited
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
CHECK(!type1->Maybe(type2) ||
(type1->IsInhabited() && type2->IsInhabited()));
}
}
// T1->Maybe(T2) implies Intersect(T1, T2) inhabited
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* intersect12 = T.Intersect(type1, type2);
CHECK(!type1->Maybe(type2) || intersect12->IsInhabited());
}
}
// T1->Is(T2) and T1 inhabited implies T1->Maybe(T2)
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
CHECK(!(type1->Is(type2) && type1->IsInhabited()) ||
type1->Maybe(type2));
}
}
// Constant(V1)->Maybe(Constant(V2)) iff V1 = V2
for (ValueIterator vt1 = T.values.begin(); vt1 != T.values.end(); ++vt1) {
for (ValueIterator vt2 = T.values.begin(); vt2 != T.values.end(); ++vt2) {
Handle<i::Object> value1 = *vt1;
Handle<i::Object> value2 = *vt2;
AstType* const_type1 = T.Constant(value1);
AstType* const_type2 = T.Constant(value2);
CHECK(const_type1->Maybe(const_type2) == (*value1 == *value2));
}
}
// Class(M1)->Maybe(Class(M2)) iff M1 = M2
for (MapIterator mt1 = T.maps.begin(); mt1 != T.maps.end(); ++mt1) {
for (MapIterator mt2 = T.maps.begin(); mt2 != T.maps.end(); ++mt2) {
Handle<i::Map> map1 = *mt1;
Handle<i::Map> map2 = *mt2;
AstType* class_type1 = T.Class(map1);
AstType* class_type2 = T.Class(map2);
CHECK(class_type1->Maybe(class_type2) == (*map1 == *map2));
}
}
// Constant(V)->Maybe(Class(M)) never
// This does NOT hold!
/*
for (MapIterator mt = T.maps.begin(); mt != T.maps.end(); ++mt) {
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
Handle<i::Map> map = *mt;
Handle<i::Object> value = *vt;
AstType* const_type = T.Constant(value);
AstType* class_type = T.Class(map);
CHECK(!const_type->Maybe(class_type));
}
}
*/
// Class(M)->Maybe(Constant(V)) never
// This does NOT hold!
/*
for (MapIterator mt = T.maps.begin(); mt != T.maps.end(); ++mt) {
for (ValueIterator vt = T.values.begin(); vt != T.values.end(); ++vt) {
Handle<i::Map> map = *mt;
Handle<i::Object> value = *vt;
AstType* const_type = T.Constant(value);
AstType* class_type = T.Class(map);
CHECK(!class_type->Maybe(const_type));
}
}
*/
// Basic types
CheckDisjoint(T.Boolean, T.Null);
CheckDisjoint(T.Undefined, T.Null);
CheckDisjoint(T.Boolean, T.Undefined);
CheckOverlap(T.SignedSmall, T.Number);
CheckOverlap(T.NaN, T.Number);
CheckDisjoint(T.Signed32, T.NaN);
CheckOverlap(T.UniqueName, T.Name);
CheckOverlap(T.String, T.Name);
CheckOverlap(T.InternalizedString, T.String);
CheckOverlap(T.InternalizedString, T.UniqueName);
CheckOverlap(T.InternalizedString, T.Name);
CheckOverlap(T.Symbol, T.UniqueName);
CheckOverlap(T.Symbol, T.Name);
CheckOverlap(T.String, T.UniqueName);
CheckDisjoint(T.String, T.Symbol);
CheckDisjoint(T.InternalizedString, T.Symbol);
CheckOverlap(T.Object, T.Receiver);
CheckOverlap(T.OtherObject, T.Object);
CheckOverlap(T.Proxy, T.Receiver);
CheckDisjoint(T.Object, T.Proxy);
// Structural types
CheckOverlap(T.ObjectClass, T.Object);
CheckOverlap(T.ArrayClass, T.Object);
CheckOverlap(T.ObjectClass, T.ObjectClass);
CheckOverlap(T.ArrayClass, T.ArrayClass);
CheckDisjoint(T.ObjectClass, T.ArrayClass);
CheckOverlap(T.SmiConstant, T.SignedSmall);
CheckOverlap(T.SmiConstant, T.Signed32);
CheckOverlap(T.SmiConstant, T.Number);
CheckOverlap(T.ObjectConstant1, T.Object);
CheckOverlap(T.ObjectConstant2, T.Object);
CheckOverlap(T.ArrayConstant, T.Object);
CheckOverlap(T.ArrayConstant, T.Receiver);
CheckOverlap(T.ObjectConstant1, T.ObjectConstant1);
CheckDisjoint(T.ObjectConstant1, T.ObjectConstant2);
CheckDisjoint(T.ObjectConstant1, T.ArrayConstant);
CheckOverlap(T.ObjectConstant1, T.ArrayClass);
CheckOverlap(T.ObjectConstant2, T.ArrayClass);
CheckOverlap(T.ArrayConstant, T.ObjectClass);
CheckOverlap(T.NumberArray, T.Receiver);
CheckDisjoint(T.NumberArray, T.AnyArray);
CheckDisjoint(T.NumberArray, T.StringArray);
CheckOverlap(T.MethodFunction, T.Object);
CheckDisjoint(T.SignedFunction1, T.NumberFunction1);
CheckDisjoint(T.SignedFunction1, T.NumberFunction2);
CheckDisjoint(T.NumberFunction1, T.NumberFunction2);
CheckDisjoint(T.SignedFunction1, T.MethodFunction);
CheckOverlap(T.ObjectConstant1, T.ObjectClass); // !!!
CheckOverlap(T.ObjectConstant2, T.ObjectClass); // !!!
CheckOverlap(T.NumberClass, T.Intersect(T.Number, T.Tagged)); // !!!
}
void Union1() {
// Identity: Union(T, None) = T
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
AstType* union_type = T.Union(type, T.None);
CheckEqual(union_type, type);
}
// Domination: Union(T, Any) = Any
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
AstType* union_type = T.Union(type, T.Any);
CheckEqual(union_type, T.Any);
}
// Idempotence: Union(T, T) = T
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
AstType* union_type = T.Union(type, type);
CheckEqual(union_type, type);
}
// Commutativity: Union(T1, T2) = Union(T2, T1)
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* union12 = T.Union(type1, type2);
AstType* union21 = T.Union(type2, type1);
CheckEqual(union12, union21);
}
}
// Associativity: Union(T1, Union(T2, T3)) = Union(Union(T1, T2), T3)
// This does NOT hold! For example:
// (Unsigned32 \/ Range(0,5)) \/ Range(-5,0) = Unsigned32 \/ Range(-5,0)
// Unsigned32 \/ (Range(0,5) \/ Range(-5,0)) = Unsigned32 \/ Range(-5,5)
/*
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
AstType* union12 = T.Union(type1, type2);
AstType* union23 = T.Union(type2, type3);
AstType* union1_23 = T.Union(type1, union23);
AstType* union12_3 = T.Union(union12, type3);
CheckEqual(union1_23, union12_3);
}
}
}
*/
// Meet: T1->Is(Union(T1, T2)) and T2->Is(Union(T1, T2))
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* union12 = T.Union(type1, type2);
CHECK(type1->Is(union12));
CHECK(type2->Is(union12));
}
}
// Upper Boundedness: T1->Is(T2) implies Union(T1, T2) = T2
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* union12 = T.Union(type1, type2);
if (type1->Is(type2)) CheckEqual(union12, type2);
}
}
// Monotonicity: T1->Is(T2) implies Union(T1, T3)->Is(Union(T2, T3))
// This does NOT hold. For example:
// Range(-5,-1) <= Signed32
// Range(-5,-1) \/ Range(1,5) = Range(-5,5) </= Signed32 \/ Range(1,5)
/*
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
AstType* union13 = T.Union(type1, type3);
AstType* union23 = T.Union(type2, type3);
CHECK(!type1->Is(type2) || union13->Is(union23));
}
}
}
*/
}
void Union2() {
// Monotonicity: T1->Is(T3) and T2->Is(T3) implies Union(T1, T2)->Is(T3)
// This does NOT hold. For example:
// Range(-2^33, -2^33) <= OtherNumber
// Range(2^33, 2^33) <= OtherNumber
// Range(-2^33, 2^33) </= OtherNumber
/*
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
AstType* union12 = T.Union(type1, type2);
CHECK(!(type1->Is(type3) && type2->Is(type3)) || union12->Is(type3));
}
}
}
*/
}
void Union3() {
// Monotonicity: T1->Is(T2) or T1->Is(T3) implies T1->Is(Union(T2, T3))
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
HandleScope scope(isolate);
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = it2; it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
AstType* union23 = T.Union(type2, type3);
CHECK(!(type1->Is(type2) || type1->Is(type3)) || type1->Is(union23));
}
}
}
}
void Union4() {
// Class-class
CheckSub(T.Union(T.ObjectClass, T.ArrayClass), T.Object);
CheckOverlap(T.Union(T.ObjectClass, T.ArrayClass), T.OtherObject);
CheckOverlap(T.Union(T.ObjectClass, T.ArrayClass), T.Receiver);
CheckDisjoint(T.Union(T.ObjectClass, T.ArrayClass), T.Number);
// Constant-constant
CheckSub(T.Union(T.ObjectConstant1, T.ObjectConstant2), T.Object);
CheckOverlap(T.Union(T.ObjectConstant1, T.ArrayConstant), T.OtherObject);
CheckUnordered(T.Union(T.ObjectConstant1, T.ObjectConstant2),
T.ObjectClass);
CheckOverlap(T.Union(T.ObjectConstant1, T.ArrayConstant), T.OtherObject);
CheckDisjoint(T.Union(T.ObjectConstant1, T.ArrayConstant), T.Number);
CheckOverlap(T.Union(T.ObjectConstant1, T.ArrayConstant),
T.ObjectClass); // !!!
// Bitset-array
CHECK(this->IsBitset(T.Union(T.AnyArray, T.Receiver)));
CHECK(this->IsUnion(T.Union(T.NumberArray, T.Number)));
CheckEqual(T.Union(T.AnyArray, T.Receiver), T.Receiver);
CheckEqual(T.Union(T.AnyArray, T.OtherObject), T.OtherObject);
CheckUnordered(T.Union(T.AnyArray, T.String), T.Receiver);
CheckOverlap(T.Union(T.NumberArray, T.String), T.Object);
CheckDisjoint(T.Union(T.NumberArray, T.String), T.Number);
// Bitset-function
CHECK(this->IsBitset(T.Union(T.MethodFunction, T.Object)));
CHECK(this->IsUnion(T.Union(T.NumberFunction1, T.Number)));
CheckEqual(T.Union(T.MethodFunction, T.Object), T.Object);
CheckUnordered(T.Union(T.NumberFunction1, T.String), T.Object);
CheckOverlap(T.Union(T.NumberFunction2, T.String), T.Object);
CheckDisjoint(T.Union(T.NumberFunction1, T.String), T.Number);
// Bitset-class
CheckSub(T.Union(T.ObjectClass, T.SignedSmall),
T.Union(T.Object, T.Number));
CheckSub(T.Union(T.ObjectClass, T.OtherObject), T.Object);
CheckUnordered(T.Union(T.ObjectClass, T.String), T.OtherObject);
CheckOverlap(T.Union(T.ObjectClass, T.String), T.Object);
CheckDisjoint(T.Union(T.ObjectClass, T.String), T.Number);
// Bitset-constant
CheckSub(T.Union(T.ObjectConstant1, T.Signed32),
T.Union(T.Object, T.Number));
CheckSub(T.Union(T.ObjectConstant1, T.OtherObject), T.Object);
CheckUnordered(T.Union(T.ObjectConstant1, T.String), T.OtherObject);
CheckOverlap(T.Union(T.ObjectConstant1, T.String), T.Object);
CheckDisjoint(T.Union(T.ObjectConstant1, T.String), T.Number);
// Class-constant
CheckSub(T.Union(T.ObjectConstant1, T.ArrayClass), T.Object);
CheckUnordered(T.ObjectClass, T.Union(T.ObjectConstant1, T.ArrayClass));
CheckSub(T.Union(T.ObjectConstant1, T.ArrayClass),
T.Union(T.Receiver, T.Object));
CheckUnordered(T.Union(T.ObjectConstant1, T.ArrayClass), T.ArrayConstant);
CheckOverlap(T.Union(T.ObjectConstant1, T.ArrayClass), T.ObjectConstant2);
CheckOverlap(T.Union(T.ObjectConstant1, T.ArrayClass),
T.ObjectClass); // !!!
// Bitset-union
CheckSub(T.NaN,
T.Union(T.Union(T.ArrayClass, T.ObjectConstant1), T.Number));
CheckSub(T.Union(T.Union(T.ArrayClass, T.ObjectConstant1), T.Signed32),
T.Union(T.ObjectConstant1, T.Union(T.Number, T.ArrayClass)));
// Class-union
CheckSub(T.Union(T.ObjectClass, T.Union(T.ObjectConstant1, T.ObjectClass)),
T.Object);
CheckEqual(T.Union(T.Union(T.ArrayClass, T.ObjectConstant2), T.ArrayClass),
T.Union(T.ArrayClass, T.ObjectConstant2));
// Constant-union
CheckEqual(T.Union(T.ObjectConstant1,
T.Union(T.ObjectConstant1, T.ObjectConstant2)),
T.Union(T.ObjectConstant2, T.ObjectConstant1));
CheckEqual(
T.Union(T.Union(T.ArrayConstant, T.ObjectConstant2), T.ObjectConstant1),
T.Union(T.ObjectConstant2,
T.Union(T.ArrayConstant, T.ObjectConstant1)));
// Array-union
CheckEqual(T.Union(T.AnyArray, T.Union(T.NumberArray, T.AnyArray)),
T.Union(T.AnyArray, T.NumberArray));
CheckSub(T.Union(T.AnyArray, T.NumberArray), T.OtherObject);
// Function-union
CheckEqual(T.Union(T.NumberFunction1, T.NumberFunction2),
T.Union(T.NumberFunction2, T.NumberFunction1));
CheckSub(T.Union(T.SignedFunction1, T.MethodFunction), T.Object);
// Union-union
CheckEqual(T.Union(T.Union(T.ObjectConstant2, T.ObjectConstant1),
T.Union(T.ObjectConstant1, T.ObjectConstant2)),
T.Union(T.ObjectConstant2, T.ObjectConstant1));
CheckEqual(T.Union(T.Union(T.Number, T.ArrayClass),
T.Union(T.SignedSmall, T.Receiver)),
T.Union(T.Number, T.Receiver));
}
void Intersect() {
// Identity: Intersect(T, Any) = T
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
AstType* intersect_type = T.Intersect(type, T.Any);
CheckEqual(intersect_type, type);
}
// Domination: Intersect(T, None) = None
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
AstType* intersect_type = T.Intersect(type, T.None);
CheckEqual(intersect_type, T.None);
}
// Idempotence: Intersect(T, T) = T
for (TypeIterator it = T.types.begin(); it != T.types.end(); ++it) {
AstType* type = *it;
AstType* intersect_type = T.Intersect(type, type);
CheckEqual(intersect_type, type);
}
// Commutativity: Intersect(T1, T2) = Intersect(T2, T1)
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* intersect12 = T.Intersect(type1, type2);
AstType* intersect21 = T.Intersect(type2, type1);
CheckEqual(intersect12, intersect21);
}
}
// Associativity:
// Intersect(T1, Intersect(T2, T3)) = Intersect(Intersect(T1, T2), T3)
// This does NOT hold. For example:
// (Class(..stringy1..) /\ Class(..stringy2..)) /\ Constant(..string..) =
// None
// Class(..stringy1..) /\ (Class(..stringy2..) /\ Constant(..string..)) =
// Constant(..string..)
/*
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
AstType* intersect12 = T.Intersect(type1, type2);
AstType* intersect23 = T.Intersect(type2, type3);
AstType* intersect1_23 = T.Intersect(type1, intersect23);
AstType* intersect12_3 = T.Intersect(intersect12, type3);
CheckEqual(intersect1_23, intersect12_3);
}
}
}
*/
// Join: Intersect(T1, T2)->Is(T1) and Intersect(T1, T2)->Is(T2)
// This does NOT hold. For example:
// Class(..stringy..) /\ Constant(..string..) = Constant(..string..)
// Currently, not even the disjunction holds:
// Class(Internal/TaggedPtr) /\ (Any/Untagged \/ Context(..)) =
// Class(Internal/TaggedPtr) \/ Context(..)
/*
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* intersect12 = T.Intersect(type1, type2);
CHECK(intersect12->Is(type1));
CHECK(intersect12->Is(type2));
}
}
*/
// Lower Boundedness: T1->Is(T2) implies Intersect(T1, T2) = T1
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* intersect12 = T.Intersect(type1, type2);
if (type1->Is(type2)) CheckEqual(intersect12, type1);
}
}
// Monotonicity: T1->Is(T2) implies Intersect(T1, T3)->Is(Intersect(T2, T3))
// This does NOT hold. For example:
// Class(OtherObject/TaggedPtr) <= Any/TaggedPtr
// Class(OtherObject/TaggedPtr) /\ Any/UntaggedInt1 = Class(..)
// Any/TaggedPtr /\ Any/UntaggedInt1 = None
/*
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
AstType* intersect13 = T.Intersect(type1, type3);
AstType* intersect23 = T.Intersect(type2, type3);
CHECK(!type1->Is(type2) || intersect13->Is(intersect23));
}
}
}
*/
// Monotonicity: T1->Is(T3) or T2->Is(T3) implies Intersect(T1, T2)->Is(T3)
// This does NOT hold. For example:
// Class(..stringy..) <= Class(..stringy..)
// Class(..stringy..) /\ Constant(..string..) = Constant(..string..)
// Constant(..string..) </= Class(..stringy..)
/*
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
AstType* intersect12 = T.Intersect(type1, type2);
CHECK(!(type1->Is(type3) || type2->Is(type3)) ||
intersect12->Is(type3));
}
}
}
*/
// Monotonicity: T1->Is(T2) and T1->Is(T3) implies T1->Is(Intersect(T2, T3))
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
HandleScope scope(isolate);
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
AstType* intersect23 = T.Intersect(type2, type3);
CHECK(!(type1->Is(type2) && type1->Is(type3)) ||
type1->Is(intersect23));
}
}
}
// Bitset-class
CheckEqual(T.Intersect(T.ObjectClass, T.Object), T.ObjectClass);
CheckEqual(T.Semantic(T.Intersect(T.ObjectClass, T.Number)), T.None);
// Bitset-array
CheckEqual(T.Intersect(T.NumberArray, T.Object), T.NumberArray);
CheckEqual(T.Semantic(T.Intersect(T.AnyArray, T.Proxy)), T.None);
// Bitset-function
CheckEqual(T.Intersect(T.MethodFunction, T.Object), T.MethodFunction);
CheckEqual(T.Semantic(T.Intersect(T.NumberFunction1, T.Proxy)), T.None);
// Bitset-union
CheckEqual(T.Intersect(T.Object, T.Union(T.ObjectConstant1, T.ObjectClass)),
T.Union(T.ObjectConstant1, T.ObjectClass));
CheckEqual(T.Semantic(T.Intersect(T.Union(T.ArrayClass, T.ObjectConstant1),
T.Number)),
T.None);
// Class-constant
CHECK(T.Intersect(T.ObjectConstant1, T.ObjectClass)->IsInhabited()); // !!!
CHECK(T.Intersect(T.ArrayClass, T.ObjectConstant2)->IsInhabited());
// Array-union
CheckEqual(T.Intersect(T.NumberArray, T.Union(T.NumberArray, T.ArrayClass)),
T.NumberArray);
CheckEqual(T.Intersect(T.AnyArray, T.Union(T.Object, T.SmiConstant)),
T.AnyArray);
CHECK(!T.Intersect(T.Union(T.AnyArray, T.ArrayConstant), T.NumberArray)
->IsInhabited());
// Function-union
CheckEqual(
T.Intersect(T.MethodFunction, T.Union(T.String, T.MethodFunction)),
T.MethodFunction);
CheckEqual(T.Intersect(T.NumberFunction1, T.Union(T.Object, T.SmiConstant)),
T.NumberFunction1);
CHECK(!T.Intersect(T.Union(T.MethodFunction, T.Name), T.NumberFunction2)
->IsInhabited());
// Class-union
CheckEqual(
T.Intersect(T.ArrayClass, T.Union(T.ObjectConstant2, T.ArrayClass)),
T.ArrayClass);
CheckEqual(T.Intersect(T.ArrayClass, T.Union(T.Object, T.SmiConstant)),
T.ArrayClass);
CHECK(T.Intersect(T.Union(T.ObjectClass, T.ArrayConstant), T.ArrayClass)
->IsInhabited()); // !!!
// Constant-union
CheckEqual(T.Intersect(T.ObjectConstant1,
T.Union(T.ObjectConstant1, T.ObjectConstant2)),
T.ObjectConstant1);
CheckEqual(T.Intersect(T.SmiConstant, T.Union(T.Number, T.ObjectConstant2)),
T.SmiConstant);
CHECK(
T.Intersect(T.Union(T.ArrayConstant, T.ObjectClass), T.ObjectConstant1)
->IsInhabited()); // !!!
// Union-union
CheckEqual(T.Intersect(T.Union(T.Number, T.ArrayClass),
T.Union(T.SignedSmall, T.Receiver)),
T.Union(T.SignedSmall, T.ArrayClass));
CheckEqual(T.Intersect(T.Union(T.Number, T.ObjectClass),
T.Union(T.Signed32, T.OtherObject)),
T.Union(T.Signed32, T.ObjectClass));
CheckEqual(T.Intersect(T.Union(T.ObjectConstant2, T.ObjectConstant1),
T.Union(T.ObjectConstant1, T.ObjectConstant2)),
T.Union(T.ObjectConstant2, T.ObjectConstant1));
CheckEqual(
T.Intersect(T.Union(T.ArrayClass,
T.Union(T.ObjectConstant2, T.ObjectConstant1)),
T.Union(T.ObjectConstant1,
T.Union(T.ArrayConstant, T.ObjectConstant2))),
T.Union(T.ArrayConstant,
T.Union(T.ObjectConstant2, T.ObjectConstant1))); // !!!
}
void Distributivity() {
// Union(T1, Intersect(T2, T3)) = Intersect(Union(T1, T2), Union(T1, T3))
// This does NOT hold. For example:
// Untagged \/ (Untagged /\ Class(../Tagged)) = Untagged \/ Class(../Tagged)
// (Untagged \/ Untagged) /\ (Untagged \/ Class(../Tagged)) =
// Untagged /\ (Untagged \/ Class(../Tagged)) = Untagged
// because Untagged <= Untagged \/ Class(../Tagged)
/*
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
AstType* union12 = T.Union(type1, type2);
AstType* union13 = T.Union(type1, type3);
AstType* intersect23 = T.Intersect(type2, type3);
AstType* union1_23 = T.Union(type1, intersect23);
AstType* intersect12_13 = T.Intersect(union12, union13);
CHECK(Equal(union1_23, intersect12_13));
}
}
}
*/
// Intersect(T1, Union(T2, T3)) = Union(Intersect(T1, T2), Intersect(T1,T3))
// This does NOT hold. For example:
// Untagged /\ (Untagged \/ Class(../Tagged)) = Untagged
// (Untagged /\ Untagged) \/ (Untagged /\ Class(../Tagged)) =
// Untagged \/ Class(../Tagged)
/*
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
for (TypeIterator it3 = T.types.begin(); it3 != T.types.end(); ++it3) {
AstType* type1 = *it1;
AstType* type2 = *it2;
AstType* type3 = *it3;
AstType* intersect12 = T.Intersect(type1, type2);
AstType* intersect13 = T.Intersect(type1, type3);
AstType* union23 = T.Union(type2, type3);
AstType* intersect1_23 = T.Intersect(type1, union23);
AstType* union12_13 = T.Union(intersect12, intersect13);
CHECK(Equal(intersect1_23, union12_13));
}
}
}
*/
}
void GetRange() {
// GetRange(Range(a, b)) = Range(a, b).
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
AstType* type1 = *it1;
if (type1->IsRange()) {
AstRangeType* range = type1->GetRange()->AsRange();
CHECK(type1->Min() == range->Min());
CHECK(type1->Max() == range->Max());
}
}
// GetRange(Union(Constant(x), Range(min,max))) == Range(min, max).
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
if (type1->IsConstant() && type2->IsRange()) {
AstType* u = T.Union(type1, type2);
CHECK(type2->Min() == u->GetRange()->Min());
CHECK(type2->Max() == u->GetRange()->Max());
}
}
}
}
void HTypeFromType() {
for (TypeIterator it1 = T.types.begin(); it1 != T.types.end(); ++it1) {
for (TypeIterator it2 = T.types.begin(); it2 != T.types.end(); ++it2) {
AstType* type1 = *it1;
AstType* type2 = *it2;
HType htype1 = HType::FromType(type1);
HType htype2 = HType::FromType(type2);
CHECK(!type1->Is(type2) || htype1.IsSubtypeOf(htype2));
}
}
}
};
} // namespace
TEST(AstIsSomeType_zone) { Tests().IsSomeType(); }
TEST(AstPointwiseRepresentation_zone) { Tests().PointwiseRepresentation(); }
TEST(AstBitsetType_zone) { Tests().Bitset(); }
TEST(AstClassType_zone) { Tests().Class(); }
TEST(AstConstantType_zone) { Tests().Constant(); }
TEST(AstRangeType_zone) { Tests().Range(); }
TEST(AstArrayType_zone) { Tests().Array(); }
TEST(AstFunctionType_zone) { Tests().Function(); }
TEST(AstOf_zone) { Tests().Of(); }
TEST(AstNowOf_zone) { Tests().NowOf(); }
TEST(AstMinMax_zone) { Tests().MinMax(); }
TEST(AstBitsetGlb_zone) { Tests().BitsetGlb(); }
TEST(AstBitsetLub_zone) { Tests().BitsetLub(); }
TEST(AstIs1_zone) { Tests().Is1(); }
TEST(AstIs2_zone) { Tests().Is2(); }
TEST(AstNowIs_zone) { Tests().NowIs(); }
TEST(AstContains_zone) { Tests().Contains(); }
TEST(AstNowContains_zone) { Tests().NowContains(); }
TEST(AstMaybe_zone) { Tests().Maybe(); }
TEST(AstUnion1_zone) { Tests().Union1(); }
TEST(AstUnion2_zone) { Tests().Union2(); }
TEST(AstUnion3_zone) { Tests().Union3(); }
TEST(AstUnion4_zone) { Tests().Union4(); }
TEST(AstIntersect_zone) { Tests().Intersect(); }
TEST(AstDistributivity_zone) { Tests().Distributivity(); }
TEST(AstGetRange_zone) { Tests().GetRange(); }
TEST(AstHTypeFromType_zone) { Tests().HTypeFromType(); }
| 39.181627 | 80 | 0.58295 | [
"object",
"vector"
] |
a19df53ed360f0eff464bd1dc63eb914fd841b12 | 1,268 | cpp | C++ | UVA/vol-106/10625.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | 3 | 2017-05-12T14:45:37.000Z | 2020-01-18T16:51:25.000Z | UVA/vol-106/10625.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | null | null | null | UVA/vol-106/10625.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct CharCount {
char ch;
int cnt;
CharCount(char ch, int cnt):ch(ch),cnt(cnt){}
};
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);
char ch;
string str;
int T, n, r;
cin >> T;
while (T-- && cin>>n) {
vector<CharCount> rules[127];
for (int i=0; i<n; ++i) {
cin >> str;
int C[127] = {};
for (int j=3; str[j]; ++j)
++C[str[j]];
vector<CharCount> &v = rules[str[0]];
for (int i=0; i<127; ++i) if (C[i])
v.push_back(CharCount(i, C[i]));
}
cin >> n;
while (n--) {
unsigned long long C[127] = {}, CT[127] = {};
cin >> str >> ch >> r;
for (int i=0; str[i]; ++i)
++C[str[i]];
while (r--) {
for (char ch=33; ch<127; ++ch) {
if (rules[ch].size())
for (const CharCount &cc: rules[ch])
CT[cc.ch] += C[ch]*cc.cnt;
else CT[ch] += C[ch];
C[ch] = 0;
}
swap(CT, C);
}
cout << C[ch] << "\n";
}
}
}
| 24.384615 | 60 | 0.364353 | [
"vector"
] |
a1a0f6fbd63645a22bdec6ab0265cd1066dea00f | 1,822 | cpp | C++ | TestWrapper.cpp | talibe84/JOSHI | 1cda3c49f131eff3f6eccf3979ce44ec1466aa43 | [
"CECILL-B"
] | null | null | null | TestWrapper.cpp | talibe84/JOSHI | 1cda3c49f131eff3f6eccf3979ce44ec1466aa43 | [
"CECILL-B"
] | null | null | null | TestWrapper.cpp | talibe84/JOSHI | 1cda3c49f131eff3f6eccf3979ce44ec1466aa43 | [
"CECILL-B"
] | null | null | null | // TestWrapper.cpp
//
// Testing heterogeneous properties
//
// (C) Datasim Education BV 2006
//
#include "datasimdate.hpp" // Dates and other useful stuff
#include "datetime.hpp"
#include <string> // Standard string class in C++
#include "Wrapper.cpp"
#include "SimplePropertySet.cpp"
using namespace std;
class Person
{
public: // Everything public, for convenience only
// Data
Wrapper<string> nam; // Name of person
Wrapper<DatasimDate> dob; // Date of birth
Wrapper<DatasimDate> createdD; // Internal, when object was created
SimplePropertySet<string, AnyType*> props;
public:
Person (const string& name, const DatasimDate& DateofBirth)
{
nam = name;
dob = DateofBirth;
createdD = DatasimDate(); // default, today REALLY!
// Now add this stuff into the property set
props = SimplePropertySet<string, AnyType*>();
props.add(string("Name"), &nam);
props.add(string("DOB"), &dob);
props.add(string("CreatedDate"), &createdD);
}
void print() const
{ // Who am I?
cout << "\n** Person Data **\n";
SimplePropertySet<string, AnyType*>::const_iterator it;
for (it = props.Begin(); it != props.End(); it++)
{
cout << "Key " << it ->first << endl;
// No value printed because we lack polymorphism in
// general
}
}
};
int main()
{
DatasimDate myBirthday(29, 8, 1952);
string myName ("Daniel J. Duffy");
Person dd(myName, myBirthday);
dd.print();
DatasimDate bBirthday(06, 8, 1994);
string bName ("Brendan Duffy");
Person bd(bName, bBirthday);
bd.print();
Wrapper<string> w1;
Wrapper<string> w2;
if (w1.sameType(w2) == true)
{
cout << "Same type\n";
}
else
{
cout << "Not Same type\n";
}
return 0;
}
| 20.021978 | 72 | 0.612514 | [
"object"
] |
a1a456fbfb7ffd7943a2d6a2aaf6c24d1a97a5f0 | 1,087 | cpp | C++ | tests/ibm/ibm/test_storage_wrapper.cpp | mfournial/Faasm | f6c48b8b38b78c1b14a7b5557f3bccad9d4424ae | [
"Apache-2.0"
] | 1 | 2020-04-21T07:33:42.000Z | 2020-04-21T07:33:42.000Z | tests/ibm/ibm/test_storage_wrapper.cpp | mfournial/Faasm | f6c48b8b38b78c1b14a7b5557f3bccad9d4424ae | [
"Apache-2.0"
] | 4 | 2020-02-03T18:54:32.000Z | 2020-05-13T18:28:28.000Z | tests/ibm/ibm/test_storage_wrapper.cpp | mfournial/Faasm | f6c48b8b38b78c1b14a7b5557f3bccad9d4424ae | [
"Apache-2.0"
] | null | null | null | #include <catch/catch.hpp>
#include <storage/IBMStorageWrapper.h>
#include <util/config.h>
using namespace storage;
namespace tests {
TEST_CASE("Test authentication", "[ibm]") {
util::SystemConfig &conf = util::getSystemConfig();
IBMStorageWrapper wrapper(conf.ibmApiKey);
const std::string &actual = wrapper.getAuthToken();
REQUIRE(!actual.empty());
}
TEST_CASE("Test read/write keys in bucket", "[ibm]") {
util::SystemConfig &conf = util::getSystemConfig();
IBMStorageWrapper wrapper(conf.ibmApiKey);
std::vector<uint8_t> byteDataA = {0, 1, 2, 3, 'c', '\\', '@', '$', '%'};
std::vector<uint8_t> byteDataB = {11, 99, 123, '#', '\n', '\t'};
SECTION("Test bytes read/ write") {
wrapper.addKeyBytes(conf.bucketName, "alpha", byteDataA);
wrapper.addKeyBytes(conf.bucketName, "beta", byteDataB);
REQUIRE(wrapper.getKeyBytes(conf.bucketName, "alpha") == byteDataA);
REQUIRE(wrapper.getKeyBytes(conf.bucketName, "beta") == byteDataB);
}
}
} | 32.939394 | 80 | 0.612695 | [
"vector"
] |
a1a6e5da2257b776def941a9b23216dc11d0b4c2 | 1,337 | cpp | C++ | Mavn/ResourceAllocation.cpp | rajko-z/mahl-compiler | c417de8546c40524f09a9de67ecd5786f2199669 | [
"MIT"
] | null | null | null | Mavn/ResourceAllocation.cpp | rajko-z/mahl-compiler | c417de8546c40524f09a9de67ecd5786f2199669 | [
"MIT"
] | null | null | null | Mavn/ResourceAllocation.cpp | rajko-z/mahl-compiler | c417de8546c40524f09a9de67ecd5786f2199669 | [
"MIT"
] | null | null | null | #include "ResourceAllocation.h"
#include "InterferenceGraph.h"
#include "Constants.h"
#include "Utils.h"
#include <set>
#include <vector>
using namespace std;
bool doResourceAllocation(SimplificationStack& simplificationStack, InterferenceGraph& ig)
{
while (!simplificationStack.empty())
{
Variable* var = simplificationStack.top();
simplificationStack.pop();
std::set<Regs> colored;
for (Variable* var2 : *(ig.variables))
{
if (ig.matrix[var->getPosition()][var2->getPosition()] == __INTERFERENCE__)
{
if (var2->getReg() != Regs::no_assign)
{
colored.insert(var2->getReg());
}
}
}
bool success = false;
for (int r = 0; r < __REG_NUMBER__; ++r)
{
Regs reg = static_cast<Regs>(r);
if (colored.find(reg) == colored.end())
{
var->setReg(reg);
success = true;
break;
}
}
if (!success)
return false;
}
return true;
}
void changeRegsNameWithNewAllocation(Program& program)
{
Instructions& instructions = program.getInstructions();
for (Instruction* inst : instructions)
{
for (Variable* v : inst->getSrc())
{
if (v->getType() == Variable::REG_VAR)
v->setName(getNameForRegister(v->getReg()));
}
for (Variable* v : inst->getDst())
{
if (v->getType() == Variable::REG_VAR)
v->setName(getNameForRegister(v->getReg()));
}
}
}
| 19.661765 | 90 | 0.646223 | [
"vector"
] |
a1a8823d2edf8dd4dcda7a982eb08b3e0596a1b5 | 1,336 | cpp | C++ | July LeetCode Challenge/Day_18.cpp | mishrraG/100DaysOfCode | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 13 | 2020-08-10T14:06:37.000Z | 2020-09-24T14:21:33.000Z | July LeetCode Challenge/Day_18.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | null | null | null | July LeetCode Challenge/Day_18.cpp | mishrraG/DaysOfCP | 3358af290d4f05889917808d68b95f37bd76e698 | [
"MIT"
] | 1 | 2020-05-31T21:09:14.000Z | 2020-05-31T21:09:14.000Z | class Solution {
public:
bool impossible;
void dfs(vector<vector<int>>&map1, int i, vector<bool>&visited, vector<int>&donecourse) {
if (visited[i]) {
impossible = true;
return;
}
visited[i] = true;
if (map1[i].size() == 0) {
donecourse.push_back(i);
return;
}
else {
for (auto it = map1[i].begin(); it != map1[i].end(); it++) {
if (find(donecourse.begin(), donecourse.end(), *it) != donecourse.end())
continue;
else {
dfs(map1, *it, visited, donecourse);
if (impossible) return;
}
}
donecourse.push_back(i);
}
}
vector<int> findOrder(int numCourses, vector<vector<int>>& courses) {
impossible = false;
vector<vector<int>>v(numCourses);
vector<int>donecourse;
vector<bool>visited(numCourses, false);
for (auto it : courses) {
v[it[0]].push_back(it[1]);
}
for (int i = 0; i < numCourses; i++) {
if (!visited[i])
dfs(v, i, visited, donecourse);
}
if (impossible) {
vector<int>ans;
return ans;
}
return donecourse;
}
}; | 29.688889 | 93 | 0.461826 | [
"vector"
] |
a1a918fe8527b7432b445fe87cbc59d67cd6a2d6 | 7,495 | cc | C++ | chrome/browser/ui/ash/vpn_list_forwarder.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/ui/ash/vpn_list_forwarder.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/ui/ash/vpn_list_forwarder.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/ash/vpn_list_forwarder.h"
#include "ash/public/interfaces/constants.mojom.h"
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "components/user_manager/user.h"
#include "components/user_manager/user_manager.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/common/service_manager_connection.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_set.h"
#include "extensions/common/permissions/api_permission.h"
#include "extensions/common/permissions/permissions_data.h"
#include "services/service_manager/public/cpp/connector.h"
namespace mojo {
template <>
struct TypeConverter<ash::mojom::ArcVpnProviderPtr,
app_list::ArcVpnProviderManager::ArcVpnProvider*> {
static ash::mojom::ArcVpnProviderPtr Convert(
const app_list::ArcVpnProviderManager::ArcVpnProvider* input) {
auto result = ash::mojom::ArcVpnProvider::New();
result->app_name = input->app_name;
result->package_name = input->package_name;
result->app_id = input->app_id;
result->last_launch_time = input->last_launch_time;
return result;
}
};
} // namespace mojo
namespace {
bool IsVPNProvider(const extensions::Extension* extension) {
return extension->permissions_data()->HasAPIPermission(
extensions::APIPermission::kVpnProvider);
}
Profile* GetProfileForPrimaryUser() {
const user_manager::User* const primary_user =
user_manager::UserManager::Get()->GetPrimaryUser();
if (!primary_user)
return nullptr;
return chromeos::ProfileHelper::Get()->GetProfileByUser(primary_user);
}
// Connects to the VpnList mojo interface in ash.
ash::mojom::VpnListPtr ConnectToVpnList() {
ash::mojom::VpnListPtr vpn_list;
content::ServiceManagerConnection::GetForProcess()
->GetConnector()
->BindInterface(ash::mojom::kServiceName, &vpn_list);
return vpn_list;
}
} // namespace
VpnListForwarder::VpnListForwarder() : weak_factory_(this) {
if (user_manager::UserManager::Get()->GetPrimaryUser()) {
// If a user is logged in, start observing the primary user's extension
// registry immediately.
AttachToPrimaryUserProfile();
} else {
// If no user is logged in, wait until the first user logs in (thus becoming
// the primary user) and a profile is created for that user.
registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED,
content::NotificationService::AllSources());
}
}
VpnListForwarder::~VpnListForwarder() {
if (extension_registry_)
extension_registry_->RemoveObserver(this);
if (arc_vpn_provider_manager_)
arc_vpn_provider_manager_->RemoveObserver(this);
vpn_list_ = nullptr;
}
void VpnListForwarder::OnArcVpnProvidersRefreshed(
const std::vector<
std::unique_ptr<app_list::ArcVpnProviderManager::ArcVpnProvider>>&
arc_vpn_providers) {
std::vector<ash::mojom::ArcVpnProviderPtr> arc_vpn_provider_ptrs;
for (const auto& arc_vpn_provider : arc_vpn_providers) {
arc_vpn_provider_ptrs.emplace_back(
ash::mojom::ArcVpnProvider::From(arc_vpn_provider.get()));
}
vpn_list_->SetArcVpnProviders(std::move(arc_vpn_provider_ptrs));
}
void VpnListForwarder::OnArcVpnProviderUpdated(
app_list::ArcVpnProviderManager::ArcVpnProvider* arc_vpn_provider) {
vpn_list_->AddOrUpdateArcVPNProvider(
ash::mojom::ArcVpnProvider::From(arc_vpn_provider));
}
void VpnListForwarder::OnArcVpnProviderRemoved(
const std::string& package_name) {
vpn_list_->RemoveArcVPNProvider(package_name);
}
void VpnListForwarder::OnExtensionLoaded(
content::BrowserContext* browser_context,
const extensions::Extension* extension) {
if (IsVPNProvider(extension))
UpdateVPNProviders();
}
void VpnListForwarder::OnExtensionUnloaded(
content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionReason reason) {
if (IsVPNProvider(extension))
UpdateVPNProviders();
}
void VpnListForwarder::OnShutdown(extensions::ExtensionRegistry* registry) {
DCHECK(extension_registry_);
extension_registry_->RemoveObserver(this);
extension_registry_ = nullptr;
}
void VpnListForwarder::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
DCHECK_EQ(chrome::NOTIFICATION_PROFILE_CREATED, type);
const Profile* const profile = content::Source<Profile>(source).ptr();
if (!chromeos::ProfileHelper::Get()->IsPrimaryProfile(profile)) {
// If the profile that was just created does not belong to the primary user
// (e.g. login profile), ignore it.
return;
}
// The first user logged in (thus becoming the primary user) and a profile was
// created for that user. Stop observing profile creation. Wait one message
// loop cycle to allow other code which observes the
// chrome::NOTIFICATION_PROFILE_CREATED notification to finish initializing
// the profile, then start observing the primary user's extension registry.
registrar_.RemoveAll();
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&VpnListForwarder::AttachToPrimaryUserProfile,
weak_factory_.GetWeakPtr()));
}
void VpnListForwarder::UpdateVPNProviders() {
DCHECK(extension_registry_);
std::vector<ash::mojom::ThirdPartyVpnProviderPtr> third_party_providers;
for (const auto& extension : extension_registry_->enabled_extensions()) {
if (!IsVPNProvider(extension.get()))
continue;
ash::mojom::ThirdPartyVpnProviderPtr provider =
ash::mojom::ThirdPartyVpnProvider::New();
provider->name = extension->name();
provider->extension_id = extension->id();
third_party_providers.push_back(std::move(provider));
}
// Ash starts without any third-party providers. If we've never sent one then
// there's no need to send an empty list. This case commonly occurs on startup
// when the user has no third-party VPN extensions installed.
if (!sent_providers_ && third_party_providers.empty())
return;
vpn_list_->SetThirdPartyVpnProviders(std::move(third_party_providers));
sent_providers_ = true;
}
void VpnListForwarder::AttachToPrimaryUserProfile() {
DCHECK(!vpn_list_);
vpn_list_ = ConnectToVpnList();
DCHECK(vpn_list_);
AttachToPrimaryUserExtensionRegistry();
AttachToPrimaryUserArcVpnProviderManager();
}
void VpnListForwarder::AttachToPrimaryUserExtensionRegistry() {
DCHECK(!extension_registry_);
extension_registry_ =
extensions::ExtensionRegistry::Get(GetProfileForPrimaryUser());
extension_registry_->AddObserver(this);
UpdateVPNProviders();
}
void VpnListForwarder::AttachToPrimaryUserArcVpnProviderManager() {
arc_vpn_provider_manager_ =
app_list::ArcVpnProviderManager::Get(GetProfileForPrimaryUser());
if (arc_vpn_provider_manager_)
arc_vpn_provider_manager_->AddObserver(this);
}
| 35.861244 | 80 | 0.750767 | [
"vector"
] |
a1abd536dfa5524cb2a61d80aa5ccb971d107107 | 7,157 | cpp | C++ | tests/unit/testreleasemonitor.cpp | abpostelnicu/mozilla-vpn-client | 8401aa3eb4b579b06cf88a765a7a4c32d10e0bbb | [
"MIT"
] | 1 | 2021-06-19T04:01:54.000Z | 2021-06-19T04:01:54.000Z | tests/unit/testreleasemonitor.cpp | abpostelnicu/mozilla-vpn-client | 8401aa3eb4b579b06cf88a765a7a4c32d10e0bbb | [
"MIT"
] | 2 | 2020-11-29T13:51:47.000Z | 2020-12-01T07:29:09.000Z | tests/unit/testreleasemonitor.cpp | abpostelnicu/mozilla-vpn-client | 8401aa3eb4b579b06cf88a765a7a4c32d10e0bbb | [
"MIT"
] | null | null | null | /* 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 "testreleasemonitor.h"
#include "../../src/releasemonitor.h"
#include "../../src/update/versionapi.h"
#include "helper.h"
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
void TestReleaseMonitor::failure() {
ReleaseMonitor rm;
rm.runSoon();
TestHelper::networkConfig.append(TestHelper::NetworkConfig(
TestHelper::NetworkConfig::Failure, QByteArray()));
QEventLoop loop;
connect(&rm, &ReleaseMonitor::releaseChecked, [&] { loop.exit(); });
loop.exec();
}
void TestReleaseMonitor::success_data() {
QTest::addColumn<QByteArray>("json");
QTest::addColumn<bool>("result");
QTest::addRow("empty") << QByteArray("") << false;
QJsonObject obj;
QTest::addRow("empty object") << QJsonDocument(obj).toJson() << false;
QJsonValue value(42);
obj.insert("linux", value);
obj.insert("ios", value);
obj.insert("macos", value);
obj.insert("dummy", value);
QTest::addRow("invalid platform") << QJsonDocument(obj).toJson() << false;
QJsonObject platform;
obj.insert("linux", platform);
obj.insert("ios", platform);
obj.insert("macos", platform);
obj.insert("dummy", platform);
QTest::addRow("empty platform") << QJsonDocument(obj).toJson() << false;
QJsonObject latest;
platform.insert("latest", latest);
obj.insert("linux", platform);
obj.insert("ios", platform);
obj.insert("macos", platform);
obj.insert("dummy", platform);
QTest::addRow("empty latest") << QJsonDocument(obj).toJson() << false;
latest.insert("version", 42);
platform.insert("latest", latest);
obj.insert("linux", platform);
obj.insert("ios", platform);
obj.insert("macos", platform);
obj.insert("dummy", platform);
QTest::addRow("invalid latest version")
<< QJsonDocument(obj).toJson() << false;
latest.insert("version", "42");
platform.insert("latest", latest);
obj.insert("linux", platform);
obj.insert("ios", platform);
obj.insert("macos", platform);
obj.insert("dummy", platform);
QTest::addRow("missing minimum") << QJsonDocument(obj).toJson() << false;
QJsonObject minimum;
minimum.insert("version", 42);
platform.insert("minimum", minimum);
obj.insert("linux", platform);
obj.insert("ios", platform);
obj.insert("macos", platform);
obj.insert("dummy", platform);
QTest::addRow("invalid minimum version")
<< QJsonDocument(obj).toJson() << false;
minimum.insert("version", "42");
platform.insert("minimum", minimum);
obj.insert("linux", platform);
obj.insert("ios", platform);
obj.insert("macos", platform);
obj.insert("dummy", platform);
QTest::addRow("all good") << QJsonDocument(obj).toJson() << true;
minimum.insert("version", "9999");
platform.insert("minimum", minimum);
obj.insert("linux", platform);
obj.insert("ios", platform);
obj.insert("macos", platform);
obj.insert("dummy", platform);
QTest::addRow("completed!") << QJsonDocument(obj).toJson() << true;
}
void TestReleaseMonitor::success() {
ReleaseMonitor rm;
rm.runSoon();
QFETCH(QByteArray, json);
TestHelper::networkConfig.append(
TestHelper::NetworkConfig(TestHelper::NetworkConfig::Success, json));
QEventLoop loop;
connect(&rm, &ReleaseMonitor::releaseChecked, [&] { loop.exit(); });
loop.exec();
}
void TestReleaseMonitor::compareVersions_data() {
QTest::addColumn<QString>("a");
QTest::addColumn<QString>("b");
QTest::addColumn<int>("result");
QTest::addRow("empty a") << ""
<< "123" << 1;
QTest::addRow("empty b") << "123"
<< "" << -1;
QTest::addRow("empty all") << ""
<< "" << 0;
QTest::addRow("equal 1") << "0.1"
<< "0.1" << 0;
QTest::addRow("equal 2") << "0.1.2"
<< "0.1.2" << 0;
QTest::addRow("equal 3") << "0.1.2.3"
<< "0.1.2.3" << 0;
QTest::addRow("equal 4") << "0"
<< "0" << 0;
QTest::addRow("equal 5") << "123"
<< "123" << 0;
QTest::addRow("euqal 6") << "0.1.2.123"
<< "0.1.2.456" << 0;
QTest::addRow("a wins 1") << "0"
<< "123" << -1;
QTest::addRow("a wins 2") << "0.1"
<< "123" << -1;
QTest::addRow("a wins 3") << "0.1.2"
<< "123" << -1;
QTest::addRow("a wins 4") << "0.1.2.3"
<< "123" << -1;
QTest::addRow("a wins 5") << "0.1.2.3.4"
<< "123" << -1;
QTest::addRow("a wins 6") << "1.2.3.4"
<< "123" << -1;
QTest::addRow("a wins 7") << "0"
<< "1" << -1;
QTest::addRow("a wins 8") << "0"
<< "0.1" << -1;
QTest::addRow("a wins 9") << "0"
<< "0.1.2" << -1;
QTest::addRow("a wins A") << "0"
<< "0.1.2.3" << -1;
QTest::addRow("a wins B") << "0.1"
<< "1" << -1;
QTest::addRow("a wins C") << "0.1"
<< "0.2" << -1;
QTest::addRow("a wins D") << "0.1"
<< "0.1.2" << -1;
QTest::addRow("a wins E") << "0.1.2"
<< "1" << -1;
QTest::addRow("a wins F") << "0.1.2"
<< "0.2" << -1;
QTest::addRow("a wins 10") << "0.1.2"
<< "0.1.3" << -1;
QTest::addRow("b wins 1") << "123"
<< "0" << 1;
QTest::addRow("b wins 2") << "123"
<< "0.1" << 1;
QTest::addRow("b wins 3") << "123"
<< "0.1.2" << 1;
QTest::addRow("b wins 4") << "123"
<< "0.1.2.3" << 1;
QTest::addRow("b wins 5") << "123"
<< "0.1.2.3.4" << 1;
QTest::addRow("b wins 6") << "123"
<< "1.2.3.4" << 1;
QTest::addRow("b wins 7") << "1"
<< "0" << 1;
QTest::addRow("b wins 8") << "0.1"
<< "0" << 1;
QTest::addRow("b wins 9") << "0.1.2"
<< "0" << 1;
QTest::addRow("b wins A") << "0.1.2.3"
<< "0" << 1;
QTest::addRow("b wins B") << "1"
<< "0.1" << 1;
QTest::addRow("b wins C") << "0.2"
<< "0.1" << 1;
QTest::addRow("b wins D") << "0.1.2"
<< "0.1" << 1;
QTest::addRow("b wins E") << "1"
<< "0.1.2" << 1;
QTest::addRow("b wins F") << "0.2"
<< "0.1.2" << 1;
QTest::addRow("b wins 10") << "0.1.3"
<< "0.1.2" << 1;
}
void TestReleaseMonitor::compareVersions() {
QFETCH(QString, a);
QFETCH(QString, b);
QFETCH(int, result);
QCOMPARE(VersionApi::compareVersions(a, b), result);
}
static TestReleaseMonitor s_testReleaseMonitor;
| 33.288372 | 76 | 0.497275 | [
"object"
] |
a1aee7a85d4d2ce16f9f3da7e13dfe9bd6f99064 | 16,006 | cpp | C++ | third_party/WebKit/Source/core/inspector/ThreadDebugger.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2019-01-28T08:09:58.000Z | 2021-11-15T15:32:10.000Z | third_party/WebKit/Source/core/inspector/ThreadDebugger.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/inspector/ThreadDebugger.cpp | Wzzzx/chromium-crosswalk | 768dde8efa71169f1c1113ca6ef322f1e8c9e7de | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 6 | 2020-09-23T08:56:12.000Z | 2021-11-18T03:40:49.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/inspector/ThreadDebugger.h"
#include "bindings/core/v8/ScriptValue.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8DOMException.h"
#include "bindings/core/v8/V8DOMTokenList.h"
#include "bindings/core/v8/V8Event.h"
#include "bindings/core/v8/V8EventListener.h"
#include "bindings/core/v8/V8EventListenerInfo.h"
#include "bindings/core/v8/V8EventListenerList.h"
#include "bindings/core/v8/V8HTMLAllCollection.h"
#include "bindings/core/v8/V8HTMLCollection.h"
#include "bindings/core/v8/V8Node.h"
#include "bindings/core/v8/V8NodeList.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/inspector/InspectorDOMDebuggerAgent.h"
#include "core/inspector/InspectorTraceEvents.h"
#include "platform/ScriptForbiddenScope.h"
#include "wtf/CurrentTime.h"
#include "wtf/PtrUtil.h"
#include <memory>
namespace blink {
ThreadDebugger::ThreadDebugger(v8::Isolate* isolate)
: m_isolate(isolate)
, m_debugger(V8Debugger::create(isolate, this))
, m_asyncInstrumentationEnabled(false)
{
}
ThreadDebugger::~ThreadDebugger()
{
}
// static
ThreadDebugger* ThreadDebugger::from(v8::Isolate* isolate)
{
if (!isolate)
return nullptr;
V8PerIsolateData* data = V8PerIsolateData::from(isolate);
return data ? data->threadDebugger() : nullptr;
}
void ThreadDebugger::willExecuteScript(v8::Isolate* isolate, int scriptId)
{
if (ThreadDebugger* debugger = ThreadDebugger::from(isolate))
debugger->debugger()->willExecuteScript(isolate->GetCurrentContext(), scriptId);
}
void ThreadDebugger::didExecuteScript(v8::Isolate* isolate)
{
if (ThreadDebugger* debugger = ThreadDebugger::from(isolate))
debugger->debugger()->didExecuteScript(isolate->GetCurrentContext());
}
void ThreadDebugger::idleStarted(v8::Isolate* isolate)
{
if (ThreadDebugger* debugger = ThreadDebugger::from(isolate))
debugger->debugger()->idleStarted();
}
void ThreadDebugger::idleFinished(v8::Isolate* isolate)
{
if (ThreadDebugger* debugger = ThreadDebugger::from(isolate))
debugger->debugger()->idleFinished();
}
void ThreadDebugger::asyncTaskScheduled(const String& operationName, void* task, bool recurring)
{
if (m_asyncInstrumentationEnabled)
m_debugger->asyncTaskScheduled(operationName, task, recurring);
}
void ThreadDebugger::asyncTaskCanceled(void* task)
{
if (m_asyncInstrumentationEnabled)
m_debugger->asyncTaskCanceled(task);
}
void ThreadDebugger::allAsyncTasksCanceled()
{
if (m_asyncInstrumentationEnabled)
m_debugger->allAsyncTasksCanceled();
}
void ThreadDebugger::asyncTaskStarted(void* task)
{
if (m_asyncInstrumentationEnabled)
m_debugger->asyncTaskStarted(task);
}
void ThreadDebugger::asyncTaskFinished(void* task)
{
if (m_asyncInstrumentationEnabled)
m_debugger->asyncTaskFinished(task);
}
void ThreadDebugger::beginUserGesture()
{
m_userGestureIndicator = wrapUnique(new UserGestureIndicator(DefinitelyProcessingNewUserGesture));
}
void ThreadDebugger::endUserGesture()
{
m_userGestureIndicator.reset();
}
String16 ThreadDebugger::valueSubtype(v8::Local<v8::Value> value)
{
if (V8Node::hasInstance(value, m_isolate))
return "node";
if (V8NodeList::hasInstance(value, m_isolate)
|| V8DOMTokenList::hasInstance(value, m_isolate)
|| V8HTMLCollection::hasInstance(value, m_isolate)
|| V8HTMLAllCollection::hasInstance(value, m_isolate)) {
return "array";
}
if (V8DOMException::hasInstance(value, m_isolate))
return "error";
return String();
}
bool ThreadDebugger::formatAccessorsAsProperties(v8::Local<v8::Value> value)
{
return V8DOMWrapper::isWrapper(m_isolate, value);
}
bool ThreadDebugger::isExecutionAllowed()
{
return !ScriptForbiddenScope::isScriptForbidden();
}
double ThreadDebugger::currentTimeMS()
{
return WTF::currentTimeMS();
}
bool ThreadDebugger::isInspectableHeapObject(v8::Local<v8::Object> object)
{
if (object->InternalFieldCount() < v8DefaultWrapperInternalFieldCount)
return true;
v8::Local<v8::Value> wrapper = object->GetInternalField(v8DOMWrapperObjectIndex);
// Skip wrapper boilerplates which are like regular wrappers but don't have
// native object.
if (!wrapper.IsEmpty() && wrapper->IsUndefined())
return false;
return true;
}
void ThreadDebugger::enableAsyncInstrumentation()
{
DCHECK(!m_asyncInstrumentationEnabled);
m_asyncInstrumentationEnabled = true;
}
void ThreadDebugger::disableAsyncInstrumentation()
{
DCHECK(m_asyncInstrumentationEnabled);
m_asyncInstrumentationEnabled = false;
}
static void returnDataCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
info.GetReturnValue().Set(info.Data());
}
static v8::Maybe<bool> createDataProperty(v8::Local<v8::Context> context, v8::Local<v8::Object> object, v8::Local<v8::Name> key, v8::Local<v8::Value> value)
{
v8::TryCatch tryCatch(context->GetIsolate());
v8::Isolate::DisallowJavascriptExecutionScope throwJs(context->GetIsolate(), v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
return object->CreateDataProperty(context, key, value);
}
static void createFunctionPropertyWithData(v8::Local<v8::Context> context, v8::Local<v8::Object> object, const char* name, v8::FunctionCallback callback, v8::Local<v8::Value> data, const char* description)
{
v8::Local<v8::String> funcName = v8String(context->GetIsolate(), name);
v8::Local<v8::Function> func;
if (!v8::Function::New(context, callback, data, 0, v8::ConstructorBehavior::kThrow).ToLocal(&func))
return;
func->SetName(funcName);
v8::Local<v8::String> returnValue = v8String(context->GetIsolate(), description);
v8::Local<v8::Function> toStringFunction;
if (v8::Function::New(context, returnDataCallback, returnValue, 0, v8::ConstructorBehavior::kThrow).ToLocal(&toStringFunction))
createDataProperty(context, func, v8String(context->GetIsolate(), "toString"), toStringFunction);
createDataProperty(context, object, funcName, func);
}
void ThreadDebugger::createFunctionProperty(v8::Local<v8::Context> context, v8::Local<v8::Object> object, const char* name, v8::FunctionCallback callback, const char* description)
{
createFunctionPropertyWithData(context, object, name, callback, v8::External::New(context->GetIsolate(), this), description);
}
v8::Maybe<bool> ThreadDebugger::createDataPropertyInArray(v8::Local<v8::Context> context, v8::Local<v8::Array> array, int index, v8::Local<v8::Value> value)
{
v8::TryCatch tryCatch(context->GetIsolate());
v8::Isolate::DisallowJavascriptExecutionScope throwJs(context->GetIsolate(), v8::Isolate::DisallowJavascriptExecutionScope::THROW_ON_FAILURE);
return array->CreateDataProperty(context, index, value);
}
void ThreadDebugger::installAdditionalCommandLineAPI(v8::Local<v8::Context> context, v8::Local<v8::Object> object)
{
createFunctionProperty(context, object, "monitorEvents", ThreadDebugger::monitorEventsCallback, "function monitorEvents(object, [types]) { [Command Line API] }");
createFunctionProperty(context, object, "unmonitorEvents", ThreadDebugger::unmonitorEventsCallback, "function unmonitorEvents(object, [types]) { [Command Line API] }");
createFunctionProperty(context, object, "getEventListeners", ThreadDebugger::getEventListenersCallback, "function getEventListeners(node) { [Command Line API] }");
}
static Vector<String> normalizeEventTypes(const v8::FunctionCallbackInfo<v8::Value>& info)
{
Vector<String> types;
if (info.Length() > 1 && info[1]->IsString())
types.append(toCoreString(info[1].As<v8::String>()));
if (info.Length() > 1 && info[1]->IsArray()) {
v8::Local<v8::Array> typesArray = v8::Local<v8::Array>::Cast(info[1]);
for (size_t i = 0; i < typesArray->Length(); ++i) {
v8::Local<v8::Value> typeValue;
if (!typesArray->Get(info.GetIsolate()->GetCurrentContext(), i).ToLocal(&typeValue) || !typeValue->IsString())
continue;
types.append(toCoreString(v8::Local<v8::String>::Cast(typeValue)));
}
}
if (info.Length() == 1)
types.appendVector(Vector<String>({ "mouse", "key", "touch", "pointer", "control", "load", "unload", "abort", "error", "select", "input", "change", "submit", "reset", "focus", "blur", "resize", "scroll", "search", "devicemotion", "deviceorientation" }));
Vector<String> outputTypes;
for (size_t i = 0; i < types.size(); ++i) {
if (types[i] == "mouse")
outputTypes.appendVector(Vector<String>({ "click", "dblclick", "mousedown", "mouseeenter", "mouseleave", "mousemove", "mouseout", "mouseover", "mouseup", "mouseleave", "mousewheel" }));
else if (types[i] == "key")
outputTypes.appendVector(Vector<String>({ "keydown", "keyup", "keypress", "textInput" }));
else if (types[i] == "touch")
outputTypes.appendVector(Vector<String>({ "touchstart", "touchmove", "touchend", "touchcancel" }));
else if (types[i] == "pointer")
outputTypes.appendVector(Vector<String>({ "pointerover", "pointerout", "pointerenter", "pointerleave", "pointerdown", "pointerup", "pointermove", "pointercancel", "gotpointercapture", "lostpointercapture" }));
else if (types[i] == "control")
outputTypes.appendVector(Vector<String>({ "resize", "scroll", "zoom", "focus", "blur", "select", "input", "change", "submit", "reset" }));
else
outputTypes.append(types[i]);
}
return outputTypes;
}
void ThreadDebugger::logCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() < 1)
return;
ThreadDebugger* debugger = static_cast<ThreadDebugger*>(v8::Local<v8::External>::Cast(info.Data())->Value());
DCHECK(debugger);
Event* event = V8Event::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!event)
return;
debugger->debugger()->logToConsole(info.GetIsolate()->GetCurrentContext(), event->type(), v8String(info.GetIsolate(), event->type()), info[0]);
}
v8::Local<v8::Function> ThreadDebugger::eventLogFunction()
{
if (m_eventLogFunction.IsEmpty())
m_eventLogFunction.Reset(m_isolate, v8::Function::New(m_isolate->GetCurrentContext(), logCallback, v8::External::New(m_isolate, this), 0, v8::ConstructorBehavior::kThrow).ToLocalChecked());
return m_eventLogFunction.Get(m_isolate);
}
static EventTarget* firstArgumentAsEventTarget(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() < 1)
return nullptr;
if (EventTarget* target = V8EventTarget::toImplWithTypeCheck(info.GetIsolate(), info[0]))
return target;
return toDOMWindow(info.GetIsolate(), info[0]);
}
void ThreadDebugger::setMonitorEventsCallback(const v8::FunctionCallbackInfo<v8::Value>& info, bool enabled)
{
EventTarget* eventTarget = firstArgumentAsEventTarget(info);
if (!eventTarget)
return;
Vector<String> types = normalizeEventTypes(info);
ThreadDebugger* debugger = static_cast<ThreadDebugger*>(v8::Local<v8::External>::Cast(info.Data())->Value());
DCHECK(debugger);
EventListener* eventListener = V8EventListenerList::getEventListener(ScriptState::current(info.GetIsolate()), debugger->eventLogFunction(), false, enabled ? ListenerFindOrCreate : ListenerFindOnly);
if (!eventListener)
return;
for (size_t i = 0; i < types.size(); ++i) {
if (enabled)
eventTarget->addEventListener(AtomicString(types[i]), eventListener, false);
else
eventTarget->removeEventListener(AtomicString(types[i]), eventListener, false);
}
}
// static
void ThreadDebugger::monitorEventsCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
setMonitorEventsCallback(info, true);
}
// static
void ThreadDebugger::unmonitorEventsCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
setMonitorEventsCallback(info, false);
}
// static
void ThreadDebugger::getEventListenersCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() < 1)
return;
ThreadDebugger* debugger = static_cast<ThreadDebugger*>(v8::Local<v8::External>::Cast(info.Data())->Value());
DCHECK(debugger);
v8::Isolate* isolate = info.GetIsolate();
V8EventListenerInfoList listenerInfo;
// eventListeners call can produce message on ErrorEvent during lazy event listener compilation.
debugger->muteWarningsAndDeprecations();
debugger->debugger()->muteConsole();
InspectorDOMDebuggerAgent::eventListenersInfoForTarget(isolate, info[0], listenerInfo);
debugger->debugger()->unmuteConsole();
debugger->unmuteWarningsAndDeprecations();
v8::Local<v8::Object> result = v8::Object::New(isolate);
AtomicString currentEventType;
v8::Local<v8::Array> listeners;
size_t outputIndex = 0;
v8::Local<v8::Context> context = isolate->GetCurrentContext();
for (auto& info : listenerInfo) {
if (currentEventType != info.eventType) {
currentEventType = info.eventType;
listeners = v8::Array::New(isolate);
outputIndex = 0;
createDataProperty(context, result, v8String(isolate, currentEventType), listeners);
}
v8::Local<v8::Object> listenerObject = v8::Object::New(isolate);
createDataProperty(context, listenerObject, v8String(isolate, "listener"), info.handler);
createDataProperty(context, listenerObject, v8String(isolate, "useCapture"), v8::Boolean::New(isolate, info.useCapture));
createDataProperty(context, listenerObject, v8String(isolate, "passive"), v8::Boolean::New(isolate, info.passive));
createDataProperty(context, listenerObject, v8String(isolate, "type"), v8String(isolate, currentEventType));
v8::Local<v8::Function> removeFunction;
if (info.removeFunction.ToLocal(&removeFunction))
createDataProperty(context, listenerObject, v8String(isolate, "remove"), removeFunction);
createDataPropertyInArray(context, listeners, outputIndex++, listenerObject);
}
info.GetReturnValue().Set(result);
}
void ThreadDebugger::consoleTime(const String16& title)
{
TRACE_EVENT_COPY_ASYNC_BEGIN0("blink.console", String(title).utf8().data(), this);
}
void ThreadDebugger::consoleTimeEnd(const String16& title)
{
TRACE_EVENT_COPY_ASYNC_END0("blink.console", String(title).utf8().data(), this);
}
void ThreadDebugger::consoleTimeStamp(const String16& title)
{
v8::Isolate* isolate = m_isolate;
TRACE_EVENT_INSTANT1("devtools.timeline", "TimeStamp", TRACE_EVENT_SCOPE_THREAD, "data", InspectorTimeStampEvent::data(currentExecutionContext(isolate), title));
}
void ThreadDebugger::startRepeatingTimer(double interval, V8DebuggerClient::TimerCallback callback, void* data)
{
m_timerData.append(data);
m_timerCallbacks.append(callback);
std::unique_ptr<Timer<ThreadDebugger>> timer = wrapUnique(new Timer<ThreadDebugger>(this, &ThreadDebugger::onTimer));
Timer<ThreadDebugger>* timerPtr = timer.get();
m_timers.append(std::move(timer));
timerPtr->startRepeating(interval, BLINK_FROM_HERE);
}
void ThreadDebugger::cancelTimer(void* data)
{
for (size_t index = 0; index < m_timerData.size(); ++index) {
if (m_timerData[index] == data) {
m_timers[index]->stop();
m_timerCallbacks.remove(index);
m_timers.remove(index);
m_timerData.remove(index);
return;
}
}
}
void ThreadDebugger::onTimer(Timer<ThreadDebugger>* timer)
{
for (size_t index = 0; index < m_timers.size(); ++index) {
if (m_timers[index].get() == timer) {
m_timerCallbacks[index](m_timerData[index]);
return;
}
}
}
} // namespace blink
| 39.915212 | 262 | 0.710421 | [
"object",
"vector"
] |
a1b1fafd2bb3dd0a91a82ed9f90d67ee4e448334 | 28,217 | hpp | C++ | sequitur.hpp | lytnus/cpp-sequitur | a27a5d1ad85b78d6366f74d2be18d3727d5bce94 | [
"MIT"
] | null | null | null | sequitur.hpp | lytnus/cpp-sequitur | a27a5d1ad85b78d6366f74d2be18d3727d5bce94 | [
"MIT"
] | null | null | null | sequitur.hpp | lytnus/cpp-sequitur | a27a5d1ad85b78d6366f74d2be18d3727d5bce94 | [
"MIT"
] | null | null | null | #ifndef SEQUITUR_H
#define SEQUITUR_H
#include <unordered_map>
#include <cassert>
#include <list>
#include <tuple>
#include <stack>
#include <memory>
#include "sequitur/symbols.hpp"
#include "sequitur/symbolwrapper.hpp"
#include "sequitur/hashing.hpp"
#include "sequitur/id.hpp"
namespace jw
{
//global aliases to help me along:
using uint = unsigned int;
//declare iter class before sequitur:
template<typename Type> class SequiturIter;
template<typename Type>
class Sequitur
{
//### iterator classes ###
template<typename ChildIter>
class SequiturIter
{
public:
using value_type = Type;
using const_value_type = const Type;
SequiturIter(const Sequitur<Type> * in_parent): parent(in_parent) {}
const_value_type & operator* ();
const_value_type * operator-> ();
bool operator==(const ChildIter & other) const;
bool operator!=(const ChildIter & other) const;
ChildIter& operator++();
ChildIter operator++(int);
ChildIter& operator--();
ChildIter operator--(int);
protected:
virtual void forward()=0;
virtual void backward()=0;
const Symbol * resolveForward(const Symbol * in);
const Symbol * resolveBackward(const Symbol * in);
std::stack<const Symbol*> pointer_stack;
const Symbol* current_item;
const Sequitur<Type> * parent;
};
struct ForwardIter: public SequiturIter<ForwardIter>
{
ForwardIter(const Sequitur<Type> * in_parent, Symbol* c): SequiturIter<ForwardIter>(in_parent)
{
this->current_item = this->resolveForward(c);
}
void forward();
void backward();
};
struct ReverseIter: public SequiturIter<ReverseIter>
{
ReverseIter(const Sequitur<Type> * in_parent, Symbol* c): SequiturIter<ReverseIter>(in_parent)
{
this->current_item = this->resolveBackward(c);
}
void forward();
void backward();
};
//### end iterator classes ###
public:
//some types for comparison:
const std::type_info & RuleHeadType = typeid(RuleHead);
const std::type_info & RuleTailType = typeid(RuleTail);
const std::type_info & RuleSymbolType = typeid(RuleSymbol);
const std::type_info & ValueType = typeid(Value);
//let's simplify some names:
using DigramIndex = std::unordered_map<std::pair<SymbolWrapper,SymbolWrapper>,Symbol*>;
using RuleIndex = std::unordered_map<uint, Symbol*>;
using Value = ValueSymbol<Type>;
using const_iterator = ForwardIter;
using const_reverse_iterator = ReverseIter;
//may be useful outside the class:
using value_type = Type;
using const_value_type = const Type;
//add new symbol to list.
//linkMade if symbol not first one added.
void push_back(Type);
//get const iterators:
const_iterator begin() const {return const_iterator(this, rule_index.at(0));}
const_iterator end() const {return const_iterator(this, sequence_end);}
const_reverse_iterator rbegin() const {return const_reverse_iterator(this, sequence_end);}
const_reverse_iterator rend() const {return const_reverse_iterator(this, rule_index.at(0));}
//return const references to rules for deep inspection:
const RuleIndex & getRules() const { return rule_index; }
//print things:
void printList(const Symbol *, unsigned int number) const;
void printAll() const;
void printSequence() const;
void printRules() const;
void printDigramIndex() const;
unsigned size() const { return length; }
//constructor:
Sequitur();
//move constructor:
Sequitur(Sequitur<Type> &&)=default;
//destructor to clean up:
~Sequitur();
private:
//waht to do when a link is made between two symbols:
void linkMade(Symbol * first);
//return Iter pointing to digram location, OR end of sequence if none:
Symbol * findAndAddDigram(Symbol *first);
//make a digram pair for use in the digram index:
std::pair<SymbolWrapper,SymbolWrapper> makeDigramPair(Symbol * first);
//remove a digram from the digram index:
void removeDigramFromIndex(Symbol * first);
//return ptr to the RuleHead if digram is complete rule:
RuleHead * getCompleteRule(Symbol * first);
//swaps two occurrences with a new rule:
std::pair<Symbol*,Symbol*> swapForNewRule(Symbol * first, Symbol * other);
//swaps a digram with an existing rule:
Symbol *swapForExistingRule(Symbol * first, RuleHead *rule_head);
//decrement Item if it's a rule:
bool decrementIfRule(Symbol * item);
//increment if it's a rule:
bool incrementIfRule(Symbol * item);
//check links formed around rules if they are valid etc:
void checkNewLinks(Symbol *rule1, Symbol *rule2);
void checkNewLinks(Symbol *rule1);
//check for rules only used once in rule_container and expand if found:
void expandRuleIfNecessary(Symbol * potential_rule);
//swapForRule(symbol it 1, symbol it 2)
//Each time a digram is replaced by a symbol representing a rule
// For each symbol in the digram
// If the symbol represents a rule
// If the rule represented only occurs once now
// Replace the symbol with contents of the rule
// remove the rule
ID id_generator;
Symbol * sequence_end;
unsigned int length = 0;
DigramIndex digram_index;
RuleIndex rule_index;
};
//CONSTRUCTOR
template<typename Type>
inline Sequitur<Type>::Sequitur()
{
RuleTail * start_tail = new RuleTail();
RuleHead * start_head = new RuleHead(id_generator.get(), start_tail);
start_head->insertAfter(start_tail);
sequence_end = start_tail;
rule_index[start_head->getID()] = start_head;
}
//DESTRUCTOR
template<typename Type>
inline Sequitur<Type>::~Sequitur()
{
//delete symbols:
auto it = rule_index.begin();
while(it != rule_index.end())
{
it->second->forUntil([](Symbol * item)
{
delete item;
return true;
});
it = rule_index.erase(it);
}
//clear digrams:
digram_index.clear();
//clear the object pools, freeing up all available memory:
//(won't free up used memory in the case of SinglePool)
ObjectPool<Value>::clear();
ObjectPool<RuleHead>::clear();
ObjectPool<RuleTail>::clear();
ObjectPool<RuleSymbol>::clear();
}
template<typename Type>
void Sequitur<Type>::push_back(Type s)
{
//add new symbol:
Symbol * val = sequence_end->insertBefore(new Value(s));
if(++length > 1)
{
auto one_from_end = val->prev();
linkMade(one_from_end);
}
}
//linkMade(symbol it 1, symbol it 2)
//Each time a new link is made between two symbols
// Check the digram index for another instance of this digram
// If another instance is found and does not overlap with this one
// If the other instance is a complete rule
// swapForRule(1, 2)
// Otherwise
// Create a new rule
// Replace both digrams with a new symbol representing this rule
// Else if this digram does not exist
// Add this digram to the index
// Else
// Do nothing (because other digram is overlapping).
template<typename Type>
void Sequitur<Type>::linkMade(Symbol * first)
{
assert(first != nullptr && "###linkMade: No nullptr expected here###");
assert(first->isNext() && "###linkMade: digram has only one symbol###");
//return iter to match if there's anything to do with it:
// - match does not overlap
// - match exists (digram added if not)
Symbol * match_location = findAndAddDigram(first);
//if there was a match, and is no overlap:
if(match_location != nullptr)
{
//get ruleHead it's pointing too, or nullptr if not rule:
RuleHead * rule_head = getCompleteRule(match_location);
//if other occurrence is not a rule:
if(!rule_head)
{
//match_location already in digram index, so swap that for new rule:
auto locations = swapForNewRule(first, match_location);
checkNewLinks(locations.first, locations.second);
}
//if it is a rule...
else
{
//replace digram with rule symbol:
Symbol * location = swapForExistingRule(first, rule_head);
checkNewLinks(location);
}
}
}
template<typename Type>
Symbol * Sequitur<Type>::findAndAddDigram(Symbol * first)
{
assert(first->isNext() && "###Digram is invalid!###");
//place this pair into digram_index if it doesnt exist:
auto out_pair = digram_index.emplace(makeDigramPair(first),first);
//get bool indicating whether insertion took place, and iter to location:
bool inserted = out_pair.second;
Symbol * other_first = out_pair.first->second;
//if already inserted, return end:
if(inserted) return nullptr;
//check for overlap:
if(other_first->next() == first || other_first == first->next())
{
return nullptr;
}
else return other_first;
}
template<typename Type>
std::pair<SymbolWrapper,SymbolWrapper> Sequitur<Type>::makeDigramPair(Symbol *first)
{
//while we can, we should not ever be making digram pairs out of ruleheads or ruletails:
assert(first->isNext());
assert(typeid(*first) != typeid(RuleHead*));
assert(typeid(first->next()) != typeid(RuleTail*));
//make a copy whatever symbols are in our digram:
std::unique_ptr<Symbol> first_copy = first->clone();
std::unique_ptr<Symbol> second_copy = first->next()->clone();
//and add these to a pair, moving them to pass ownerhsip into container:
return std::make_pair(std::move(first_copy), std::move(second_copy));
}
template<typename Type>
void Sequitur<Type>::removeDigramFromIndex(Symbol *first)
{
if(typeid(*first) == RuleHeadType) return;
if(typeid(*(first->next())) == RuleTailType) return;
//digram must be pointed at Item to be removed:
auto iter = digram_index.find(makeDigramPair(first));
if(iter != digram_index.end() && iter->second == first)
{
digram_index.erase(iter);
}
}
template<typename Type>
RuleHead * Sequitur<Type>::getCompleteRule(Symbol * first)
{
assert(first->isNext() && "should be at least one symbol following this");
//surrounding symbols:
auto tail = first->next(2);
auto head = first->prev();
if(typeid(*head) == RuleHeadType && typeid(*tail) == RuleTailType)
return static_cast<RuleHead*>(head);
else return nullptr;
}
template<typename Type>
std::pair<Symbol *, Symbol *> Sequitur<Type>::swapForNewRule(Symbol *match1, Symbol *match2)
{
assert(match1->next() && "first should be part of a digram");
assert(match2->next() && "other should be part of digram");
assert(match1->prev() != match2 && "should be no overlap");
assert(match2->next() != match1 && "should be no overlap");
assert(makeDigramPair(match1) == makeDigramPair(match2) && "digrams should be equal");
Symbol * match1_second = match1->next();
//make a new rule representing digram:
RuleTail * rule_tail = new RuleTail();
RuleHead * rule_head = new RuleHead(id_generator.get(), rule_tail);
Symbol * rule_item1 = rule_head->insertAfter(match1->clone().release());
Symbol * rule_item2 = rule_item1->insertAfter(match1_second->clone().release());
rule_item2->insertAfter(rule_tail);
//point digram_index to rule now:
digram_index[makeDigramPair(match1)] = rule_item1;
//point rule index to rule too:
rule_index[rule_head->getID()] = rule_head;
//increment count of any rules in digram, as we've added a copy:
incrementIfRule(match1);
incrementIfRule(match1_second);
//swap digrams for this new rule (expands rules out if needbe):
Symbol * loc1 = swapForExistingRule(match1, rule_head);
Symbol * loc2 = swapForExistingRule(match2, rule_head);
//return pair of locations:
return std::make_pair(loc1, loc2);
}
template<typename Type>
Symbol * Sequitur<Type>::swapForExistingRule(Symbol *first, RuleHead *rule_head)
{
assert(first->isPrev() && "should ALWAYS be one symbol before.");
assert(first->isNext() && "incomplete digram.");
assert(first->next()->isNext() && "should always be a tail after this digram.");
assert(rule_index.find(rule_head->getID()) != rule_index.end() && "rule should exist in index");
//replaces digram at first, with rule at rule_start (contains RuleHead)
//- remove digrams around first (not first itself)
//- decrement the count of any rules in digram to be removed
//- increment count of new rule
//- unlink and then delete first digram
//- place new RuleSymbol where first was.
Symbol * second = first->next();
Symbol * before_digram = first->prev();
//remove digrams around match if they exist and point to same location:
removeDigramFromIndex(second);
removeDigramFromIndex(before_digram);
//remove digram itself, decrementing count of any rule symbols:
first->unlink(2);
decrementIfRule(first);
decrementIfRule(second);
//now, we can delete the original digram elements entirely:
delete first;
delete second;
//insert rule in it's place, incrementing its count:
RuleSymbol * new_rule = rule_head->makeRuleSymbol().release();
new_rule->getRule()->increment();
//expand any rules contained within this rule now if needbe:
Symbol * rule_item1 = rule_head->next();
Symbol * rule_item2 = rule_item1->next();
expandRuleIfNecessary(rule_item1);
expandRuleIfNecessary(rule_item2);
//return position of rule in sequence:
return before_digram->insertAfter(new_rule);
}
//decrement Item if it's a rule:
template<typename Type>
bool Sequitur<Type>::decrementIfRule(Symbol *item)
{
if(typeid(*item) == RuleSymbolType)
{
static_cast<RuleSymbol*>(item)->getRule()->decrement();
return true;
}
else return false;
}
//increment if it's a rule:
template<typename Type>
bool Sequitur<Type>::incrementIfRule(Symbol *item)
{
if(typeid(*item) == RuleSymbolType)
{
static_cast<RuleSymbol*>(item)->getRule()->increment();
return true;
}
else return false;
}
template<typename Type>
void Sequitur<Type>::checkNewLinks(Symbol * rule1, Symbol * rule2)
{
assert(typeid(rule1) != typeid(RuleTail*) && "rule1 should never point to a RuleTail");
assert(typeid(rule2) != typeid(RuleTail*) && "rule2 should never point to a RuleTail");
//get any UNIQUE iterators to starts of digrams given that we inserted rule1 and rule2
//and check them:
//1. check digram at position rule1 if there is something valid following it.
auto rule1_next = rule1->next();
if(typeid(*rule1_next) != RuleTailType && typeid(*rule1) != RuleHeadType)
linkMade(rule1);
//2. check digram at position rule2 if there is something valid following it:
auto rule2_next = rule2->next();
if(typeid(*rule2_next) != RuleTailType && typeid(*rule2) != RuleHeadType)
linkMade(rule2);
//3. check digram at position --rule2 if it exists and is not equal to rule1:
auto rule2_prev = rule2->prev();
if(rule2_prev != rule1 && typeid(*rule2_prev) != RuleHeadType)
linkMade(rule2_prev);
//4. check digram at position --rule1 if it exists and is not equal to rule2:
auto rule1_prev = rule1->prev();
if(rule1_prev != rule2 && typeid(*rule1_prev) != RuleHeadType)
linkMade(rule1_prev);
}
template<typename Type>
void Sequitur<Type>::checkNewLinks(Symbol *rule1)
{
assert(typeid(*rule1) != typeid(RuleTail) && "rule should never point to a RuleTail");
//1. check digram at position rule if something valid following it:
auto rule1_next = rule1->next();
if(typeid(*rule1_next) != RuleTailType && typeid(*rule1) != RuleHeadType)
linkMade(rule1);
//2. check digram at position --rule if it exists and is valid:
auto rule1_prev = rule1->prev();
if(typeid(*rule1_prev) != RuleHeadType)
linkMade(rule1_prev);
}
template<typename Type>
void Sequitur<Type>::expandRuleIfNecessary(Symbol *potential_rule)
{
assert(typeid(*potential_rule) != typeid(RuleHead));
assert(typeid(*potential_rule) != typeid(RuleTail));
//if it's not a rule, ignore it:
if(typeid(*potential_rule) != RuleSymbolType) return;
RuleSymbol * rule_symbol = static_cast<RuleSymbol*>(potential_rule);
//a couple of checks to make sure nothing is broken:
assert(rule_symbol->getCount() && "count should never be 0");
assert(rule_index.find(rule_symbol->getID()) != rule_index.end() && "rule no exist!");
//if rule symbol count is not 1 (or 0) leave it be:
if(rule_symbol->getCount() != 1) return;
//if we've got this far, expand the rule:
//(by making rules hold ptr's to the Item* containing the rule head,
// and rule heads holding ptr's to the rule tail, we could improve this)
RuleHead * rule_head_item = rule_symbol->getRule();
Symbol * rule_first_item = rule_head_item->next();
Symbol * rule_tail_item = rule_head_item->getTail();
Symbol * rule_last_item = rule_tail_item->prev();
//check that indeed the rule_tail is a RuleTail (it always should be):
assert(typeid(*rule_head_item) == typeid(RuleHead) && "should always be a head at start.");
assert(typeid(*rule_tail_item) == typeid(RuleTail) && "should always be a tail at end.");
//delete rule from rule_index and free up ID for future use:
unsigned int rule_id = rule_head_item->getID();
rule_index.erase(rule_id);
id_generator.free(rule_id);
//get items surrounding the rule symbol we wanna swap out:
Symbol * before_potential_rule = potential_rule->prev();
Symbol * after_potential_rule = potential_rule->next();
//delete the digrams pointing to these items (relies on rule head):
removeDigramFromIndex(before_potential_rule);
removeDigramFromIndex(potential_rule);
//separate rule from its head and tail:
rule_head_item->splitAfter();
rule_tail_item->splitBefore();
//now we no longer need them, we can delete them:
delete rule_head_item;
delete rule_tail_item;
//unlink and delete the rule symbol:
potential_rule->splitBefore();
potential_rule->splitAfter();
delete potential_rule;
//join up the pieces:
before_potential_rule->joinAfter(rule_first_item);
after_potential_rule->joinBefore(rule_last_item);
//now, check new digrams made if they don't contain rule heads or tails:
if(typeid(*before_potential_rule) != RuleHeadType) linkMade(before_potential_rule);
if(typeid(*(rule_last_item->next())) != RuleTailType) linkMade(rule_last_item);
}
template<typename Type>
void Sequitur<Type>::printList(const Symbol * list, unsigned int number) const
{
list->forUntil([&number,this](const Symbol * item)
{
if(typeid(*item) == ValueType)
{
std::cout << static_cast<const Value*>(item)->getValue() << " ";
}
else if(typeid(*item) == RuleSymbolType)
{
std::cout << "[" << static_cast<const RuleSymbol*>(item)->getID() << "] ";
}
else if(typeid(*item) == RuleHeadType)
{
std::cout << "[" << static_cast<const RuleHead*>(item)->getID()
<< "(" << static_cast<const RuleHead*>(item)->getCount() << ")]: < ";
}
else if(typeid(*item) == RuleTailType)
{
std::cout << ">";
}
if(!--number) return false;
else return true;
});
}
template<typename Type>
void Sequitur<Type>::printSequence() const
{
printList(rule_index.at(0), 0);
std::cout << std::endl;
}
template<typename Type>
void Sequitur<Type>::printRules() const
{
for(const auto & rule_pair : rule_index )
{
std::cout << rule_pair.first << ": ";
printList(rule_pair.second, 0);
std::cout << std::endl;
}
}
template<typename Type>
void Sequitur<Type>::printAll() const
{
//print out rules:
for(const auto & rule_pair : rule_index )
{
std::cout << rule_pair.first << ": ";
printList(rule_pair.second, 0);
std::cout << std::endl;
}
printDigramIndex();
std::cout << std::endl;
}
template<typename Type>
void Sequitur<Type>::printDigramIndex() const
{
for(auto & i : digram_index)
{
printList(i.second, 2);
std::cout << ", ";
}
std::cout << std::endl;
}
//###############################
//### Sequitur Iterator Class ###
//###############################
template<typename Type>
template<typename ChildIter>
typename Sequitur<Type>::const_value_type &
Sequitur<Type>::SequiturIter<ChildIter>::operator*()
{
return static_cast<const Value*>(current_item)->getValue();
}
template<typename Type>
template<typename ChildIter>
typename Sequitur<Type>::const_value_type *
Sequitur<Type>::SequiturIter<ChildIter>::operator->()
{
return &(static_cast<const Value*>(current_item)->getValue());
}
template<typename Type>
template<typename ChildIter>
bool Sequitur<Type>::SequiturIter<ChildIter>::operator==(const ChildIter & other) const
{
return current_item == other.current_item &&
pointer_stack == other.pointer_stack;
}
template<typename Type>
template<typename ChildIter>
bool Sequitur<Type>::SequiturIter<ChildIter>::operator!=(const ChildIter & other) const
{
return !(*this == other);
}
template<typename Type>
template<typename ChildIter>
const Symbol * Sequitur<Type>::SequiturIter<ChildIter>::resolveForward(const Symbol * in)
{
const std::type_info & type = typeid(*in);
const Symbol * output;
if(type == parent->ValueType)
{
output = in;
}
else if(type == parent->RuleSymbolType)
{
//go down one level:
pointer_stack.push(in);
output = resolveForward(static_cast<const RuleSymbol*>(in)->getRule()->next());
}
else if(type == parent->RuleHeadType)
{
output = resolveForward(in->next());
}
else //in == parent->RuleTailType
{
//###only hit when going forwards###
if(pointer_stack.empty()) return in;
//otherwise, go up one level:
const Symbol * back = pointer_stack.top();
pointer_stack.pop();
output = resolveForward(back->next());
}
return output;
}
template<typename Type>
template<typename ChildIter>
const Symbol * Sequitur<Type>::SequiturIter<ChildIter>::resolveBackward(const Symbol * in)
{
const std::type_info & type = typeid(*in);
const Symbol * output;
if(type == parent->ValueType)
{
output = in;
}
else if(type == parent->RuleSymbolType)
{
//go down one level:
pointer_stack.push(in);
output = resolveBackward(static_cast<const RuleSymbol*>(in)->getRule()->getTail()->prev());
}
else if(type == parent->RuleTailType)
{
output = resolveBackward(in->prev());
}
else //in == parent->RuleHeadType
{
//if at the end:
if(pointer_stack.empty()) return in;
//otherwise, go up one level:
const Symbol * back = pointer_stack.top();
pointer_stack.pop();
output = resolveBackward(back->prev());
}
return output;
}
template<typename Type>
template<typename ChildIter>
ChildIter& Sequitur<Type>::SequiturIter<ChildIter>::operator++()
{
this->forward();
return *static_cast<ChildIter*>(this);
}
template<typename Type>
template<typename ChildIter>
ChildIter Sequitur<Type>::SequiturIter<ChildIter>::operator++(int)
{
ChildIter tmp(*static_cast<ChildIter*>(this));
this->forward();
return tmp;
}
template<typename Type>
template<typename ChildIter>
ChildIter & Sequitur<Type>::SequiturIter<ChildIter>::operator--()
{
this->backward();
return *static_cast<ChildIter*>(this);
}
template<typename Type>
template<typename ChildIter>
ChildIter Sequitur<Type>::SequiturIter<ChildIter>::operator--(int)
{
ChildIter tmp(*static_cast<ChildIter*>(this));
this->backward();
return tmp;
}
// ##############################################################
// ### function definitions for forward and reverse iterator: ###
// ##############################################################
template<typename Type>
void Sequitur<Type>::ForwardIter::forward()
{
this->current_item = this->resolveForward(this->current_item->next());
}
template<typename Type>
void Sequitur<Type>::ForwardIter::backward()
{
this->current_item = this->resolveBackward(this->current_item->prev());
}
template<typename Type>
void Sequitur<Type>::ReverseIter::forward()
{
this->current_item = this->resolveBackward(this->current_item->prev());
}
template<typename Type>
void Sequitur<Type>::ReverseIter::backward()
{
this->current_item = this->resolveForward(this->current_item->next());
}
}//end of jw namespace;
#endif // SEQUITUR_H
| 34.878863 | 106 | 0.586065 | [
"object"
] |
a1b206f8c5cbd6049a9438399f039a3e9ab05d28 | 13,389 | cpp | C++ | modules/basegl/src/processors/volumeprocessing/volumecombiner.cpp | alexanderbock/inviwo | 5a23de833ba3f7bd56d71154e75df3bfc6ee6a7c | [
"BSD-2-Clause"
] | 349 | 2015-01-30T09:21:52.000Z | 2022-03-25T03:10:02.000Z | modules/basegl/src/processors/volumeprocessing/volumecombiner.cpp | alexanderbock/inviwo | 5a23de833ba3f7bd56d71154e75df3bfc6ee6a7c | [
"BSD-2-Clause"
] | 641 | 2015-09-23T08:54:06.000Z | 2022-03-23T09:50:55.000Z | modules/basegl/src/processors/volumeprocessing/volumecombiner.cpp | alexanderbock/inviwo | 5a23de833ba3f7bd56d71154e75df3bfc6ee6a7c | [
"BSD-2-Clause"
] | 124 | 2015-02-27T23:45:02.000Z | 2022-02-21T09:37:14.000Z | /*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2021 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <modules/basegl/processors/volumeprocessing/volumecombiner.h>
#include <modules/opengl/volume/volumegl.h>
#include <modules/opengl/texture/textureunit.h>
#include <inviwo/core/util/shuntingyard.h>
#include <inviwo/core/util/zip.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/volume/volumeutils.h>
namespace {
std::string idToString(const size_t& id) {
if (id == 0) return "";
return inviwo::toString(id);
}
} // namespace
namespace inviwo {
const ProcessorInfo VolumeCombiner::processorInfo_{
"org.inviwo.VolumeCombiner", // Class identifier
"Volume Combiner", // Display name
"Volume Operation", // Category
CodeState::Experimental, // Code state
Tags::GL, // Tags
};
const ProcessorInfo VolumeCombiner::getProcessorInfo() const { return processorInfo_; }
VolumeCombiner::VolumeCombiner()
: Processor()
, inport_("inport")
, outport_("outport")
, description_("description", "Volumes")
, eqn_("eqn", "Equation", "v1")
, normalizationMode_(
"normalizationMode", "Normalization Mode",
{{"normalized", "Normalize volumes", NormalizationMode::Normalized},
{"signedNormalized", "Normalize volumes with sign", NormalizationMode::SignedNormalized},
{"noNormalization", "No normalization", NormalizationMode::NotNormalized}},
0)
, scales_("scales", "Scale factors")
, addScale_("addScale", "Add Scale Factor")
, removeScale_("removeScale", "Remove Scale Factor")
, useWorldSpace_("useWorldSpaceCoordinateSystem", "World Space", false)
, borderValue_("borderValue", "Border value", vec4(0.f), vec4(0.f), vec4(1.f), vec4(0.1f))
, dataRange_("dataRange", "Data Range")
, rangeMode_("rangeMode", "Mode")
, outputDataRange_("outputDataRange", "Output Data Range", 0.0, 1.0,
std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),
0.01, 0.0, InvalidationLevel::Valid, PropertySemantics::Text)
, outputValueRange_("outputValueRange", "Output ValueRange", 0.0, 1.0,
std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),
0.01, 0.0, InvalidationLevel::Valid, PropertySemantics::Text)
, customRange_("customRange", "Custom Range")
, customDataRange_("customDataRange", "Custom Data Range", 0.0, 1.0,
std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),
0.01, 0.0, InvalidationLevel::InvalidOutput, PropertySemantics::Text)
, customValueRange_("customValueRange", "Custom Value Range", 0.0, 1.0,
std::numeric_limits<double>::lowest(), std::numeric_limits<double>::max(),
0.01, 0.0, InvalidationLevel::InvalidOutput, PropertySemantics::Text)
, fragment_{std::make_shared<StringShaderResource>("volumecombiner.frag", "")}
, shader_({{ShaderType::Vertex, utilgl::findShaderResource("volume_gpu.vert")},
{ShaderType::Geometry, utilgl::findShaderResource("volume_gpu.geom")},
{ShaderType::Fragment, fragment_}},
Shader::Build::No)
, fbo_() {
description_.setSemantics(PropertySemantics::Multiline);
description_.setReadOnly(true);
description_.setCurrentStateAsDefault();
isReady_.setUpdate([this]() { return allInportsAreReady() && (valid_ || dirty_); });
addPort(inport_);
addPort(outport_);
addProperty(description_);
addProperty(eqn_);
addProperty(normalizationMode_);
addProperty(addScale_);
addProperty(removeScale_);
addProperty(scales_);
addProperty(useWorldSpace_);
useWorldSpace_.addProperty(borderValue_);
addProperty(dataRange_);
dataRange_.addProperties(rangeMode_, outputDataRange_, outputValueRange_, customRange_,
customDataRange_, customValueRange_);
outputDataRange_.setReadOnly(true);
outputValueRange_.setReadOnly(true);
customRange_.onChange([&]() {
customDataRange_.setReadOnly(!customRange_.get());
customValueRange_.setReadOnly(!customRange_.get());
});
customDataRange_.setReadOnly(!customRange_.get());
customValueRange_.setReadOnly(!customRange_.get());
normalizationMode_.onChange([&]() { dirty_ = true; });
addScale_.onChange([&]() {
size_t i = scales_.size();
auto p = std::make_unique<FloatProperty>("scale" + toString(i), "s" + toString(i + 1), 1.0f,
-2.f, 2.f, 0.01f);
p->setSerializationMode(PropertySerializationMode::All);
scales_.addProperty(p.release());
});
removeScale_.onChange([&]() {
if (scales_.size() > 0) {
dirty_ = true;
delete scales_.removeProperty(scales_.getProperties().back());
isReady_.update();
}
});
eqn_.onChange([&]() {
dirty_ = true;
isReady_.update();
});
inport_.onConnect([&]() {
dirty_ = true;
updateProperties();
isReady_.update();
});
inport_.onDisconnect([&]() {
dirty_ = true;
updateProperties();
isReady_.update();
});
useWorldSpace_.onChange([this]() {
dirty_ = true;
isReady_.update();
});
}
std::string VolumeCombiner::buildEquation() const {
std::map<std::string, double> vars = {};
std::map<std::string, std::string> symbols;
for (auto&& i : util::enumerate(inport_)) {
symbols["s" + toString(i.first() + 1)] = "scale" + toString(i.first());
symbols["v" + toString(i.first() + 1)] = "vol" + toString(i.first());
}
return shuntingyard::Calculator::shaderCode(eqn_.get(), vars, symbols);
}
void VolumeCombiner::buildShader(const std::string& eqn) {
std::stringstream ss;
ss << "#include \"utils/structs.glsl\"\n";
ss << "#include \"utils/sampler3d.glsl\"\n\n";
ss << "in vec4 texCoord_;\n";
ss << "uniform vec4 " << borderValue_.getIdentifier() << ";\n";
for (auto&& i : util::enumerate(inport_)) {
ss << "uniform sampler3D volume" << idToString(i.first()) << ";\n";
ss << "uniform VolumeParameters volume" << idToString(i.first()) << "Parameters;\n";
}
for (auto prop : scales_.getProperties()) {
ss << "uniform float " << prop->getIdentifier() << ";\n";
}
ss << "\nvoid main() {\n";
// Determine which normalization mode should be used
std::string getVoxel;
auto mode = normalizationMode_.get();
if (mode == NormalizationMode::Normalized)
getVoxel = "getNormalizedVoxel";
else if (mode == NormalizationMode::SignedNormalized)
getVoxel = "getSignNormalizedVoxel";
else
getVoxel = "getVoxel";
for (auto&& i : util::enumerate(inport_)) {
const std::string vol = "vol" + toString(i.first());
const std::string v = "volume" + idToString(i.first());
const std::string vp = "volume" + idToString(i.first()) + "Parameters";
if (useWorldSpace_) {
const std::string coord = "coord" + toString(i.first());
// Retrieve data from world space and use border value if outside of volume
ss << " vec3 " << coord << " = (" << vp << ".worldToTexture * "
<< "volumeParameters.textureToWorld * texCoord_).xyz;\n";
ss << " vec4 " << vol << ";\n";
ss << " if (all(greaterThanEqual(" << coord << ", vec3(0))) &&"
<< " all(lessThanEqual(" << coord << ", vec3(1)))) {\n";
ss << " " << vol << " = " << getVoxel << "(" << v << ", " << vp << ", " << coord
<< ");\n";
ss << " } else {\n";
ss << " " << vol << " = borderValue;\n";
ss << " }\n\n";
} else {
ss << " vec4 " << vol << " = " << getVoxel << "(" << v << ", " << vp
<< ", texCoord_.xyz);\n";
}
}
ss << " FragData0 = " << eqn << ";\n";
ss << " gl_FragDepth = 1.0;\n";
ss << "}\n";
fragment_->setSource(ss.str());
shader_.build();
}
void VolumeCombiner::updateProperties() {
std::stringstream desc;
std::vector<OptionPropertyIntOption> options;
for (auto&& p : util::enumerate(inport_.getConnectedOutports())) {
const std::string str =
"v" + toString(p.first() + 1) + ": " + p.second()->getProcessor()->getDisplayName();
desc << str << "\n";
options.emplace_back("v" + toString(p.first() + 1), str, static_cast<int>(p.first()));
}
options.emplace_back("maxRange", "min/max {v1, v2, ...}", -1);
description_.set(desc.str());
rangeMode_.replaceOptions(options);
}
void VolumeCombiner::process() {
if (inport_.isChanged()) {
const DataFormatBase* format = inport_.getData()->getDataFormat();
volume_ = std::make_shared<Volume>(inport_.getData()->getDimensions(), format);
volume_->setModelMatrix(inport_.getData()->getModelMatrix());
volume_->setWorldMatrix(inport_.getData()->getWorldMatrix());
// pass on metadata
volume_->copyMetaDataFrom(*inport_.getData());
volume_->dataMap_ = inport_.getData()->dataMap_;
outport_.setData(volume_);
}
updateDataRange();
if (dirty_) {
dirty_ = false;
try {
buildShader(buildEquation());
valid_ = true;
} catch (Exception& e) {
valid_ = false;
isReady_.update();
throw Exception(e.getMessage() + ": " + eqn_.get(), IVW_CONTEXT);
}
}
shader_.activate();
TextureUnitContainer cont;
int i = 0;
for (const auto& vol : inport_) {
utilgl::bindAndSetUniforms(shader_, cont, *vol, "volume" + idToString(i));
++i;
}
utilgl::setUniforms(shader_, borderValue_);
for (auto prop : scales_.getProperties()) {
utilgl::setUniforms(shader_, *static_cast<FloatProperty*>(prop));
}
const size3_t dim{inport_.getData()->getDimensions()};
fbo_.activate();
glViewport(0, 0, static_cast<GLsizei>(dim.x), static_cast<GLsizei>(dim.y));
// We always need to ask for a editable representation
// this will invalidate any other representations
VolumeGL* outVolumeGL = volume_->getEditableRepresentation<VolumeGL>();
if (inport_.isChanged()) {
fbo_.attachColorTexture(outVolumeGL->getTexture().get(), 0);
}
utilgl::multiDrawImagePlaneRect(static_cast<int>(dim.z));
shader_.deactivate();
fbo_.deactivate();
isReady_.update();
}
void VolumeCombiner::updateDataRange() {
dvec2 dataRange = inport_.getData()->dataMap_.dataRange;
dvec2 valueRange = inport_.getData()->dataMap_.valueRange;
if (rangeMode_.getSelectedIdentifier() == "maxRange") {
auto minmax = [](const dvec2& a, const dvec2& b) {
return dvec2{std::min(a.x, b.x), std::max(a.y, b.y)};
};
for (const auto& vol : inport_) {
dataRange = minmax(dataRange, vol->dataMap_.dataRange);
valueRange = minmax(valueRange, vol->dataMap_.valueRange);
}
} else {
dataRange = inport_.getVectorData()[rangeMode_.getSelectedValue()]->dataMap_.dataRange;
valueRange = inport_.getVectorData()[rangeMode_.getSelectedValue()]->dataMap_.valueRange;
}
outputDataRange_.set(dataRange);
outputValueRange_.set(valueRange);
if (customRange_) {
dataRange = customDataRange_;
valueRange = customValueRange_;
}
volume_->dataMap_.dataRange = dataRange;
volume_->dataMap_.valueRange = valueRange;
}
} // namespace inviwo
| 39.149123 | 100 | 0.61431 | [
"geometry",
"vector"
] |
a1b72be74ac763b0c871cc4e55ec8fa14c725388 | 10,627 | cpp | C++ | tests/binaryloggertest/logging.cpp | ztxc/Log4Qt | 41c108535b6a0035e667c5a1a5d696c7adbd81c3 | [
"Apache-2.0"
] | 421 | 2015-12-22T15:13:26.000Z | 2022-03-29T02:26:28.000Z | tests/binaryloggertest/logging.cpp | ztxc/Log4Qt | 41c108535b6a0035e667c5a1a5d696c7adbd81c3 | [
"Apache-2.0"
] | 34 | 2016-05-09T17:32:38.000Z | 2022-03-21T09:56:43.000Z | tests/binaryloggertest/logging.cpp | ztxc/Log4Qt | 41c108535b6a0035e667c5a1a5d696c7adbd81c3 | [
"Apache-2.0"
] | 184 | 2016-01-15T08:43:16.000Z | 2022-03-29T02:26:31.000Z | #include "logging.h"
#include <QByteArray>
#include <QVariant>
#include <QDateTime>
#include <QStringBuilder>
static QString escape(const QString &string);
static QString toString(const QVariantMap &map);
static QString toString(const QVariantList &list);
static QString toString(const QVariantHash &hash);
static QString toString(const QStringList &stringList);
static QString toString(const QByteArray &byteArray);
static QString toString(QDate date);
static QString toString(QTime time);
static QString toString(const QDateTime &datetime);
static QString toString(const QString &string);
static QString toString(const QVariant &value, int userType);
static QString toString(const QVariant &value);
static bool isOpenBracket(const QStringList &brackets, QChar c);
static bool isCloseBracket(const QStringList &brackets, QChar c);
QString Logging::createDumpString(const QByteArray &data, const bool withCaption)
{
const int bytesPerLine = 16;
const QByteArray dist(" ");
const QByteArray placeHolder(" ");
const QByteArray intention(" ");
QByteArray line;
QByteArray details(dist);
unsigned char fromChar = 0x20;
unsigned char toChar = 0x7e;
QByteArray out;
if (withCaption)
out.append("Dump:\n offset (hex) - data (hex) - data (text)\n");
QByteArray hexData = data.toHex();
line.append(intention);
line.append("00000000 ");
for ( int i = 1, ii = 0; i <= data.size(); ++i, ii += 2 )
{
unsigned char byte = data[i - 1];
line.append(hexData.mid(ii, 2));
line.append(' ');
if ( byte >= fromChar && byte <= toChar )
details.append(static_cast<char>(byte));
else
details.append('.');
if (( i % bytesPerLine ) == 0)
{
// one line ready
line.append(details);
out.append(line);
out.append('\n');
line.clear();
line.append(intention);
line.append(QStringLiteral("%0 ").arg(i, 8, 16, QLatin1Char('0')).toLatin1());
details.clear();
details.append(dist);
}
else if (i == data.size())
{
int remaining = bytesPerLine - ( i % bytesPerLine );
for ( int j = 0; j < remaining; j++ )
line.append(placeHolder);
// end if data
line.append(details);
out.append(line);
}
}
return out;
}
QString Logging::toString(const QVariant &value)
{
return ::toString(value);
}
QString toString(const QVariant &value)
{
switch (value.type())
{
case QVariant::Invalid:
return QStringLiteral("<Invalid>");
case QVariant::BitArray:
return QStringLiteral("<BitArray>");
case QVariant::Bitmap:
return QStringLiteral("<Bitmap>");
case QVariant::Brush:
return QStringLiteral("<Brush>");
case QVariant::Color:
return QStringLiteral("<Color>");
case QVariant::Cursor:
return QStringLiteral("<Cursor>");
case QVariant::EasingCurve:
return QStringLiteral("<EasingCurve>");
case QVariant::ModelIndex:
return QStringLiteral("<ModelIndex>");
case QVariant::Font:
return QStringLiteral("<Font>");
case QVariant::Icon:
return QStringLiteral("<Icon>");
case QVariant::Image:
return QStringLiteral("<Image>");
case QVariant::KeySequence:
return QStringLiteral("<KeySequence>");
case QVariant::Line:
return QStringLiteral("<Line>");
case QVariant::LineF:
return QStringLiteral("<LineF>");
case QVariant::Locale:
return QStringLiteral("<Locale>");
#if QT_VERSION < 0x060000
case QVariant::Matrix:
return QStringLiteral("<Matrix>");
#endif
case QVariant::Transform:
return QStringLiteral("<Transform>");
case QVariant::Matrix4x4:
return QStringLiteral("<Matrix4x4>");
case QVariant::Palette:
return QStringLiteral("<Palette>");
case QVariant::Pen:
return QStringLiteral("<Pen>");
case QVariant::Pixmap:
return QStringLiteral("<Pixmap>");
case QVariant::Point:
return QStringLiteral("<Point>");
case QVariant::PointF:
return QStringLiteral("<PointF>");
case QVariant::Polygon:
return QStringLiteral("<Polygon>");
case QVariant::PolygonF:
return QStringLiteral("<PolygonF>");
case QVariant::Quaternion:
return QStringLiteral("<Quaternion>");
case QVariant::Rect:
return QStringLiteral("<Rect>");
case QVariant::RectF:
return QStringLiteral("<RectF>");
#if QT_VERSION < 0x060000
case QVariant::RegExp:
return QStringLiteral("<RegExp>");
#endif
case QVariant::RegularExpression:
return QStringLiteral("<RegularExpression>");
case QVariant::Region:
return QStringLiteral("<Region>");
case QVariant::Size:
return QStringLiteral("<Size>");
case QVariant::SizeF:
return QStringLiteral("<SizeF>");
case QVariant::SizePolicy:
return QStringLiteral("<SizePolicy>");
case QVariant::TextFormat:
return QStringLiteral("<TextFormat>");
case QVariant::TextLength:
return QStringLiteral("<TextLength>");
case QVariant::Vector2D:
return QStringLiteral("<Vector2D>");
case QVariant::Vector3D:
return QStringLiteral("<Vector3D>");
case QVariant::Vector4D:
return QStringLiteral("<Vector4D>");
case QVariant::Int:
case QVariant::Double:
case QVariant::Char:
case QVariant::Bool:
case QVariant::UInt:
case QVariant::LongLong:
case QVariant::ULongLong:
case QVariant::Url:
case QVariant::Uuid:
return value.toString();
case QVariant::ByteArray:
return toString(value.toByteArray());
case QVariant::Date:
return toString(value.toDate());
case QVariant::DateTime:
return toString(value.toDateTime());
case QVariant::Hash:
return toString(value.toHash());
case QVariant::List:
return toString(value.toList());
case QVariant::Map:
return toString(value.toMap());
case QVariant::String:
return toString(value.toString());
case QVariant::StringList:
return toString(value.toStringList());
case QVariant::Time:
return toString(value.toTime());
case QVariant::UserType:
return toString(value, value.userType());
default:
break;
}
return QStringLiteral("<Unknow variant type>");
}
QString toString(const QVariantMap &map)
{
QStringList result;
for (auto pos = map.cbegin(); pos != map.cend(); ++pos)
result << QStringLiteral("%1=%2").arg(toString(pos.key()), toString(pos.value()));
return QStringLiteral("{") % result.join(QStringLiteral(", ")) % QStringLiteral("}");
}
QString toString(const QVariantList &list)
{
QStringList result;
for (const auto &value : list)
result << toString(value);
return QStringLiteral("[") % result.join(QStringLiteral(", ")) % QStringLiteral("]");
}
QString toString(const QVariantHash &hash)
{
QStringList result;
for (auto pos = hash.cbegin(); pos != hash.cend(); ++pos)
result << QStringLiteral("%1=%2").arg(toString(pos.key()), toString(pos.value()));
return QStringLiteral("{") % result.join(QStringLiteral(", ")) % QStringLiteral("}");
}
QString toString(const QStringList &stringList)
{
QStringList result;
for (const auto &string : stringList)
result << toString(string);
return QStringLiteral("[") % result.join(QStringLiteral(", ")) % QStringLiteral("]");
}
QString toString(const QByteArray &byteArray)
{
QStringList result;
for (auto byte : byteArray)
result << QStringLiteral("%1").arg(byte, 2, 16, QChar('0'));
return QStringLiteral("[") % result.join(QStringLiteral(", ")) % QStringLiteral("]");
}
QString toString(QDate date)
{
return date.toString(QStringLiteral("yyyy-MM-dd"));
}
QString toString(QTime time)
{
return time.toString(QStringLiteral("hh:mm:ss.zzz"));
}
QString toString(const QDateTime &datetime)
{
return toString(datetime.date()) % QStringLiteral("T") % toString(datetime.time()) + datetime.timeZoneAbbreviation();
}
QString toString(const QString &string)
{
return QStringLiteral("\"") % escape(string) % QStringLiteral("\"");
}
QString escape(const QString &string)
{
QString copy(string);
return copy.replace('"', QLatin1String("\\\""))
.replace('\n', QLatin1String("\\n"))
.replace('\r', QLatin1String("\\r"))
.replace('\t', QLatin1String("\\t"));
}
QString toString(const QVariant &value, int userType)
{
Q_UNUSED(value)
return QStringLiteral("{UserType: %1").arg(userType);
}
bool isOpenBracket(const QStringList &brackets, QChar c)
{
for (const auto &b : brackets)
{
if (!b.isEmpty() && b[0] == c)
return true;
}
return false;
}
bool isCloseBracket(const QStringList &brackets, QChar c)
{
for (const auto &b : brackets)
{
if (b.length() > 1 && b[1] == c)
return true;
}
return false;
}
QString Logging::indentString(const QString &string, const QStringList &indentBrackets)
{
QString result;
QChar quote{'\0'};
QChar last{'\0'};
QChar current{'\0'};
int indent = 0;
for (int i = 0; i < string.length(); ++i)
{
current = string[i];
if (quote != QChar('\0'))
{
if (quote == current)
quote = '\0';
}
else
{
switch (current.toLatin1())
{
case '\'':
case '"':
quote = current;
break;
case ',':
result += "\n" + QString(indent, QChar(' '));
break;
default:
if (isOpenBracket(indentBrackets, current))
{
result += "\n" + QString(indent, QChar(' '));
indent++;
}
else if (isCloseBracket(indentBrackets, current))
{
indent--;
result += "\n" + QString(indent, QChar(' '));
}
break;
}
}
if (isOpenBracket(indentBrackets, last))
{
if (!isCloseBracket(indentBrackets, current))
result += "\n" + QString(indent, QChar(' '));
}
result += QString(current);
last = string[i];
}
return result;
}
| 28.877717 | 121 | 0.599887 | [
"transform"
] |
a1b8ce2ae2d63bf7bc187dbce1c6d3f5bb477e4f | 7,958 | cpp | C++ | APX_Files/Src/AdditionalJSONCommands.cpp | poco2018/Archicad-Keynotes | 8796a44022ddc3d2675cd630b6fa0c7d8a6c9586 | [
"MIT"
] | 2 | 2021-07-15T10:05:25.000Z | 2021-11-20T06:21:46.000Z | APX_Files/Src/AdditionalJSONCommands.cpp | poco2018/Archicad-Keynotes | 8796a44022ddc3d2675cd630b6fa0c7d8a6c9586 | [
"MIT"
] | null | null | null | APX_Files/Src/AdditionalJSONCommands.cpp | poco2018/Archicad-Keynotes | 8796a44022ddc3d2675cd630b6fa0c7d8a6c9586 | [
"MIT"
] | null | null | null | #include "AdditionalJSONCommands.hpp"
#include "ObjectState.hpp"
#include "FileSystem.hpp"
#include "AddOnMain.hpp"
constexpr const char* AdditionalJSONCommandsNamespace = "AdditionalJSONCommands";
static GS::HashTable<GS::UniString, API_Guid> GetPublisherSetNameGuidTable ()
{
GS::HashTable<GS::UniString, API_Guid> table;
Int32 numberOfPublisherSets = 0;
ACAPI_Navigator (APINavigator_GetNavigatorSetNumID, &numberOfPublisherSets);
API_NavigatorSet set = {};
for (Int32 ii = 0; ii < numberOfPublisherSets; ++ii) {
set.mapId = API_PublisherSets;
if (ACAPI_Navigator (APINavigator_GetNavigatorSetID, &set, &ii) == NoError) {
table.Add (set.name, set.rootGuid);
}
}
return table;
}
static GS::Optional<IO::Location> GetApplicationLocation ()
{
IO::Location applicationFileLocation;
GSErrCode error = IO::fileSystem.GetSpecialLocation (IO::FileSystem::ApplicationFile, &applicationFileLocation);
if (error != NoError) {
return GS::NoValue;
}
return applicationFileLocation;
}
constexpr const char* ErrorResponseField = "error";
constexpr const char* ErrorCodeResponseField = "code";
constexpr const char* ErrorMessageResponseField = "message";
static GS::ObjectState CreateErrorResponse(APIErrCodes errorCode, const char* errorMessage)
{
GS::ObjectState error;
error.Add(ErrorCodeResponseField, errorCode);
error.Add(ErrorMessageResponseField, errorMessage);
return GS::ObjectState(ErrorResponseField, error);
}
// --- AdditionalJSONCommand ----------------------------------------------------------------------------------
GS::String AdditionalJSONCommand::GetNamespace() const
{
return AdditionalJSONCommandsNamespace;
}
GS::Optional<GS::UniString> AdditionalJSONCommand::GetSchemaDefinitions() const
{
return {};
}
GS::Optional<GS::UniString> AdditionalJSONCommand::GetInputParametersSchema() const
{
return {};
}
GS::Optional<GS::UniString> AdditionalJSONCommand::GetResponseSchema() const
{
return GS::UniString::Printf(R"({
"type": "object",
"properties": {
"%s": {
"$ref": "APITypes.json#/definitions/Error"
}
},
"additionalProperties": false,
"required": []
})",
ErrorResponseField);
}
void AdditionalJSONCommand::OnResponseValidationFailed(const GS::ObjectState& /*response*/) const
{
ACAPI_WriteReport(" JSON Validation Failed", true);
}
// ---------- KeyNote Command -------------------------------
GS::String KeyNoteCommand::GetName() const
{
//ACAPI_WriteReport("inside ketnotecommand getname", false);
return "KeyNote";
}
constexpr const char* SymbolShapeParameterField = "Symbol Shape";
constexpr const char* TextPenParameterField = "Text Pen";
constexpr const char* FontTypeParameterField = "Font Type";
constexpr const char* FontSizeParameterField = "Font Size";
constexpr const char* FontstyleBoldParameterField = "Font Style Bold";
constexpr const char* FontStyleItalicParameterField = "Font Style Italic";
constexpr const char* FontStyleUnderLineParameterField = "Font Style UnderLine";
constexpr const char* ContourPenParameterField = "Contour Pen";
constexpr const char* FillTypeParameterField = "Fill Type";
constexpr const char* FillPenParameterField = "Fill Pen";
constexpr const char* FillBackGroundPenParameterField = "Fill BackGround Pen";
constexpr const char* TextOrientationParameterField = "typeTextRotation";
constexpr const char* ClassificationParameterField = "Classification";
constexpr const char* CircleDiameterParameterField = "CircleDiameter";
constexpr const char* DisciplineParameterField = "Discipline";
constexpr const char* TextParameterField = "txt";
constexpr const char* NoteParameterField = "note";
//constexpr const char* ErrorMessageResponseField = "errormessage";
GS::Optional<GS::UniString> KeyNoteCommand::GetInputParametersSchema() const
{
//ACAPI_WriteReport("inside keynotecommand getinputparamschema", true);
return GS::UniString::Printf(R"({
"type": "object",
"properties": {
"%s": {
"type": "string",
"description": "The name of the Library Shape",
"minLength": 1
},
"%s": {
"type": "integer",
"description": "Text Pen Number.",
"minLength": 1
},
"%s": {
"type": "string",
"description": "The name of the Font",
"minLength": 1
},
"%s": {
"type": "number",
"description": "Font Size in mm",
"minLength": 1
},
"%s": {
"type": "boolean",
"description": "Bold Toggle",
"minLength": 1
},
"%s": {
"type": "boolean",
"description": "Italic Toggle",
"minLength": 1
},
"%s": {
"type": "boolean",
"description": "UnderLine Toggle",
"minLength": 1
},
"%s": {
"type": "integer",
"description": "Contour Pen Number.",
"minLength": 1
},
"%s": {
"type": "integer",
"description": "Fill Type Pen Number",
"minLength": 1
},
"%s": {
"type": "integer",
"description": "Fill Pen Number",
"minLength": 1
},
"%s": {
"type": "integer",
"description": "Fill BackGround Pen Number",
"minLength": 1
},
"%s": {
"type": "string",
"description": "Type Rotation",
"minLength": 1
},
"%s": {
"type": "string",
"description": "Classification",
"minLength": 1
},
"%s": {
"type": "string",
"description": "Discipline",
"minLength": 1
},
"%s": {
"type": "number",
"description": "Diameter",
"minLength": 1
},
"%s": {
"type": "string",
"description": "txt",
"minLength": 1
},
"%s": {
"type": "string",
"description": "note",
"minLength": 1
}
},
"additionalProperties": false,
"required": [
"%s"
]
})",
SymbolShapeParameterField, TextPenParameterField, FontTypeParameterField,FontSizeParameterField,
FontstyleBoldParameterField, FontStyleItalicParameterField, FontStyleUnderLineParameterField,
ContourPenParameterField, FillTypeParameterField, FillPenParameterField,FillBackGroundPenParameterField,
TextOrientationParameterField, ClassificationParameterField, DisciplineParameterField,
CircleDiameterParameterField, TextParameterField, NoteParameterField,SymbolShapeParameterField
);
// Never gets here because of above return
//ACAPI_WriteReport("At End of keynotecommand getinputparamschema", true);
}
keyParams keysettings;
GS::ObjectState KeyNoteCommand::Execute(const GS::ObjectState& parameters, GS::ProcessControl& /*processControl*/) const
{
//ACAPI_WriteReport("inside keynotecommand execute", true);
// transfer style settings
parameters.Get(SymbolShapeParameterField,keysettings.shape);
parameters.Get(TextPenParameterField, keysettings.tpen);
parameters.Get(FontTypeParameterField, keysettings.fontType);
parameters.Get(FontSizeParameterField, keysettings.fsz);
parameters.Get(FontstyleBoldParameterField, keysettings.gs_text_style_bold);
parameters.Get(FontStyleItalicParameterField, keysettings.gs_text_style_italic);
parameters.Get(FontStyleUnderLineParameterField, keysettings.gs_text_style_underline);
parameters.Get(ContourPenParameterField, keysettings.gs_cont_pen);
parameters.Get(FillTypeParameterField, keysettings.gs_fill_type);
parameters.Get(FillPenParameterField, keysettings.gs_fill_pen);
parameters.Get(FillBackGroundPenParameterField, keysettings.gs_back_pen);
parameters.Get(TextOrientationParameterField, keysettings.typeTextRotation);
parameters.Get(ClassificationParameterField, keysettings.classification);
parameters.Get(DisciplineParameterField, keysettings.discipline);
parameters.Get(CircleDiameterParameterField, keysettings.shapeDiameter);
parameters.Get(TextParameterField, keysettings.txt);
parameters.Get(NoteParameterField, keysettings.note);
// end of transfer section
// Activate Keynote Code
//ACAPI_WriteReport("End of execute before DoPlaceSymbol %s", true, keysettings.shape.ToCStr().Get());
GSErrCode err = Do_PlaceKeySymbol(keysettings);
if (err != NoError) {
return GS::ObjectState(ErrorMessageResponseField, "Keynote failed. Check parameters");
}
return {};
}
// ---------- End KeyNote Command ------------------------------- | 29.474074 | 120 | 0.722418 | [
"object",
"shape"
] |
a1ba9d3a8fd0282749a9e341862a3618aa3c8636 | 12,897 | cpp | C++ | src/qt/src/3rdparty/webkit/Source/WebCore/platform/network/HTTPParsers.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 46 | 2015-01-08T14:32:34.000Z | 2022-02-05T16:48:26.000Z | src/qt/src/3rdparty/webkit/Source/WebCore/platform/network/HTTPParsers.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 7 | 2015-01-20T14:28:12.000Z | 2017-01-18T17:21:44.000Z | src/qt/src/3rdparty/webkit/Source/WebCore/platform/network/HTTPParsers.cpp | ant0ine/phantomjs | 8114d44a28134b765ab26b7e13ce31594fa81253 | [
"BSD-3-Clause"
] | 14 | 2015-10-27T06:17:48.000Z | 2020-03-03T06:15:50.000Z | /*
* Copyright (C) 2006 Alexey Proskuryakov (ap@webkit.org)
* Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2009 Torch Mobile Inc. http://www.torchmobile.com/
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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 "config.h"
#include "HTTPParsers.h"
#include "ResourceResponseBase.h"
#include "PlatformString.h"
#include <wtf/text/CString.h>
#include <wtf/DateMath.h>
using namespace WTF;
namespace WebCore {
// true if there is more to parse
static inline bool skipWhiteSpace(const String& str, unsigned& pos, bool fromHttpEquivMeta)
{
unsigned len = str.length();
if (fromHttpEquivMeta) {
while (pos != len && str[pos] <= ' ')
++pos;
} else {
while (pos != len && (str[pos] == '\t' || str[pos] == ' '))
++pos;
}
return pos != len;
}
// Returns true if the function can match the whole token (case insensitive).
// Note: Might return pos == str.length()
static inline bool skipToken(const String& str, unsigned& pos, const char* token)
{
unsigned len = str.length();
while (pos != len && *token) {
if (toASCIILower(str[pos]) != *token++)
return false;
++pos;
}
return true;
}
ContentDispositionType contentDispositionType(const String& contentDisposition)
{
if (contentDisposition.isEmpty())
return ContentDispositionNone;
// Some broken sites just send
// Content-Disposition: ; filename="file"
// screen those out here.
if (contentDisposition.startsWith(";"))
return ContentDispositionNone;
if (contentDisposition.startsWith("inline", false))
return ContentDispositionInline;
// Some broken sites just send
// Content-Disposition: filename="file"
// without a disposition token... screen those out.
if (contentDisposition.startsWith("filename", false))
return ContentDispositionNone;
// Also in use is Content-Disposition: name="file"
if (contentDisposition.startsWith("name", false))
return ContentDispositionNone;
// We have a content-disposition of "attachment" or unknown.
// RFC 2183, section 2.8 says that an unknown disposition
// value should be treated as "attachment"
return ContentDispositionAttachment;
}
bool parseHTTPRefresh(const String& refresh, bool fromHttpEquivMeta, double& delay, String& url)
{
unsigned len = refresh.length();
unsigned pos = 0;
if (!skipWhiteSpace(refresh, pos, fromHttpEquivMeta))
return false;
while (pos != len && refresh[pos] != ',' && refresh[pos] != ';')
++pos;
if (pos == len) { // no URL
url = String();
bool ok;
delay = refresh.stripWhiteSpace().toDouble(&ok);
return ok;
} else {
bool ok;
delay = refresh.left(pos).stripWhiteSpace().toDouble(&ok);
if (!ok)
return false;
++pos;
skipWhiteSpace(refresh, pos, fromHttpEquivMeta);
unsigned urlStartPos = pos;
if (refresh.find("url", urlStartPos, false) == urlStartPos) {
urlStartPos += 3;
skipWhiteSpace(refresh, urlStartPos, fromHttpEquivMeta);
if (refresh[urlStartPos] == '=') {
++urlStartPos;
skipWhiteSpace(refresh, urlStartPos, fromHttpEquivMeta);
} else
urlStartPos = pos; // e.g. "Refresh: 0; url.html"
}
unsigned urlEndPos = len;
if (refresh[urlStartPos] == '"' || refresh[urlStartPos] == '\'') {
UChar quotationMark = refresh[urlStartPos];
urlStartPos++;
while (urlEndPos > urlStartPos) {
urlEndPos--;
if (refresh[urlEndPos] == quotationMark)
break;
}
// https://bugs.webkit.org/show_bug.cgi?id=27868
// Sometimes there is no closing quote for the end of the URL even though there was an opening quote.
// If we looped over the entire alleged URL string back to the opening quote, just go ahead and use everything
// after the opening quote instead.
if (urlEndPos == urlStartPos)
urlEndPos = len;
}
url = refresh.substring(urlStartPos, urlEndPos - urlStartPos).stripWhiteSpace();
return true;
}
}
double parseDate(const String& value)
{
return parseDateFromNullTerminatedCharacters(value.utf8().data());
}
String filenameFromHTTPContentDisposition(const String& value)
{
Vector<String> keyValuePairs;
value.split(';', keyValuePairs);
unsigned length = keyValuePairs.size();
for (unsigned i = 0; i < length; i++) {
size_t valueStartPos = keyValuePairs[i].find('=');
if (valueStartPos == notFound)
continue;
String key = keyValuePairs[i].left(valueStartPos).stripWhiteSpace();
if (key.isEmpty() || key != "filename")
continue;
String value = keyValuePairs[i].substring(valueStartPos + 1).stripWhiteSpace();
// Remove quotes if there are any
if (value[0] == '\"')
value = value.substring(1, value.length() - 2);
return value;
}
return String();
}
String extractMIMETypeFromMediaType(const String& mediaType)
{
Vector<UChar, 64> mimeType;
unsigned length = mediaType.length();
mimeType.reserveCapacity(length);
for (unsigned i = 0; i < length; i++) {
UChar c = mediaType[i];
if (c == ';')
break;
// While RFC 2616 does not allow it, other browsers allow multiple values in the HTTP media
// type header field, Content-Type. In such cases, the media type string passed here may contain
// the multiple values separated by commas. For now, this code ignores text after the first comma,
// which prevents it from simply failing to parse such types altogether. Later for better
// compatibility we could consider using the first or last valid MIME type instead.
// See https://bugs.webkit.org/show_bug.cgi?id=25352 for more discussion.
if (c == ',')
break;
// FIXME: The following is not correct. RFC 2616 allows linear white space before and
// after the MIME type, but not within the MIME type itself. And linear white space
// includes only a few specific ASCII characters; a small subset of isSpaceOrNewline.
// See https://bugs.webkit.org/show_bug.cgi?id=8644 for a bug tracking part of this.
if (isSpaceOrNewline(c))
continue;
mimeType.append(c);
}
if (mimeType.size() == length)
return mediaType;
return String(mimeType.data(), mimeType.size());
}
String extractCharsetFromMediaType(const String& mediaType)
{
unsigned int pos, len;
findCharsetInMediaType(mediaType, pos, len);
return mediaType.substring(pos, len);
}
void findCharsetInMediaType(const String& mediaType, unsigned int& charsetPos, unsigned int& charsetLen, unsigned int start)
{
charsetPos = start;
charsetLen = 0;
size_t pos = start;
unsigned length = mediaType.length();
while (pos < length) {
pos = mediaType.find("charset", pos, false);
if (pos == notFound || pos == 0) {
charsetLen = 0;
return;
}
// is what we found a beginning of a word?
if (mediaType[pos-1] > ' ' && mediaType[pos-1] != ';') {
pos += 7;
continue;
}
pos += 7;
// skip whitespace
while (pos != length && mediaType[pos] <= ' ')
++pos;
if (mediaType[pos++] != '=') // this "charset" substring wasn't a parameter name, but there may be others
continue;
while (pos != length && (mediaType[pos] <= ' ' || mediaType[pos] == '"' || mediaType[pos] == '\''))
++pos;
// we don't handle spaces within quoted parameter values, because charset names cannot have any
unsigned endpos = pos;
while (pos != length && mediaType[endpos] > ' ' && mediaType[endpos] != '"' && mediaType[endpos] != '\'' && mediaType[endpos] != ';')
++endpos;
charsetPos = pos;
charsetLen = endpos - pos;
return;
}
}
XSSProtectionDisposition parseXSSProtectionHeader(const String& header)
{
String stippedHeader = header.stripWhiteSpace();
if (stippedHeader.isEmpty())
return XSSProtectionEnabled;
if (stippedHeader[0] == '0')
return XSSProtectionDisabled;
unsigned length = header.length();
unsigned pos = 0;
if (stippedHeader[pos++] == '1'
&& skipWhiteSpace(stippedHeader, pos, false)
&& stippedHeader[pos++] == ';'
&& skipWhiteSpace(stippedHeader, pos, false)
&& skipToken(stippedHeader, pos, "mode")
&& skipWhiteSpace(stippedHeader, pos, false)
&& stippedHeader[pos++] == '='
&& skipWhiteSpace(stippedHeader, pos, false)
&& skipToken(stippedHeader, pos, "block")
&& pos == length)
return XSSProtectionBlockEnabled;
return XSSProtectionEnabled;
}
String extractReasonPhraseFromHTTPStatusLine(const String& statusLine)
{
size_t spacePos = statusLine.find(' ');
// Remove status code from the status line.
spacePos = statusLine.find(' ', spacePos + 1);
return statusLine.substring(spacePos + 1);
}
bool parseRange(const String& range, long long& rangeOffset, long long& rangeEnd, long long& rangeSuffixLength)
{
// The format of "Range" header is defined in RFC 2616 Section 14.35.1.
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35.1
// We don't support multiple range requests.
rangeOffset = rangeEnd = rangeSuffixLength = -1;
// The "bytes" unit identifier should be present.
static const char bytesStart[] = "bytes=";
if (!range.startsWith(bytesStart, false))
return false;
String byteRange = range.substring(sizeof(bytesStart) - 1);
// The '-' character needs to be present.
int index = byteRange.find('-');
if (index == -1)
return false;
// If the '-' character is at the beginning, the suffix length, which specifies the last N bytes, is provided.
// Example:
// -500
if (!index) {
String suffixLengthString = byteRange.substring(index + 1).stripWhiteSpace();
bool ok;
long long value = suffixLengthString.toInt64Strict(&ok);
if (ok)
rangeSuffixLength = value;
return true;
}
// Otherwise, the first-byte-position and the last-byte-position are provied.
// Examples:
// 0-499
// 500-
String firstBytePosStr = byteRange.left(index).stripWhiteSpace();
bool ok;
long long firstBytePos = firstBytePosStr.toInt64Strict(&ok);
if (!ok)
return false;
String lastBytePosStr = byteRange.substring(index + 1).stripWhiteSpace();
long long lastBytePos = -1;
if (!lastBytePosStr.isEmpty()) {
lastBytePos = lastBytePosStr.toInt64Strict(&ok);
if (!ok)
return false;
}
if (firstBytePos < 0 || !(lastBytePos == -1 || lastBytePos >= firstBytePos))
return false;
rangeOffset = firstBytePos;
rangeEnd = lastBytePos;
return true;
}
}
| 34.300532 | 141 | 0.63224 | [
"vector"
] |
a1c11aa300f7be0768214aad66b2cc6e052ec21f | 5,140 | cpp | C++ | game_upgrade.cpp | AutoLS/DodgeTheBlocks | 1a2ee586ce82a8d9ebdfab074d793dd1f4b30eba | [
"MIT"
] | null | null | null | game_upgrade.cpp | AutoLS/DodgeTheBlocks | 1a2ee586ce82a8d9ebdfab074d793dd1f4b30eba | [
"MIT"
] | null | null | null | game_upgrade.cpp | AutoLS/DodgeTheBlocks | 1a2ee586ce82a8d9ebdfab074d793dd1f4b30eba | [
"MIT"
] | null | null | null | #include "game_upgrade.h"
void UpdateUpgradeMenu(upgrade_menu* UpgradeMenu, player_profile* Profile,
game_renderer* Renderer, render* Graphics)
{
TTF_Font* Font = Renderer->RenderFonts[DEFAULT_FONT_MEDIUM];
object_data Object = Renderer->RenderObjects[R_OBJECT_RECT];
glDeleteTextures(1, &UpgradeMenu->SkillPointText.Texture);
char Buffer[50] = {};
stbsp_sprintf(Buffer, "Skill points: %d", Profile->SkillPoints);
UpgradeMenu->SkillPointText = LoadRenderText(Font, Buffer, Object);
SetRenderTextPos(Graphics, &UpgradeMenu->SkillPointText,
V2(-15, 15), TEXT_POSITION_TOP_RIGHT);
for(int i = 0; i < UPGRADE_TYPE_MAX; ++i)
{
glDeleteTextures(1, &UpgradeMenu->LevelText[i].Texture);
char Buffer[10] = {};
stbsp_sprintf(Buffer, "%d", Profile->UpgradeLevels[i]);
UpgradeMenu->LevelText[i] = LoadRenderText(Font, Buffer, Object);
SetRenderTextPos(Graphics, &UpgradeMenu->LevelText[i],
V2(300 + 150/2,
UpgradeMenu->UpgradeText[i].Pos.y-
UpgradeMenu->LevelText[i].Dim.y*0.5f),
TEXT_POSITION_TOP_LEFT);
}
}
upgrade_menu InitUpgradeMenu(game_renderer* Renderer, render* Graphics,
player_profile* Profile)
{
TTF_Font* Font = Renderer->RenderFonts[DEFAULT_FONT_MEDIUM];
TTF_Font* FontL = Renderer->RenderFonts[DEFAULT_FONT_LARGE];
uint32 Shader = Renderer->Shaders[RENDERER_TEXTURED];
object_data Object = Renderer->RenderObjects[R_OBJECT_RECT];
upgrade_menu UpgradeMenu = {};
char* UpgradeText[] =
{
"Attack speed",
"Health",
"Meteor spawn",
"Item spawn",
"Item duration",
"Stage duration"
};
char* InfoText[] =
{
"Increases laser shooting speed.",
"Increase HP by 1 each 5 levels. MAX LV: 50",
"Increase the spawn time for meteor.",
"Reduce the spawn time for items.",
"Increase item's duration.",
"Decrease stage effect duration."
};
render_text PlusText = LoadRenderText(FontL, "+", Object);
render_text MinusText = LoadRenderText(FontL, "-", Object);
uint32 InfoTexture = LoadTextureGL("ast/information.png", true, false);
for(int i = 0; i < UPGRADE_TYPE_MAX; ++i)
{
UpgradeMenu.UpgradeText[i] = LoadRenderText(Font, UpgradeText[i], Object);
SetRenderTextPos(Graphics, &UpgradeMenu.UpgradeText[i],
V2(15, 100 + (i*50.0f)), TEXT_POSITION_TOP_LEFT);
UpgradeMenu.InfoBlock[i] =
CreateHoverBlock(InfoTexture, InfoText[i],
Renderer,
V2(250, UpgradeMenu.UpgradeText[i].Pos.y),
V2(30, 30), Color(0, 0, 0), true);
SetRenderTextPos(Graphics, &MinusText,
V2(300, UpgradeMenu.UpgradeText[i].Pos.y-MinusText.Dim.y*0.5f),
TEXT_POSITION_TOP_LEFT);
UpgradeMenu.Minus[i] = CreateButton(UI_BUTTON_PLAIN_TEXT, 0, 0, MinusText);
SetRenderTextPos(Graphics, &PlusText,
V2(450, UpgradeMenu.UpgradeText[i].Pos.y-PlusText.Dim.y*0.5f),
TEXT_POSITION_TOP_LEFT);
UpgradeMenu.Plus[i] = CreateButton(UI_BUTTON_PLAIN_TEXT, 0, 0, PlusText);
char Buffer[10] = {};
stbsp_sprintf(Buffer, "%d", Profile->UpgradeLevels[i]);
UpgradeMenu.LevelText[i] = LoadRenderText(Font, Buffer, Object);
SetRenderTextPos(Graphics, &UpgradeMenu.LevelText[i],
V2(300 + 150/2,
UpgradeMenu.UpgradeText[i].Pos.y-
UpgradeMenu.LevelText[i].Dim.y*0.5f),
TEXT_POSITION_TOP_LEFT);
}
UpgradeMenu.TitleText = LoadRenderText(Renderer->RenderFonts[DEFAULT_FONT_LARGE],
"UPGRADES", Object);
SetRenderTextPos(Graphics, &UpgradeMenu.TitleText, V2(15, 15), TEXT_POSITION_TOP_LEFT);
char Buffer[50] = {};
stbsp_sprintf(Buffer, "Skill points: %d", Profile->SkillPoints);
UpgradeMenu.SkillPointText = LoadRenderText(Font, Buffer, Object);
SetRenderTextPos(Graphics, &UpgradeMenu.SkillPointText,
V2(-15, 15), TEXT_POSITION_TOP_RIGHT);
render_text BackText =
LoadRenderText(Renderer->RenderFonts[DEFAULT_FONT_LARGE], "BACK", Object);
SetRenderTextPos(Graphics, &BackText, V2(15, -15), TEXT_POSITION_BOTTOM_LEFT);
UpgradeMenu.BackButton = CreateButton(UI_BUTTON_PLAIN_TEXT, 0, 0, BackText);
return UpgradeMenu;
}
void RenderUpgradeMenu(upgrade_menu* UpgradeMenu, game_renderer* Renderer, render* Graphics)
{
SetScreenSpaceProjection(Renderer->Shaders[RENDERER_TEXTURED],
Graphics->WinDim);
SetScreenSpaceProjection(Renderer->Shaders[RENDERER_PRIMITIVES],
Graphics->WinDim);
RenderText(Renderer->Shaders[RENDERER_TEXTURED],
&UpgradeMenu->TitleText,
Color(), false);
RenderText(Renderer->Shaders[RENDERER_TEXTURED],
&UpgradeMenu->SkillPointText,
Color(), false);
for(int i = 0; i < UPGRADE_TYPE_MAX; ++i)
{
RenderText(Renderer->Shaders[RENDERER_TEXTURED],
&UpgradeMenu->UpgradeText[i],
Color(), false);
RenderButton(&UpgradeMenu->Plus[i], Renderer);
RenderButton(&UpgradeMenu->Minus[i], Renderer);
RenderText(Renderer->Shaders[RENDERER_TEXTURED],
&UpgradeMenu->LevelText[i], Color(), false);
RenderHoverBlock(&UpgradeMenu->InfoBlock[i], Renderer);
}
RenderButton(&UpgradeMenu->BackButton, Renderer);
} | 37.794118 | 93 | 0.696693 | [
"render",
"object"
] |
a1c146a4b21f37f995b08fb5d300de65635f3195 | 2,601 | cc | C++ | src/pmem/PersistentPtr.cc | ecmwf/pmem | e7fc7a18ec8ac928730812b4e7a0565a18295fcd | [
"Apache-2.0"
] | null | null | null | src/pmem/PersistentPtr.cc | ecmwf/pmem | e7fc7a18ec8ac928730812b4e7a0565a18295fcd | [
"Apache-2.0"
] | null | null | null | src/pmem/PersistentPtr.cc | ecmwf/pmem | e7fc7a18ec8ac928730812b4e7a0565a18295fcd | [
"Apache-2.0"
] | null | null | null | /*
* (C) Copyright 1996-2015 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation
* nor does it submit to any jurisdiction.
*/
/*
* This software was developed as part of the EC H2020 funded project NextGenIO
* (Project ID: 671951) www.nextgenio.eu
*/
/// @author Simon Smart
/// @date Feb 2016
#include "eckit/log/Log.h"
#include "pmem/AtomicConstructor.h"
#include "pmem/LibPMem.h"
#include "pmem/PersistentPtr.h"
using namespace eckit;
namespace pmem {
// -------------------------------------------------------------------------------------------------
/// This is a static routine that can be passed to the atomic allocation routines. All the logic
/// should be passed in as the functor AtomicConstructor<T>.
///
/// @note the void*arg argument MUST be interpreted as const, otherwise we break the ability to pass
/// const references to constructor objects into allocate.
int pmem_constructor(PMEMobjpool * pool, void * obj, void * arg) {
const AtomicConstructorBase * constr_fn = reinterpret_cast<const AtomicConstructorBase*>(arg);
Log::debug<LibPMem>() << "Constructing persistent object of " << constr_fn->size()
<< " bytes at: " << obj << std::endl;
// The constructor should return zero for success. If it has failed (e.g. if a subobjects
// allocation has failed) this needs to be propagated upwards so that the block reservation
// can be correctly unwound.
int ret = constr_fn->build(obj);
if (ret != 0)
::pmemobj_persist(pool, obj, constr_fn->size());
return ret;
}
// -------------------------------------------------------------------------------------------------
PersistentPtrBase::PersistentPtrBase() :
oid_(OID_NULL) {}
PersistentPtrBase::PersistentPtrBase(PMEMoid oid) :
oid_(oid) {}
void PersistentPtrBase::free() {
::pmemobj_free(&oid_);
}
void PersistentPtrBase::nullify() {
oid_ = OID_NULL;
}
bool PersistentPtrBase::null() const {
return oid_.off == 0;
}
PMEMoid PersistentPtrBase::raw() const {
return oid_;
}
void PersistentPtrBase::setPersist(PMEMobjpool * pool, PMEMoid oid) {
oid_ = oid;
::pmemobj_persist(pool, &oid_, sizeof(oid_));
}
// -------------------------------------------------------------------------------------------------
} // namespace pmem
| 27.378947 | 100 | 0.614764 | [
"object"
] |
a1c195c7e5d8b267c83e6355f6f382740c9f407e | 6,049 | cpp | C++ | src/JRectangle.cpp | jildertviet/ofxJVisuals | 878c5b0e7a7dda49ddb71b3f5d19c13987706a73 | [
"MIT"
] | null | null | null | src/JRectangle.cpp | jildertviet/ofxJVisuals | 878c5b0e7a7dda49ddb71b3f5d19c13987706a73 | [
"MIT"
] | 6 | 2021-10-16T07:10:04.000Z | 2021-12-26T13:23:54.000Z | src/JRectangle.cpp | jildertviet/ofxJVisuals | 878c5b0e7a7dda49ddb71b3f5d19c13987706a73 | [
"MIT"
] | null | null | null | //
// JRectangle
//
// Created by Jildert Viet on 24-01-16.
//
//
#include "JRectangle.hpp"
JRectangle::JRectangle(){
setType("JRectangle");
}
JRectangle::JRectangle(float millisTime, ofVec2f loc, ofVec2f size, ofColor color, float attack, float release, ofVec2f direction, bool move){
setType("JRectangle");
setEndTime(millisTime);
this->loc = loc; this->size = size;
colors.clear();
colors.push_back(color);
active=true;
// setEnvelope(attack, millisTime-attack-release,release);
addEnvAlpha(vector<float>{0, (float)colors[0].a, (float)colors[0].a, 0}, vector<float>{attack, millisTime-attack-release,release});
this->direction = direction;
speed = 1;
bMove = move;
}
JRectangle::JRectangle(ofVec3f loc, ofVec3f size){
setType("JRectangle");
this->loc = loc; this->size = size; active=false;
bMove = false;
direction = ofVec2f(-1,0);
speed = 1;
}
void JRectangle::ownDtor(){
removeFromVector();
}
void JRectangle::setAlpha(unsigned char alpha){
if(m){
for(char i=0; i<m->getNumColors(); i++){
ofColor c = m->getColor(i);
c.a = alpha;
m->setColor(i, c);
}
}
}
void JRectangle::setQuadColor(ofColor a, ofColor b, ofColor c, ofColor d){
if(m)
delete m;
m = new ofMesh();
m->setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
m->addVertex(glm::vec3(0,0,0));
m->addColor(a);
m->addVertex(glm::vec3(size.x, 0, 0));
m->addColor(b);
m->addVertex(glm::vec3(0, size.y, 0));
m->addColor(d); // Swapped, so color adding is clockwise
m->addVertex(glm::vec3(size.x, size.y, 0));
m->addColor(c);
}
void JRectangle::display(){
ofSetColor(colors[0]);
if(bFill){
ofFill();
} else{
ofNoFill();
}
ofPushMatrix();
if(!m){
ofTranslate(loc + (size*0.5));
ofRotateXDeg(rotation.x);
ofRotateYDeg(rotation.y);
ofRotateZDeg(rotation.z);
ofTranslate(-(size*0.5));
// ofTranslate(loc);
if(size.z){
ofDrawBox(0, 0, 0, size.x, size.y, size.z);
} else{
ofDrawRectangle(0, 0, size.x, size.y);
}
// ofTranslate(-size*0.5); // ?
// ofRotateZDeg(rotation.z);
// ofTranslate(size*0.5);
} else{
ofTranslate(loc + (size*0.5)); // This wasn't here before... (13-01-2021_
ofRotateXDeg(rotation.x);
ofRotateYDeg(rotation.y);
ofRotateZDeg(rotation.z);
ofTranslate(-(size*0.5));
m->draw();
}
ofPopMatrix();
ofFill();
}
void JRectangle::specificFunction(){
if(getNumEnv()){
if(m){
setAlpha(colors[0].a); // Transfer colors[0] alpha to mesh alpha
}
}
move();
imageFloating(); // virtual
}
void JRectangle::jump(ofVec2f distance){
loc += distance;
}
void JRectangle::noDank(){
setEndTime(400);
loc = ofVec2f(ofRandomWidth(), 0);
size = ofVec2f(100, ofGetWindowHeight());
active=true;
int attack = 10;
int release = 300;
int millisTime = 400;
addEnvAlpha(attack, millisTime-attack-release,release);
if(ofRandom(-1,1)>0){
direction = ofVec2f(-1,0);
} else{
direction = ofVec2f(1,0);
}
speed = 1;
bMove = true;
}
void JRectangle::addPtr(JRectangle** p){
toClear.push_back((Event**)p);
}
void JRectangle::addVector(vector<JRectangle*>* v){
this->v = v;
}
void JRectangle::divide(){
ofVec2f newSize = size/2.;
ofColor color = colors[(int)ofRandom(colors.size())];
color.a = ofRandom(100)+100;
for(int i=0; i<2; i++){
ofVec2f newLoc = loc+ofVec2f(i*newSize.x, i*newSize.y);
if(newLoc.x<ofGetWindowWidth() && newLoc.y<ofGetWindowHeight()){
children.push_back(new JRectangle(newSize, newLoc));
numChildren++;
JRectangle* c = children.back();
if(c->bMove){
c->bMove = true;
} else{
c->bMove = false;
}
c->speed = speed;
c->colors[0] = color;
}
newLoc = ofVec2f(newSize.x*2,0)+loc+ofVec2f(i*newSize.x, i*newSize.y);
if(newLoc.x<ofGetWindowWidth() && newLoc.y<ofGetWindowHeight()){
children.push_back(new JRectangle(newSize, newLoc));
numChildren++;
JRectangle* c = children.back();
if(c->bMove){
c->bMove = true;
} else{
c->bMove = false;
}
c->speed = speed;
c->colors[0] = color;
}
newLoc = ofVec2f(0, newSize.y*2)+loc+ofVec2f(i*newSize.x, i*newSize.y);
if(newLoc.x<ofGetWindowWidth() && newLoc.y<ofGetWindowHeight()){
children.push_back(new JRectangle(newSize, newLoc));
numChildren++;
JRectangle* c = children.back();
if(c->bMove){
c->bMove = true;
} else{
c->bMove = false;
}
c->speed = speed;
c->colors[0] = color;
}
}
cout << "Num children: " << children.size() << endl;
}
JRectangle* JRectangle::getChild(){
if(numChildren){
return children.back();
children.pop_back();
numChildren--;
} else{
return nullptr;
}
}
void JRectangle::removeFromVector(){
if(v){
for(int i=0; i<v->size(); i++){
if(v->at(i) == this){
v->at(i) = nullptr; // Later remove the nullptrs in vec
cout << "Found self!" << endl;
return;
}
}
}
}
void JRectangle::setHeight(int height){ size.y = height; }
void JRectangle::setWidth(int width){ size.x = width; }
| 26.765487 | 143 | 0.520582 | [
"mesh",
"vector"
] |
a1c69bd36e7d4364d02eb8c400ef4b36a01ced16 | 15,481 | cpp | C++ | GSM/molpro.cpp | awvwgk/molecularGSM | f78925bb142d83095e3f78587ed9cfebc98ea89d | [
"MIT"
] | 42 | 2016-09-08T19:45:41.000Z | 2022-03-17T01:57:38.000Z | GSM/molpro.cpp | awvwgk/molecularGSM | f78925bb142d83095e3f78587ed9cfebc98ea89d | [
"MIT"
] | 12 | 2017-11-08T03:55:50.000Z | 2022-03-11T18:01:57.000Z | GSM/molpro.cpp | awvwgk/molecularGSM | f78925bb142d83095e3f78587ed9cfebc98ea89d | [
"MIT"
] | 17 | 2016-11-14T17:39:50.000Z | 2022-03-17T01:58:59.000Z | #include "molpro.h"
//#include "utils.h"
using namespace std;
//set to 1 to not run molpro
#define SAFE_MODE 0
#define ONLY_RHF 0
#define BASIS631GS 0
#define READ_SCF 1
#define PSPACE 0
//pspace now is 10. //was 100.
#define DYNWEIGHT 0
#define MEMORY 400
#define DIRECT 1
//run molpro for gradient of n, derivative coupling between n,m
int Molpro::run(int n, int m)
{
//printf(" beginning Molpro run! \n"); fflush(stdout);
int runGrad = 1;
if (n<=0)
{
runGrad = 0;
n *= -1;
}
if (n>nstates)
{
printf(" ERROR: n>nstates! (%i>%i) \n",n,nstates);
exit(-1);
}
if (m>nstates)
{
printf(" ERROR: n>nstates! \n");
exit(-1);
}
//if (m==0) printf(" not computing derivative coupling \n");
#if ONLY_RHF
printf(" WARNING: using RHF! \n");
#endif
string filename = infile;
//here construct Molpro input
ofstream inpfile;
string inpfile_string = filename;
inpfile.open(inpfile_string.c_str());
inpfile.setf(ios::fixed);
inpfile.setf(ios::left);
inpfile << setprecision(6);
inpfile << "memory," << MEMORY << ",m" << endl;
inpfile << "file,2," << scratchname << endl;
inpfile << "symmetry,nosym" << endl;
inpfile << "orient,noorient" << endl;
inpfile << "geometry={" << endl;
for (int i=0;i<natoms;i++)
inpfile << " " << anames[i] << " " << xyz[3*i+0] << " " << xyz[3*i+1] << " " << xyz[3*i+2] << " " << endl;
inpfile << "}" << endl;
inpfile << endl << "basis=" << basis << endl << endl;
inpfile << "start,2100.2 !read orbitals" << endl;
#if DIRECT
inpfile << " direct " << endl;
#endif
#if !READ_SCF || ONLY_RHF
//recalculate HF at each iteration
inpfile << "hf" << endl;
#endif
#if !ONLY_RHF
//first two settings from AIMS molpro example
//inpfile << "gthresh,twoint=1.0d-13" << endl;
//inpfile << "gthresh,energy=1.0d-7,gradient=1.0d-2" << endl;
//inpfile << "data,copy, 2100.2, 3000.2" << endl;
if (runGrad)
{
inpfile << "{casscf" << endl;
inpfile << "closed," << nclosed << " !core orbs" << endl;
inpfile << "occ," << nocc << " !active orbs" << endl;
inpfile << "wf," << nelec << ",1,0 !nelectrons,symm,singlet" << endl;
inpfile << "state," << nstates << " !nstates" << endl;
#if DYNWEIGHT
inpfile << "dynw,-8.0 !dynamic weight" << endl;
#endif
//if (nstates>=3)
// inpfile << "weight,0.2,0.4,0.4 !state averaging" << endl;
//inpfile << "maxiter,40 " << endl;
inpfile << "CPMCSCF,GRAD," << n << ".1" << endl;
inpfile << "ciguess,2501.2" << endl;
inpfile << "save,ci=2501.2" << endl;
inpfile << "orbital,2100.2 !write orbitals" << endl;
//inpfile << "{ iterations" << endl;
//inpfile << " do,diagci,1,to,20 }" << endl;
#if PSPACE
inpfile << "pspace,100.0" << endl;
#endif
//inpfile << "dm,2105.2" << endl;
//inpfile << "diab,3000.2,save=3000.2" << endl;
inpfile << "}" << endl;
inpfile << endl;
#endif
inpfile << "{forces; varsav}" << endl;
#if 0
inpfile << "show,gradx" << endl;
inpfile << "show,grady" << endl;
inpfile << "show,gradz" << endl;
#endif
inpfile << endl;
}
#if !ONLY_RHF
if (m>0)
{
inpfile << "{casscf" << endl;
inpfile << "closed," << nclosed << " !core orbs" << endl;
inpfile << "occ," << nocc << " !active orbs" << endl;
inpfile << "wf," << nelec << ",1,0 !nelectrons,symm,singlet" << endl;
inpfile << "state," << nstates << " !nstates" << endl;
#if DYNWEIGHT
inpfile << "dynw,-8.0 !dynamic weight " << endl;
#endif
//if (nstates>=3)
// inpfile << "weight,0.2,0.4,0.4 !state averaging" << endl;
inpfile << "CPMCSCF,NACM," << n << ".1," << m << ".1 " << endl;
//inpfile << "ciguess,2501.2" << endl;
//inpfile << "save,ci=2501.2" << endl;
inpfile << "orbital,2100.2 !write orbitals" << endl;
//inpfile << "{ iterations" << endl;
//inpfile << " do,diagci,1,to,20 }" << endl;
#if PSPACE
inpfile << "pspace,100.0" << endl;
#endif
//inpfile << "dm,2105.2" << endl;
//inpfile << "diab,3000.2,save=2100.2" << endl;
inpfile << "}" << endl;
inpfile << endl;
inpfile << "{forces; varsav}" << endl;
#if 0
inpfile << "show,gradx" << endl;
inpfile << "show,grady" << endl;
inpfile << "show,gradz" << endl;
#endif
inpfile << endl;
}
#endif
inpfile << endl;
//restart orbitals handled by file,2,...
//inpfile << "start,2100.2" << endl;
#if 0
//varsav puts forces into gradx,grady,gradz
{forces; varsav}
show,gradx
show,grady
show,gradz
table, GRADX, GRADY, GRADZ
save,gopro1.log
#endif
inpfile.close();
#if !SAFE_MODE
//printf(" executing molpro \n"); fflush(stdout);
// string cmd = "/export/zimmerman/paulzim/Molpro_serial/bin/molpro "+filename;
//string cmd = "/export/applications/Molpro/2012.1.9/molprop_2012_1_Linux_x86_64_i8/bin/molpro";
string cmd = "molpro";
// string cmd = "/export/applications/MolproCopy/2012.1.9/molprop_2012_1_Linux_x86_64_i8/bin/molpro";
string nstr = StringTools::int2str(NPROCS,1,"0");
cmd = cmd + " -W scratch";
cmd = cmd + " -n " + nstr + " " + filename;
system(cmd.c_str());
#endif
int error = read_E();
//printf(" error after read_E: %i \n",error);
nrun++;
return 0;
}
int Molpro::seed()
{
//printf(" beginning Molpro run! \n"); fflush(stdout);
#if RHF_ONLY
printf(" skipping prelim run, no MCSCF \n");
return 0;
#endif
printf(" Running preliminary RHF/MCSCF calculation \n");
string filename = infile;
//here construct Molpro input
ofstream inpfile;
string inpfile_string = filename;
inpfile.open(inpfile_string.c_str());
inpfile.setf(ios::fixed);
inpfile.setf(ios::left);
inpfile << setprecision(6);
inpfile << "memory," << MEMORY << ",m" << endl;
inpfile << "file,2," << scratchname << endl;
inpfile << "symmetry,nosym" << endl;
inpfile << "orient,noorient" << endl;
inpfile << "geometry={" << endl;
for (int i=0;i<natoms;i++)
inpfile << " " << anames[i] << " " << xyz[3*i+0] << " " << xyz[3*i+1] << " " << xyz[3*i+2] << " " << endl;
inpfile << "}" << endl;
inpfile << endl << "basis=" << basis << endl << endl;
#if DIRECT
inpfile << " direct " << endl;
#endif
inpfile << "hf" << endl;
//inpfile << "orbital,2100.2 !write orbitals" << endl; //on by default
//write orbital settings etc from file MOLPRO_INIT
for (int i=0;i<nhf_lines;i++)
inpfile << hf_lines[i] << endl;
#if !ONLY_RHF
inpfile << "{casscf" << endl;
inpfile << "closed," << nclosed << " !core orbs" << endl;
inpfile << "occ," << nocc << " !active orbs" << endl;
inpfile << "wf," << nelec << ",1,0 !nelectrons,symm,singlet" << endl;
inpfile << "state," << nstates << " !nstates" << endl;
inpfile << "save,ci=2501.2" << endl;
inpfile << "orbital,2100.2 !write orbitals" << endl;
//inpfile << "{ iterations" << endl;
//inpfile << " do,diagci,1,to,20 }" << endl;
#if PSPACE
inpfile << "pspace,100.0" << endl;
#endif
//inpfile << "dm,2105.2" << endl;
//inpfile << "diab,2100.2,save=3000.2" << endl;
inpfile << "}" << endl;
#if 0
//for diabatic orbitals
inpfile << "{casscf" << endl;
inpfile << "closed," << nclosed << " !core orbs" << endl;
inpfile << "occ," << nocc << " !active orbs" << endl;
inpfile << "wf," << nelec << ",1,0 !nelectrons,symm,singlet" << endl;
inpfile << "state," << nstates << " !nstates" << endl;
inpfile << "diab,2100.2,save=3000.2" << endl;
inpfile << "}" << endl;
//inpfile << "data,copy, 2100.2, 3000.2" << endl;
#endif
#endif
inpfile.close();
#if !SAFE_MODE
//printf(" executing molpro \n"); fflush(stdout);
// string cmd = "/export/zimmerman/paulzim/Molpro_serial/bin/molpro "+filename;
//string cmd = "/export/applications/Molpro/2012.1.9/molprop_2012_1_Linux_x86_64_i8/bin/molpro";
string cmd = "molpro";
// string cmd = "/export/applications/MolproCopy/2012.1.9/molprop_2012_1_Linux_x86_64_i8/bin/molpro";
string nstr = StringTools::int2str(NPROCS,1,"0");
cmd = cmd + " -W scratch";
cmd = cmd + " -n " + nstr + " " + filename;
system(cmd.c_str());
#endif
#if !RHF_ONLY
int error = read_E();
#endif
nrun++;
return 0;
}
double Molpro::getE(int n)
{
#if ONLY_RHF
if (n>1)
{
printf(" WARNING: RHF but getE(%i) \n",n);
return E[0];
}
#endif
if (n<1)
{
printf(" n must be greater than 0 \n");
return -1.;
}
return E[n-1];
}
int Molpro::read_E()
{
//printf(" in Molpro::read_E \n");
ifstream outfilei;
outfilei.open(outfile.c_str());
if (!outfilei){
printf(" Error: couldn't open output file \n");
return 1;
}
string line;
bool success=true;
int found = 0;
while(!outfilei.eof())
{
success=getline(outfilei, line);
if (line.find("MCSCF STATE 1.1 Energy")!=string::npos)
{
//cout << " found: " << line << endl;
int length=StringTools::cleanstring(line);
vector<string> tok_line = StringTools::tokenize(line, " \t");
E[0]=atof(tok_line[4].c_str());
found++;
}
else if (line.find("MCSCF STATE 2.1 Energy")!=string::npos)
{
//cout << " found: " << line << endl;
int length=StringTools::cleanstring(line);
vector<string> tok_line = StringTools::tokenize(line, " \t");
E[1]=atof(tok_line[4].c_str());
found++;
if (nstates==2) break;
}
else if (line.find("MCSCF STATE 3.1 Energy")!=string::npos)
{
//cout << " found: " << line << endl;
int length=StringTools::cleanstring(line);
vector<string> tok_line = StringTools::tokenize(line, " \t");
E[2]=atof(tok_line[4].c_str());
found++;
if (nstates==3) break;
}
else if (line.find("MCSCF STATE 4.1 Energy")!=string::npos)
{
//cout << " found: " << line << endl;
int length=StringTools::cleanstring(line);
vector<string> tok_line = StringTools::tokenize(line, " \t");
E[3]=atof(tok_line[4].c_str());
found++;
if (nstates==4) break;
}
else if (line.find("MCSCF STATE 5.1 Energy")!=string::npos)
{
//cout << " found: " << line << endl;
int length=StringTools::cleanstring(line);
vector<string> tok_line = StringTools::tokenize(line, " \t");
E[4]=atof(tok_line[4].c_str());
found++;
if (nstates==4) break;
}
#if ONLY_RHF
if (line.find("RHF STATE 1.1 Energy")!=string::npos)
{
//cout << " found: " << line << endl;
int length=StringTools::cleanstring(line);
vector<string> tok_line = StringTools::tokenize(line, " \t");
E[0]=atof(tok_line[4].c_str());
found++;
}
#endif
} //end while loop
outfilei.close();
int error = 1;
if (found==nstates) error = 0;
#if 0
for (int i=0;i<nstates;i++)
printf(" E[%i]: %8.6f \n",i,E[i]);
#endif
return error;
}
void Molpro::init_hf(int nhf_lines1, string* hf_lines1)
{
nhf_lines = nhf_lines1;
if (nhf_lines<1) return;
hf_lines = new string[nhf_lines];
for (int i=0;i<nhf_lines;i++)
hf_lines[i] = hf_lines1[i];
return;
}
void Molpro::init(int nstates0, int nclosed0, int nocc0, int nelec0, int natoms0, string* anames0, double* xyz0, int NPROCS0, string basis0)
{
NPROCS = NPROCS0;
infile = "scratch/gopro.com";
outfile = "scratch/gopro.out";
nclosed = nclosed0;
nocc = nocc0;
nelec = nelec0;
basis = basis0;
nhf_lines = 0;
#if 0
//correct values for pyrazine
nclosed = 19;
nocc = 22;
nelec = 42;
#endif
natoms = natoms0;
nstates = nstates0;
E = new double[nstates];
for (int i=0;i<nstates;i++)
E[i] = 0.;
xyz = new double[3*natoms];
anames = new string[3*natoms];
dvec = new double[3*natoms];
grad = new double[3*natoms];
for (int i=0;i<natoms;i++)
{
anames[i] = anames0[i];
xyz[3*i+0] = xyz0[3*i+0];
xyz[3*i+1] = xyz0[3*i+1];
xyz[3*i+2] = xyz0[3*i+2];
}
nrun = 0;
#if DYNWEIGHT
printf(" using dynamic weighting \n");
#endif
// printf(" Done with init for %i states \n",nstates);
#if 0
for (int i=0;i<natoms;i++)
printf(" %s %8.6f %8.6f %8.6f \n",anames[i].c_str(),xyz[3*i+0],xyz[3*i+1],xyz[3*i+2]);
#endif
return;
}
void Molpro::freemem()
{
delete [] E;
delete [] xyz;
delete [] anames;
delete [] grad;
delete [] dvec;
return;
}
int Molpro::getGrad(double* grads)
{
//printf(" in Molpro::getGrad \n");
ifstream outfilei;
outfilei.open(outfile.c_str());
if (!outfilei){
printf(" Error: couldn't open output file \n");
return 1;
}
string line;
bool success=true;
success=getline(outfilei, line);
int cont = 0;
while(!outfilei.eof())
{
success=getline(outfilei, line);
if (line.find("SA-MC GRADIENT FOR STATE")!=string::npos)
{
//cout << " found: " << line << endl;
getline(outfilei,line);
getline(outfilei,line);
getline(outfilei,line);
cont = 1;
break;
}
#if ONLY_RHF
if (line.find("SCF GRADIENT FOR STATE")!=string::npos)
{
//cout << " found: " << line << endl;
getline(outfilei,line);
getline(outfilei,line);
getline(outfilei,line);
cont = 1;
break;
}
#endif
}
if (cont)
for (int i=0;i<natoms;i++)
{
success=getline(outfilei, line);
int length=StringTools::cleanstring(line);
vector<string> tok_line = StringTools::tokenize(line, " \t");
//cout << " RR: " << line << endl;
grad[3*i+0]=atof(tok_line[1].c_str());
grad[3*i+1]=atof(tok_line[2].c_str());
grad[3*i+2]=atof(tok_line[3].c_str());
}
outfilei.close();
#if 0
printf(" XYZ grad (1/Bohr): \n");
for (int i=0;i<natoms;i++)
printf(" %s %8.6f %8.6f %8.6f \n",anames[i].c_str(),grad[3*i+0],grad[3*i+1],grad[3*i+2]);
#endif
for (int i=0;i<3*natoms;i++)
grads[i] = grad[i];///BOHRtoANG;
//printf(" done reading grad \n"); fflush(stdout);
int error = 1;
if (success && cont) error = 0;
return error;
}
int Molpro::getDVec(double* dvecs)
{
//printf(" in Molpro::getDVec \n");
ifstream outfilei;
outfilei.open(outfile.c_str());
if (!outfilei){
printf(" Error: couldn't open output file \n");
return 1;
}
for (int i=0;i<3*natoms;i++)
dvec[i] = 0.;
string line;
bool success=true;
success=getline(outfilei, line);
int cont = 0;
while(!outfilei.eof())
{
success=getline(outfilei, line);
if (line.find("SA-MC NACME FOR STATES")!=string::npos)
{
//cout << " found: " << line << endl;
getline(outfilei,line);
getline(outfilei,line);
getline(outfilei,line);
cont = 1;
break;
}
}
if (cont)
for (int i=0;i<natoms;i++)
{
success=getline(outfilei, line);
int length=StringTools::cleanstring(line);
vector<string> tok_line = StringTools::tokenize(line, " \t");
//cout << " RR: " << line << endl;
dvec[3*i+0]=atof(tok_line[1].c_str());
dvec[3*i+1]=atof(tok_line[2].c_str());
dvec[3*i+2]=atof(tok_line[3].c_str());
}
outfilei.close();
#if 0
printf(" XYZ dvec (1/Bohr): \n");
for (int i=0;i<natoms;i++)
printf(" %s %8.6f %8.6f %8.6f \n",anames[i].c_str(),dvec[3*i+0],dvec[3*i+1],dvec[3*i+2]);
#endif
for (int i=0;i<3*natoms;i++)
dvecs[i] = dvec[i];///BOHRtoANG;
//printf(" done reading dvec \n"); fflush(stdout);
int error = 1;
if (success && cont) error = 0;
return error;
}
void Molpro::reset(double* xyz1)
{
for (int i=0;i<3*natoms;i++)
xyz[i] = xyz1[i];
return;
}
void Molpro::runname(string name)
{
scratchname = name;
}
void Molpro::clean_scratch()
{
#if !SAFE_MODE
system("rm scratch/gopro.*");
#endif
return;
}
| 24.69059 | 140 | 0.580906 | [
"geometry",
"vector"
] |
a1c7d4dfad37ec9d2619f35419b85884fda925f7 | 12,620 | cpp | C++ | s8_casa/main.cpp | code-mds/grafica | 604a802bf32ce5245abf249a13cadb7eb32e1fd8 | [
"MIT"
] | 1 | 2020-02-23T09:48:25.000Z | 2020-02-23T09:48:25.000Z | s8_casa/main.cpp | code-mds/grafica | 604a802bf32ce5245abf249a13cadb7eb32e1fd8 | [
"MIT"
] | null | null | null | s8_casa/main.cpp | code-mds/grafica | 604a802bf32ce5245abf249a13cadb7eb32e1fd8 | [
"MIT"
] | null | null | null | //glut_test.cpp
//glut_test.cpp
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
#ifdef __APPLE__
// Headers richiesti da OSX
#include <GL/glew.h>
#include <GLUT/glut.h>
#else
// headers richiesti da Windows e linux
#include <GL/glew.h>
#include <GL/freeglut.h>
#endif
#include <cstdlib>
#include "camera.h"
#include "draw_utils.h"
#include "house.h"
#include "main.h"
#include "light.h"
#define ANG2RAD (3.14159265358979323846 / 180.0 * 0.5)
#define COLOR_BKG 1.0, 1.0, 1.0, 0.0
#define MNU_TOGGLE_CLIPPLANE 16
#define MNU_LIGHT_POS_2REL 15
#define MNU_LIGHT_POS_1REL 14
#define MNU_LIGHT_POS_2ABS 13
#define MNU_TOGGLE_LIGHT2 12
#define MNU_TOGGLE_LIGHT1 11
#define MNU_RESET 10
#define MNU_ORTHO 9
#define MNU_PERSPECTIVE 8
#define MNU_TOGGLE_WIND 7
#define MNU_CHANGE_COLOR 6
#define MNU_OPENCLOSE_DOOR 5
#define MNU_STOP_HOUSE_ROTATION 4
#define MNU_START_HOUSE_ROTATION 3
#define MNU_TOGGLE_WIREFRAME 2
#define MNU_TOGGLE_AXIS 1
#define PROJ_ORTHOGRAPHIC 'a'
#define PROJ_PERSPECTIVE 'p'
const int WINDOW_WIDTH = 800;
const int WINDOW_HEIGHT = 600;
const int ANIM_MSEC = 50;
const int WIND_MSEC = 5000;
const char ESCAPE = 27;
struct AppGlobals {
// global variables
GLfloat windAngle = 0.0;
int mainWindowID = 0;
// The light source can be a POSITIONAL (w > 0) or DIRECTIONAL (w = 0) light source depending on the w value.
Light light1{Vertex{-.4, 1.2, -.6, 1.0}, Vertex{.1, .1, 1}};
Light light2{Vertex{.2, .1, .5, 1.0}, Vertex{-.1, .1, -1}};
Camera camera;
//Clip Plane equation: Ax + By + Cz + D = 0
GLdouble clip_plane_0[4]={
-1.0,-0.3,0.0,0.5
};
Ortho ortho{-6.0, 6.0, -6.0, 6.0, -6.0, 50.0};
Perspective perspective{ 45.0, 1.0, 100.0};
bool enableClipPlane = true;
char projection_type = PROJ_PERSPECTIVE; //PROJ_ORTHOGRAPHIC
draw_utils utils;
House house{utils, light1, light2};
};
static AppGlobals* _app;
void displayCallback() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// view transformation must be called before model transformation
_app->camera.lookAt();
// model transformations
_app->utils.draw_wind(_app->windAngle);
_app->utils.draw_axes();
_app->house.draw();
glClipPlane (GL_CLIP_PLANE0, _app->clip_plane_0);
glutSwapBuffers();
}
void windCallback(int value) {
_app->windAngle = rand() % 360 + 1;
_app->house.updateWind(_app->windAngle);
glutTimerFunc(WIND_MSEC, windCallback, 0);
}
void animationCallback(int value) {
if(_app->house.rotationEnabled())
_app->house.updateRotation(true);
_app->house.rotateDoor();
_app->house.updateAnimation();
glutTimerFunc(ANIM_MSEC, animationCallback, 0);
}
void reshapeCallback(int w, int h) {
glViewport(0, 0, w, h);
reshape(w, h);
}
void reshape(int w, int h) {
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
GLdouble aspect = (GLdouble)w/(h==0 ? 1 : h);
if(_app->projection_type == PROJ_ORTHOGRAPHIC) {
GLdouble l{_app->ortho.left};
GLdouble r{_app->ortho.right};
GLdouble b{_app->ortho.bottom};
GLdouble t{_app->ortho.top};
// orthographic projection
if (w <= h) {
b /= aspect;
t /= aspect;
} else {
l *= aspect;
r *= aspect;
}
glOrtho(l, r, b, t, _app->ortho.zNear, _app->ortho.zFar);
} else {
// perspective projection using glFrustum
GLdouble fH = tan(_app->perspective.fovy * ANG2RAD) * _app->perspective.zNear;
GLdouble fW = fH * aspect;
glFrustum(-fW, fW, -fH, fH, _app->perspective.zNear, _app->perspective.zFar);
// perspective projection using gluPerspective
//gluPerspective(_app->perspective.fovy, aspect, _app->perspective.zNear, _app->perspective.zFar);
}
}
void menuCallback(int value) {
switch (value) {
case MNU_TOGGLE_CLIPPLANE:
toggleClipPlane();
break;
case MNU_LIGHT_POS_2REL:
_app->light2.setRelative(true);
_app->light1.setRelative(true);
break;
case MNU_LIGHT_POS_1REL:
_app->light2.setRelative(false);
_app->light1.setRelative(true);
break;
case MNU_LIGHT_POS_2ABS:
_app->light2.setRelative(false);
_app->light1.setRelative(false);
break;
case MNU_TOGGLE_LIGHT2:
_app->light2.toggle();
break;
case MNU_TOGGLE_LIGHT1:
_app->light1.toggle();
break;
case MNU_RESET:
reset();
break;
case MNU_ORTHO:
setOrthographicProjection();
break;
case MNU_PERSPECTIVE:
setProspectiveProjection();
break;
case MNU_TOGGLE_AXIS:
_app->utils.toggleAxesVisibility();
break;
case MNU_TOGGLE_WIREFRAME:
_app->utils.toggleWireframeVisibility();
break;
case MNU_TOGGLE_WIND:
_app->utils.toggleWindVisibility();
break;
case MNU_START_HOUSE_ROTATION:
_app->house.updateRotation(true);
break;
case MNU_STOP_HOUSE_ROTATION:
_app->house.updateRotation(false);
break;
case MNU_OPENCLOSE_DOOR:
_app->house.toggleDoor();
break;
case MNU_CHANGE_COLOR:
_app->house.changeColor();
break;
default:
_app->utils.log("unhandled MENU");
break;
}
}
void toggleClipPlane() {
_app->enableClipPlane = !_app->enableClipPlane;
if(_app->enableClipPlane) {
glEnable(GL_CLIP_PLANE0);
} else {
glDisable(GL_CLIP_PLANE0);
}
glutPostRedisplay();
}
/**
* reset model and camera to initial values
*/
void reset() {
_app->camera.reset();
_app->house.reset();
_app->utils.log("reset");
}
void setProspectiveProjection() {
_app->utils.log("Projection: Prospective");
forceReshape(PROJ_PERSPECTIVE);
}
void setOrthographicProjection() {
_app->utils.log("Projection: Orthographic");
forceReshape(PROJ_ORTHOGRAPHIC);
}
void forceReshape(char type) {
_app->projection_type = type;
GLint viewport[4]; //x,y,w,h
glGetIntegerv(GL_VIEWPORT, viewport);
reshape(viewport[2], viewport[3]);
}
void specialKeyCallback(int key, int x, int y) {
switch (key) {
case GLUT_KEY_F12:
reset();
break;
case GLUT_KEY_F9:
_app->perspective.fovy -= 1;
_app->utils.log("fovy=" + std::to_string(_app->perspective.fovy));
reshape(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
break;
case GLUT_KEY_F10:
_app->perspective.fovy += 1;
_app->utils.log("fovy=" + std::to_string(_app->perspective.fovy));
reshape(glutGet(GLUT_WINDOW_WIDTH), glutGet(GLUT_WINDOW_HEIGHT));
break;
case GLUT_KEY_PAGE_DOWN:
_app->camera.moveBackward();
if(!_app->house.inBoundaries())
_app->camera.moveForward();
updateCamera();
break;
case GLUT_KEY_PAGE_UP:
_app->camera.moveForward();
if(!_app->house.inBoundaries())
_app->camera.moveBackward();
updateCamera();
break;
case GLUT_KEY_UP:
_app->camera.moveTop();
if(!_app->house.inBoundaries())
_app->camera.moveBottom();
updateCamera();
break;
case GLUT_KEY_DOWN:
_app->camera.moveBottom();
if(!_app->house.inBoundaries())
_app->camera.moveTop();
updateCamera();
break;
case GLUT_KEY_RIGHT:
_app->camera.moveRight();
if(!_app->house.inBoundaries())
_app->camera.moveLeft();
updateCamera();
break;
case GLUT_KEY_LEFT:
_app->camera.moveLeft();
if(!_app->house.inBoundaries())
_app->camera.moveRight();
updateCamera();
break;
case GLUT_KEY_F1:
// translation: -X
_app->house.moveLeft();
break;
case GLUT_KEY_F2:
// translation: +X
_app->house.moveRight();
break;
case GLUT_KEY_F3:
// translation: +Y
_app->house.moveUp();
break;
case GLUT_KEY_F4:
// translation: -Y
_app->house.moveDown();
break;
case GLUT_KEY_F5:
// translation: -Z
_app->house.moveNear();
break;
case GLUT_KEY_F6:
// translation: +Z
_app->house.moveFar();
break;
default:
_app->utils.log("unhandled key");
break;
}
}
void updateCamera() {
_app->utils.log(_app->camera.toString());
glutPostRedisplay();
}
void keyCallback(unsigned char key, int x, int y) {
switch (key) {
case 'C':
case 'c':
_app->house.changeColor();
break;
case 'X':
case 'x':
_app->utils.toggleAxesVisibility();
break;
case 'W':
case 'w':
_app->utils.toggleWireframeVisibility();
break;
case 'A':
case 'a':
setOrthographicProjection();
break;
case 'P':
case 'p':
setProspectiveProjection();
break;
case 'R':
case 'r':
_app->house.updateRotation(true);
break;
case 'S':
case 's':
_app->house.updateRotation(false);
break;
case 'D':
case 'd':
_app->house.toggleDoor();
break;
case ESCAPE:
glutDestroyWindow(_app->mainWindowID);
exit(0);
default:
_app->utils.log("unhandled key");
break;
}
}
void appInit() {
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT);
_app->mainWindowID = glutCreateWindow("house");
glClearColor(COLOR_BKG);
glEnable(GL_CLIP_PLANE0);
initLight();
createMenu();
glutReshapeFunc(reshapeCallback);
glutDisplayFunc(displayCallback);
glutSpecialFunc(specialKeyCallback);
glutKeyboardFunc(keyCallback);
glutTimerFunc(ANIM_MSEC, animationCallback, 0);
glutTimerFunc(WIND_MSEC, windCallback, 0);
}
void initLight() {
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_LIGHTING);
// glEnable(GL_COLOR_MATERIAL);
Light::globalAmbient();
}
void createMenu() {
int menuLight = glutCreateMenu(menuCallback);
glutAddMenuEntry("On/Off Light 1", MNU_TOGGLE_LIGHT1);
glutAddMenuEntry("On/Off Light 2", MNU_TOGGLE_LIGHT2);
glutAddMenuEntry("Light 1/2 in relative position", MNU_LIGHT_POS_2REL);
glutAddMenuEntry("Light 1 in relative position", MNU_LIGHT_POS_1REL);
glutAddMenuEntry("Light 1/2 in absolute position", MNU_LIGHT_POS_2ABS);
int menuProjection = glutCreateMenu(menuCallback);
glutAddMenuEntry("Perspective", MNU_PERSPECTIVE);
glutAddMenuEntry("Ortho", MNU_ORTHO);
glutAddMenuEntry("Toggle Clip Plane", MNU_TOGGLE_CLIPPLANE);
glutCreateMenu(menuCallback);
int menuStructure = glutCreateMenu(menuCallback);
glutAddMenuEntry("Show/Hide Wind", MNU_TOGGLE_WIND);
glutAddMenuEntry("Show/Hide Axes", MNU_TOGGLE_AXIS);
glutAddMenuEntry("Show/Hide Wireframe", MNU_TOGGLE_WIREFRAME);
glutAddMenuEntry("Change color", MNU_CHANGE_COLOR);
glutAddMenuEntry("Reset", MNU_RESET);
glutCreateMenu(menuCallback);
int menuAnimation = glutCreateMenu(menuCallback);
glutAddMenuEntry("Start House Rotation", MNU_START_HOUSE_ROTATION);
glutAddMenuEntry("Stop House Rotation", MNU_STOP_HOUSE_ROTATION);
glutAddMenuEntry("Open/Close Door", MNU_OPENCLOSE_DOOR);
glutCreateMenu(menuCallback);
glutAddSubMenu("Light", menuLight);
glutAddSubMenu("Structure", menuStructure);
glutAddSubMenu("Animation", menuAnimation);
glutAddSubMenu("Projection", menuProjection);
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutAttachMenu(GLUT_RIGHT_BUTTON);
}
int main(int argc, char* argv[]) {
AppGlobals app;
_app = &app;
glutInit(&argc, argv);
appInit();
glutMainLoop();
}
| 27.554585 | 113 | 0.605705 | [
"model"
] |
a1c8d18a37537784d8d50cd3d4b8944e9bdaee64 | 3,940 | cpp | C++ | Source/Tools/RampGenerator/RampGenerator.cpp | GKR/Urho3D | 70db25ac459dd40f76580c8f6ee9320192a425ac | [
"Apache-2.0"
] | null | null | null | Source/Tools/RampGenerator/RampGenerator.cpp | GKR/Urho3D | 70db25ac459dd40f76580c8f6ee9320192a425ac | [
"Apache-2.0"
] | null | null | null | Source/Tools/RampGenerator/RampGenerator.cpp | GKR/Urho3D | 70db25ac459dd40f76580c8f6ee9320192a425ac | [
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2008-2016 the Urho3D project.
//
// 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 <Urho3D/Container/ArrayPtr.h>
#include <Urho3D/Core/ProcessUtils.h>
#include <Urho3D/Core/StringUtils.h>
#ifdef WIN32
#include <windows.h>
#endif
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <STB/stb_image.h>
#include <STB/stb_image_write.h>
#include <Urho3D/DebugNew.h>
using namespace Urho3D;
int main(int argc, char** argv);
void Run(const Vector<String>& arguments);
int main(int argc, char** argv)
{
Vector<String> arguments;
#ifdef WIN32
arguments = ParseArguments(GetCommandLineW());
#else
arguments = ParseArguments(argc, argv);
#endif
Run(arguments);
return 0;
}
void Run(const Vector<String>& arguments)
{
if (arguments.Size() < 3)
ErrorExit("Usage: RampGenerator <output png file> <width> <power> [dimensions]\n");
int width = ToInt(arguments[1]);
float power = ToFloat(arguments[2]);
int dimensions = 1;
if (arguments.Size() > 3)
dimensions = ToInt(arguments[3]);
if (width < 2)
ErrorExit("Width must be at least 2");
if (dimensions < 1 || dimensions > 2)
ErrorExit("Dimensions must be 1 or 2");
if (dimensions == 1)
{
SharedArrayPtr<unsigned char> data(new unsigned char[width]);
for (int i = 0; i < width; ++i)
{
float x = ((float)i) / ((float)(width - 1));
data[i] = (unsigned char)((1.0f - pow(x, power)) * 255.0f);
}
// Ensure start is full bright & end is completely black
data[0] = 255;
data[width - 1] = 0;
stbi_write_png(arguments[0].CString(), width, 1, 1, data.Get(), 0);
}
if (dimensions == 2)
{
SharedArrayPtr<unsigned char> data(new unsigned char[width * width]);
for (int y = 0; y < width; ++y)
{
for (int x = 0; x < width; ++x)
{
unsigned i = y * width + x;
float halfWidth = width * 0.5f;
float xf = (x - halfWidth + 0.5f) / (halfWidth - 0.5f);
float yf = (y - halfWidth + 0.5f) / (halfWidth - 0.5f);
float dist = sqrtf(xf * xf + yf * yf);
if (dist > 1.0f)
dist = 1.0f;
data[i] = (unsigned char)((1.0f - pow(dist, power)) * 255.0f);
}
}
// Ensure the border is completely black
for (int x = 0; x < width; ++x)
{
data[x] = 0;
data[(width - 1) * width + x] = 0;
data[x * width] = 0;
data[x * width + (width - 1)] = 0;
}
stbi_write_png(arguments[0].CString(), width, width, 1, data.Get(), 0);
}
}
| 31.023622 | 92 | 0.586041 | [
"vector"
] |
a1c938936bb2adb046643fdbbc86d328d2aeef4b | 137,363 | cpp | C++ | ios/Classes/Native/Bulk_UnityEngine.ParticleSystemModule_0.cpp | ShearerAWS/mini-mafia-release | 1a97656538fe24c015efbfc7954a66065139c34a | [
"MIT"
] | null | null | null | ios/Classes/Native/Bulk_UnityEngine.ParticleSystemModule_0.cpp | ShearerAWS/mini-mafia-release | 1a97656538fe24c015efbfc7954a66065139c34a | [
"MIT"
] | null | null | null | ios/Classes/Native/Bulk_UnityEngine.ParticleSystemModule_0.cpp | ShearerAWS/mini-mafia-release | 1a97656538fe24c015efbfc7954a66065139c34a | [
"MIT"
] | null | null | null | #include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <cstring>
#include <string.h>
#include <stdio.h>
#include <cmath>
#include <limits>
#include <assert.h>
#include <stdint.h>
#include "il2cpp-class-internals.h"
#include "codegen/il2cpp-codegen.h"
#include "il2cpp-object-internals.h"
// System.Char[]
struct CharU5BU5D_t3528271667;
// System.String
struct String_t;
// System.Void
struct Void_t1185182177;
// UnityEngine.AnimationCurve
struct AnimationCurve_t3046754366;
// UnityEngine.ParticleSystem
struct ParticleSystem_t1800779281;
// UnityEngine.ParticleSystem/Particle[]
struct ParticleU5BU5D_t3069227754;
// UnityEngine.ParticleSystemRenderer
struct ParticleSystemRenderer_t2065813411;
extern RuntimeClass* AnimationCurve_t3046754366_il2cpp_TypeInfo_var;
extern RuntimeClass* Vector3_t3722313464_il2cpp_TypeInfo_var;
extern const uint32_t MinMaxCurve_t1067599125_pinvoke_FromNativeMethodDefinition_MetadataUsageId;
extern const uint32_t ParticleSystem_Emit_m497964751_MetadataUsageId;
extern const uint32_t Particle_set_angularVelocity3D_m3163963446_MetadataUsageId;
extern const uint32_t Particle_set_rotation3D_m2156157200_MetadataUsageId;
struct AnimationCurve_t3046754366;;
struct AnimationCurve_t3046754366_marshaled_com;
struct AnimationCurve_t3046754366_marshaled_com;;
struct AnimationCurve_t3046754366_marshaled_pinvoke;
struct AnimationCurve_t3046754366_marshaled_pinvoke;;
struct ParticleU5BU5D_t3069227754;
#ifndef U3CMODULEU3E_T692745538_H
#define U3CMODULEU3E_T692745538_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <Module>
struct U3CModuleU3E_t692745538
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // U3CMODULEU3E_T692745538_H
#ifndef RUNTIMEOBJECT_H
#define RUNTIMEOBJECT_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Object
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEOBJECT_H
struct Il2CppArrayBounds;
#ifndef RUNTIMEARRAY_H
#define RUNTIMEARRAY_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Array
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RUNTIMEARRAY_H
#ifndef VALUETYPE_T3640485471_H
#define VALUETYPE_T3640485471_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.ValueType
struct ValueType_t3640485471 : public RuntimeObject
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_t3640485471_marshaled_com
{
};
#endif // VALUETYPE_T3640485471_H
#ifndef BOOLEAN_T97287965_H
#define BOOLEAN_T97287965_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Boolean
struct Boolean_t97287965
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Boolean_t97287965, ___m_value_2)); }
inline bool get_m_value_2() const { return ___m_value_2; }
inline bool* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(bool value)
{
___m_value_2 = value;
}
};
struct Boolean_t97287965_StaticFields
{
public:
// System.String System.Boolean::FalseString
String_t* ___FalseString_0;
// System.String System.Boolean::TrueString
String_t* ___TrueString_1;
public:
inline static int32_t get_offset_of_FalseString_0() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___FalseString_0)); }
inline String_t* get_FalseString_0() const { return ___FalseString_0; }
inline String_t** get_address_of_FalseString_0() { return &___FalseString_0; }
inline void set_FalseString_0(String_t* value)
{
___FalseString_0 = value;
Il2CppCodeGenWriteBarrier((&___FalseString_0), value);
}
inline static int32_t get_offset_of_TrueString_1() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___TrueString_1)); }
inline String_t* get_TrueString_1() const { return ___TrueString_1; }
inline String_t** get_address_of_TrueString_1() { return &___TrueString_1; }
inline void set_TrueString_1(String_t* value)
{
___TrueString_1 = value;
Il2CppCodeGenWriteBarrier((&___TrueString_1), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // BOOLEAN_T97287965_H
#ifndef ENUM_T4135868527_H
#define ENUM_T4135868527_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Enum
struct Enum_t4135868527 : public ValueType_t3640485471
{
public:
public:
};
struct Enum_t4135868527_StaticFields
{
public:
// System.Char[] System.Enum::split_char
CharU5BU5D_t3528271667* ___split_char_0;
public:
inline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___split_char_0)); }
inline CharU5BU5D_t3528271667* get_split_char_0() const { return ___split_char_0; }
inline CharU5BU5D_t3528271667** get_address_of_split_char_0() { return &___split_char_0; }
inline void set_split_char_0(CharU5BU5D_t3528271667* value)
{
___split_char_0 = value;
Il2CppCodeGenWriteBarrier((&___split_char_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t4135868527_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t4135868527_marshaled_com
{
};
#endif // ENUM_T4135868527_H
#ifndef INT32_T2950945753_H
#define INT32_T2950945753_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int32
struct Int32_t2950945753
{
public:
// System.Int32 System.Int32::m_value
int32_t ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Int32_t2950945753, ___m_value_2)); }
inline int32_t get_m_value_2() const { return ___m_value_2; }
inline int32_t* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(int32_t value)
{
___m_value_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INT32_T2950945753_H
#ifndef INTPTR_T_H
#define INTPTR_T_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.IntPtr
struct IntPtr_t
{
public:
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }
inline void* get_m_value_0() const { return ___m_value_0; }
inline void** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(void* value)
{
___m_value_0 = value;
}
};
struct IntPtr_t_StaticFields
{
public:
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
public:
inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }
inline intptr_t get_Zero_1() const { return ___Zero_1; }
inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }
inline void set_Zero_1(intptr_t value)
{
___Zero_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // INTPTR_T_H
#ifndef SINGLE_T1397266774_H
#define SINGLE_T1397266774_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Single
struct Single_t1397266774
{
public:
// System.Single System.Single::m_value
float ___m_value_7;
public:
inline static int32_t get_offset_of_m_value_7() { return static_cast<int32_t>(offsetof(Single_t1397266774, ___m_value_7)); }
inline float get_m_value_7() const { return ___m_value_7; }
inline float* get_address_of_m_value_7() { return &___m_value_7; }
inline void set_m_value_7(float value)
{
___m_value_7 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // SINGLE_T1397266774_H
#ifndef UINT32_T2560061978_H
#define UINT32_T2560061978_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.UInt32
struct UInt32_t2560061978
{
public:
// System.UInt32 System.UInt32::m_value
uint32_t ___m_value_2;
public:
inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(UInt32_t2560061978, ___m_value_2)); }
inline uint32_t get_m_value_2() const { return ___m_value_2; }
inline uint32_t* get_address_of_m_value_2() { return &___m_value_2; }
inline void set_m_value_2(uint32_t value)
{
___m_value_2 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // UINT32_T2560061978_H
#ifndef VOID_T1185182177_H
#define VOID_T1185182177_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void
struct Void_t1185182177
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VOID_T1185182177_H
#ifndef COLOR32_T2600501292_H
#define COLOR32_T2600501292_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Color32
struct Color32_t2600501292
{
public:
union
{
#pragma pack(push, tp, 1)
struct
{
// System.Int32 UnityEngine.Color32::rgba
int32_t ___rgba_0;
};
#pragma pack(pop, tp)
struct
{
int32_t ___rgba_0_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
// System.Byte UnityEngine.Color32::r
uint8_t ___r_1;
};
#pragma pack(pop, tp)
struct
{
uint8_t ___r_1_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___g_2_OffsetPadding[1];
// System.Byte UnityEngine.Color32::g
uint8_t ___g_2;
};
#pragma pack(pop, tp)
struct
{
char ___g_2_OffsetPadding_forAlignmentOnly[1];
uint8_t ___g_2_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___b_3_OffsetPadding[2];
// System.Byte UnityEngine.Color32::b
uint8_t ___b_3;
};
#pragma pack(pop, tp)
struct
{
char ___b_3_OffsetPadding_forAlignmentOnly[2];
uint8_t ___b_3_forAlignmentOnly;
};
#pragma pack(push, tp, 1)
struct
{
char ___a_4_OffsetPadding[3];
// System.Byte UnityEngine.Color32::a
uint8_t ___a_4;
};
#pragma pack(pop, tp)
struct
{
char ___a_4_OffsetPadding_forAlignmentOnly[3];
uint8_t ___a_4_forAlignmentOnly;
};
};
public:
inline static int32_t get_offset_of_rgba_0() { return static_cast<int32_t>(offsetof(Color32_t2600501292, ___rgba_0)); }
inline int32_t get_rgba_0() const { return ___rgba_0; }
inline int32_t* get_address_of_rgba_0() { return &___rgba_0; }
inline void set_rgba_0(int32_t value)
{
___rgba_0 = value;
}
inline static int32_t get_offset_of_r_1() { return static_cast<int32_t>(offsetof(Color32_t2600501292, ___r_1)); }
inline uint8_t get_r_1() const { return ___r_1; }
inline uint8_t* get_address_of_r_1() { return &___r_1; }
inline void set_r_1(uint8_t value)
{
___r_1 = value;
}
inline static int32_t get_offset_of_g_2() { return static_cast<int32_t>(offsetof(Color32_t2600501292, ___g_2)); }
inline uint8_t get_g_2() const { return ___g_2; }
inline uint8_t* get_address_of_g_2() { return &___g_2; }
inline void set_g_2(uint8_t value)
{
___g_2 = value;
}
inline static int32_t get_offset_of_b_3() { return static_cast<int32_t>(offsetof(Color32_t2600501292, ___b_3)); }
inline uint8_t get_b_3() const { return ___b_3; }
inline uint8_t* get_address_of_b_3() { return &___b_3; }
inline void set_b_3(uint8_t value)
{
___b_3 = value;
}
inline static int32_t get_offset_of_a_4() { return static_cast<int32_t>(offsetof(Color32_t2600501292, ___a_4)); }
inline uint8_t get_a_4() const { return ___a_4; }
inline uint8_t* get_address_of_a_4() { return &___a_4; }
inline void set_a_4(uint8_t value)
{
___a_4 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // COLOR32_T2600501292_H
#ifndef MAINMODULE_T2320046318_H
#define MAINMODULE_T2320046318_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystem/MainModule
struct MainModule_t2320046318
{
public:
// UnityEngine.ParticleSystem UnityEngine.ParticleSystem/MainModule::m_ParticleSystem
ParticleSystem_t1800779281 * ___m_ParticleSystem_0;
public:
inline static int32_t get_offset_of_m_ParticleSystem_0() { return static_cast<int32_t>(offsetof(MainModule_t2320046318, ___m_ParticleSystem_0)); }
inline ParticleSystem_t1800779281 * get_m_ParticleSystem_0() const { return ___m_ParticleSystem_0; }
inline ParticleSystem_t1800779281 ** get_address_of_m_ParticleSystem_0() { return &___m_ParticleSystem_0; }
inline void set_m_ParticleSystem_0(ParticleSystem_t1800779281 * value)
{
___m_ParticleSystem_0 = value;
Il2CppCodeGenWriteBarrier((&___m_ParticleSystem_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.ParticleSystem/MainModule
struct MainModule_t2320046318_marshaled_pinvoke
{
ParticleSystem_t1800779281 * ___m_ParticleSystem_0;
};
// Native definition for COM marshalling of UnityEngine.ParticleSystem/MainModule
struct MainModule_t2320046318_marshaled_com
{
ParticleSystem_t1800779281 * ___m_ParticleSystem_0;
};
#endif // MAINMODULE_T2320046318_H
#ifndef TEXTURESHEETANIMATIONMODULE_T738696839_H
#define TEXTURESHEETANIMATIONMODULE_T738696839_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystem/TextureSheetAnimationModule
struct TextureSheetAnimationModule_t738696839
{
public:
// UnityEngine.ParticleSystem UnityEngine.ParticleSystem/TextureSheetAnimationModule::m_ParticleSystem
ParticleSystem_t1800779281 * ___m_ParticleSystem_0;
public:
inline static int32_t get_offset_of_m_ParticleSystem_0() { return static_cast<int32_t>(offsetof(TextureSheetAnimationModule_t738696839, ___m_ParticleSystem_0)); }
inline ParticleSystem_t1800779281 * get_m_ParticleSystem_0() const { return ___m_ParticleSystem_0; }
inline ParticleSystem_t1800779281 ** get_address_of_m_ParticleSystem_0() { return &___m_ParticleSystem_0; }
inline void set_m_ParticleSystem_0(ParticleSystem_t1800779281 * value)
{
___m_ParticleSystem_0 = value;
Il2CppCodeGenWriteBarrier((&___m_ParticleSystem_0), value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.ParticleSystem/TextureSheetAnimationModule
struct TextureSheetAnimationModule_t738696839_marshaled_pinvoke
{
ParticleSystem_t1800779281 * ___m_ParticleSystem_0;
};
// Native definition for COM marshalling of UnityEngine.ParticleSystem/TextureSheetAnimationModule
struct TextureSheetAnimationModule_t738696839_marshaled_com
{
ParticleSystem_t1800779281 * ___m_ParticleSystem_0;
};
#endif // TEXTURESHEETANIMATIONMODULE_T738696839_H
#ifndef VECTOR3_T3722313464_H
#define VECTOR3_T3722313464_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Vector3
struct Vector3_t3722313464
{
public:
// System.Single UnityEngine.Vector3::x
float ___x_2;
// System.Single UnityEngine.Vector3::y
float ___y_3;
// System.Single UnityEngine.Vector3::z
float ___z_4;
public:
inline static int32_t get_offset_of_x_2() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___x_2)); }
inline float get_x_2() const { return ___x_2; }
inline float* get_address_of_x_2() { return &___x_2; }
inline void set_x_2(float value)
{
___x_2 = value;
}
inline static int32_t get_offset_of_y_3() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___y_3)); }
inline float get_y_3() const { return ___y_3; }
inline float* get_address_of_y_3() { return &___y_3; }
inline void set_y_3(float value)
{
___y_3 = value;
}
inline static int32_t get_offset_of_z_4() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___z_4)); }
inline float get_z_4() const { return ___z_4; }
inline float* get_address_of_z_4() { return &___z_4; }
inline void set_z_4(float value)
{
___z_4 = value;
}
};
struct Vector3_t3722313464_StaticFields
{
public:
// UnityEngine.Vector3 UnityEngine.Vector3::zeroVector
Vector3_t3722313464 ___zeroVector_5;
// UnityEngine.Vector3 UnityEngine.Vector3::oneVector
Vector3_t3722313464 ___oneVector_6;
// UnityEngine.Vector3 UnityEngine.Vector3::upVector
Vector3_t3722313464 ___upVector_7;
// UnityEngine.Vector3 UnityEngine.Vector3::downVector
Vector3_t3722313464 ___downVector_8;
// UnityEngine.Vector3 UnityEngine.Vector3::leftVector
Vector3_t3722313464 ___leftVector_9;
// UnityEngine.Vector3 UnityEngine.Vector3::rightVector
Vector3_t3722313464 ___rightVector_10;
// UnityEngine.Vector3 UnityEngine.Vector3::forwardVector
Vector3_t3722313464 ___forwardVector_11;
// UnityEngine.Vector3 UnityEngine.Vector3::backVector
Vector3_t3722313464 ___backVector_12;
// UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector
Vector3_t3722313464 ___positiveInfinityVector_13;
// UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector
Vector3_t3722313464 ___negativeInfinityVector_14;
public:
inline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___zeroVector_5)); }
inline Vector3_t3722313464 get_zeroVector_5() const { return ___zeroVector_5; }
inline Vector3_t3722313464 * get_address_of_zeroVector_5() { return &___zeroVector_5; }
inline void set_zeroVector_5(Vector3_t3722313464 value)
{
___zeroVector_5 = value;
}
inline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___oneVector_6)); }
inline Vector3_t3722313464 get_oneVector_6() const { return ___oneVector_6; }
inline Vector3_t3722313464 * get_address_of_oneVector_6() { return &___oneVector_6; }
inline void set_oneVector_6(Vector3_t3722313464 value)
{
___oneVector_6 = value;
}
inline static int32_t get_offset_of_upVector_7() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___upVector_7)); }
inline Vector3_t3722313464 get_upVector_7() const { return ___upVector_7; }
inline Vector3_t3722313464 * get_address_of_upVector_7() { return &___upVector_7; }
inline void set_upVector_7(Vector3_t3722313464 value)
{
___upVector_7 = value;
}
inline static int32_t get_offset_of_downVector_8() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___downVector_8)); }
inline Vector3_t3722313464 get_downVector_8() const { return ___downVector_8; }
inline Vector3_t3722313464 * get_address_of_downVector_8() { return &___downVector_8; }
inline void set_downVector_8(Vector3_t3722313464 value)
{
___downVector_8 = value;
}
inline static int32_t get_offset_of_leftVector_9() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___leftVector_9)); }
inline Vector3_t3722313464 get_leftVector_9() const { return ___leftVector_9; }
inline Vector3_t3722313464 * get_address_of_leftVector_9() { return &___leftVector_9; }
inline void set_leftVector_9(Vector3_t3722313464 value)
{
___leftVector_9 = value;
}
inline static int32_t get_offset_of_rightVector_10() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___rightVector_10)); }
inline Vector3_t3722313464 get_rightVector_10() const { return ___rightVector_10; }
inline Vector3_t3722313464 * get_address_of_rightVector_10() { return &___rightVector_10; }
inline void set_rightVector_10(Vector3_t3722313464 value)
{
___rightVector_10 = value;
}
inline static int32_t get_offset_of_forwardVector_11() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___forwardVector_11)); }
inline Vector3_t3722313464 get_forwardVector_11() const { return ___forwardVector_11; }
inline Vector3_t3722313464 * get_address_of_forwardVector_11() { return &___forwardVector_11; }
inline void set_forwardVector_11(Vector3_t3722313464 value)
{
___forwardVector_11 = value;
}
inline static int32_t get_offset_of_backVector_12() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___backVector_12)); }
inline Vector3_t3722313464 get_backVector_12() const { return ___backVector_12; }
inline Vector3_t3722313464 * get_address_of_backVector_12() { return &___backVector_12; }
inline void set_backVector_12(Vector3_t3722313464 value)
{
___backVector_12 = value;
}
inline static int32_t get_offset_of_positiveInfinityVector_13() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___positiveInfinityVector_13)); }
inline Vector3_t3722313464 get_positiveInfinityVector_13() const { return ___positiveInfinityVector_13; }
inline Vector3_t3722313464 * get_address_of_positiveInfinityVector_13() { return &___positiveInfinityVector_13; }
inline void set_positiveInfinityVector_13(Vector3_t3722313464 value)
{
___positiveInfinityVector_13 = value;
}
inline static int32_t get_offset_of_negativeInfinityVector_14() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___negativeInfinityVector_14)); }
inline Vector3_t3722313464 get_negativeInfinityVector_14() const { return ___negativeInfinityVector_14; }
inline Vector3_t3722313464 * get_address_of_negativeInfinityVector_14() { return &___negativeInfinityVector_14; }
inline void set_negativeInfinityVector_14(Vector3_t3722313464 value)
{
___negativeInfinityVector_14 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // VECTOR3_T3722313464_H
#ifndef ANIMATIONCURVE_T3046754366_H
#define ANIMATIONCURVE_T3046754366_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.AnimationCurve
struct AnimationCurve_t3046754366 : public RuntimeObject
{
public:
// System.IntPtr UnityEngine.AnimationCurve::m_Ptr
intptr_t ___m_Ptr_0;
public:
inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(AnimationCurve_t3046754366, ___m_Ptr_0)); }
inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; }
inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; }
inline void set_m_Ptr_0(intptr_t value)
{
___m_Ptr_0 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.AnimationCurve
struct AnimationCurve_t3046754366_marshaled_pinvoke
{
intptr_t ___m_Ptr_0;
};
// Native definition for COM marshalling of UnityEngine.AnimationCurve
struct AnimationCurve_t3046754366_marshaled_com
{
intptr_t ___m_Ptr_0;
};
#endif // ANIMATIONCURVE_T3046754366_H
#ifndef OBJECT_T631007953_H
#define OBJECT_T631007953_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Object
struct Object_t631007953 : public RuntimeObject
{
public:
// System.IntPtr UnityEngine.Object::m_CachedPtr
intptr_t ___m_CachedPtr_0;
public:
inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_t631007953, ___m_CachedPtr_0)); }
inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; }
inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; }
inline void set_m_CachedPtr_0(intptr_t value)
{
___m_CachedPtr_0 = value;
}
};
struct Object_t631007953_StaticFields
{
public:
// System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject
int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1;
public:
inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_t631007953_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); }
inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; }
inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; }
inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value)
{
___OffsetOfInstanceIDInCPlusPlusObject_1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.Object
struct Object_t631007953_marshaled_pinvoke
{
intptr_t ___m_CachedPtr_0;
};
// Native definition for COM marshalling of UnityEngine.Object
struct Object_t631007953_marshaled_com
{
intptr_t ___m_CachedPtr_0;
};
#endif // OBJECT_T631007953_H
#ifndef PARTICLE_T1882894987_H
#define PARTICLE_T1882894987_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystem/Particle
struct Particle_t1882894987
{
public:
// UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_Position
Vector3_t3722313464 ___m_Position_0;
// UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_Velocity
Vector3_t3722313464 ___m_Velocity_1;
// UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_AnimatedVelocity
Vector3_t3722313464 ___m_AnimatedVelocity_2;
// UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_InitialVelocity
Vector3_t3722313464 ___m_InitialVelocity_3;
// UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_AxisOfRotation
Vector3_t3722313464 ___m_AxisOfRotation_4;
// UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_Rotation
Vector3_t3722313464 ___m_Rotation_5;
// UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_AngularVelocity
Vector3_t3722313464 ___m_AngularVelocity_6;
// UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::m_StartSize
Vector3_t3722313464 ___m_StartSize_7;
// UnityEngine.Color32 UnityEngine.ParticleSystem/Particle::m_StartColor
Color32_t2600501292 ___m_StartColor_8;
// System.UInt32 UnityEngine.ParticleSystem/Particle::m_RandomSeed
uint32_t ___m_RandomSeed_9;
// System.Single UnityEngine.ParticleSystem/Particle::m_Lifetime
float ___m_Lifetime_10;
// System.Single UnityEngine.ParticleSystem/Particle::m_StartLifetime
float ___m_StartLifetime_11;
// System.Single UnityEngine.ParticleSystem/Particle::m_EmitAccumulator0
float ___m_EmitAccumulator0_12;
// System.Single UnityEngine.ParticleSystem/Particle::m_EmitAccumulator1
float ___m_EmitAccumulator1_13;
public:
inline static int32_t get_offset_of_m_Position_0() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_Position_0)); }
inline Vector3_t3722313464 get_m_Position_0() const { return ___m_Position_0; }
inline Vector3_t3722313464 * get_address_of_m_Position_0() { return &___m_Position_0; }
inline void set_m_Position_0(Vector3_t3722313464 value)
{
___m_Position_0 = value;
}
inline static int32_t get_offset_of_m_Velocity_1() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_Velocity_1)); }
inline Vector3_t3722313464 get_m_Velocity_1() const { return ___m_Velocity_1; }
inline Vector3_t3722313464 * get_address_of_m_Velocity_1() { return &___m_Velocity_1; }
inline void set_m_Velocity_1(Vector3_t3722313464 value)
{
___m_Velocity_1 = value;
}
inline static int32_t get_offset_of_m_AnimatedVelocity_2() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_AnimatedVelocity_2)); }
inline Vector3_t3722313464 get_m_AnimatedVelocity_2() const { return ___m_AnimatedVelocity_2; }
inline Vector3_t3722313464 * get_address_of_m_AnimatedVelocity_2() { return &___m_AnimatedVelocity_2; }
inline void set_m_AnimatedVelocity_2(Vector3_t3722313464 value)
{
___m_AnimatedVelocity_2 = value;
}
inline static int32_t get_offset_of_m_InitialVelocity_3() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_InitialVelocity_3)); }
inline Vector3_t3722313464 get_m_InitialVelocity_3() const { return ___m_InitialVelocity_3; }
inline Vector3_t3722313464 * get_address_of_m_InitialVelocity_3() { return &___m_InitialVelocity_3; }
inline void set_m_InitialVelocity_3(Vector3_t3722313464 value)
{
___m_InitialVelocity_3 = value;
}
inline static int32_t get_offset_of_m_AxisOfRotation_4() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_AxisOfRotation_4)); }
inline Vector3_t3722313464 get_m_AxisOfRotation_4() const { return ___m_AxisOfRotation_4; }
inline Vector3_t3722313464 * get_address_of_m_AxisOfRotation_4() { return &___m_AxisOfRotation_4; }
inline void set_m_AxisOfRotation_4(Vector3_t3722313464 value)
{
___m_AxisOfRotation_4 = value;
}
inline static int32_t get_offset_of_m_Rotation_5() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_Rotation_5)); }
inline Vector3_t3722313464 get_m_Rotation_5() const { return ___m_Rotation_5; }
inline Vector3_t3722313464 * get_address_of_m_Rotation_5() { return &___m_Rotation_5; }
inline void set_m_Rotation_5(Vector3_t3722313464 value)
{
___m_Rotation_5 = value;
}
inline static int32_t get_offset_of_m_AngularVelocity_6() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_AngularVelocity_6)); }
inline Vector3_t3722313464 get_m_AngularVelocity_6() const { return ___m_AngularVelocity_6; }
inline Vector3_t3722313464 * get_address_of_m_AngularVelocity_6() { return &___m_AngularVelocity_6; }
inline void set_m_AngularVelocity_6(Vector3_t3722313464 value)
{
___m_AngularVelocity_6 = value;
}
inline static int32_t get_offset_of_m_StartSize_7() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_StartSize_7)); }
inline Vector3_t3722313464 get_m_StartSize_7() const { return ___m_StartSize_7; }
inline Vector3_t3722313464 * get_address_of_m_StartSize_7() { return &___m_StartSize_7; }
inline void set_m_StartSize_7(Vector3_t3722313464 value)
{
___m_StartSize_7 = value;
}
inline static int32_t get_offset_of_m_StartColor_8() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_StartColor_8)); }
inline Color32_t2600501292 get_m_StartColor_8() const { return ___m_StartColor_8; }
inline Color32_t2600501292 * get_address_of_m_StartColor_8() { return &___m_StartColor_8; }
inline void set_m_StartColor_8(Color32_t2600501292 value)
{
___m_StartColor_8 = value;
}
inline static int32_t get_offset_of_m_RandomSeed_9() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_RandomSeed_9)); }
inline uint32_t get_m_RandomSeed_9() const { return ___m_RandomSeed_9; }
inline uint32_t* get_address_of_m_RandomSeed_9() { return &___m_RandomSeed_9; }
inline void set_m_RandomSeed_9(uint32_t value)
{
___m_RandomSeed_9 = value;
}
inline static int32_t get_offset_of_m_Lifetime_10() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_Lifetime_10)); }
inline float get_m_Lifetime_10() const { return ___m_Lifetime_10; }
inline float* get_address_of_m_Lifetime_10() { return &___m_Lifetime_10; }
inline void set_m_Lifetime_10(float value)
{
___m_Lifetime_10 = value;
}
inline static int32_t get_offset_of_m_StartLifetime_11() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_StartLifetime_11)); }
inline float get_m_StartLifetime_11() const { return ___m_StartLifetime_11; }
inline float* get_address_of_m_StartLifetime_11() { return &___m_StartLifetime_11; }
inline void set_m_StartLifetime_11(float value)
{
___m_StartLifetime_11 = value;
}
inline static int32_t get_offset_of_m_EmitAccumulator0_12() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_EmitAccumulator0_12)); }
inline float get_m_EmitAccumulator0_12() const { return ___m_EmitAccumulator0_12; }
inline float* get_address_of_m_EmitAccumulator0_12() { return &___m_EmitAccumulator0_12; }
inline void set_m_EmitAccumulator0_12(float value)
{
___m_EmitAccumulator0_12 = value;
}
inline static int32_t get_offset_of_m_EmitAccumulator1_13() { return static_cast<int32_t>(offsetof(Particle_t1882894987, ___m_EmitAccumulator1_13)); }
inline float get_m_EmitAccumulator1_13() const { return ___m_EmitAccumulator1_13; }
inline float* get_address_of_m_EmitAccumulator1_13() { return &___m_EmitAccumulator1_13; }
inline void set_m_EmitAccumulator1_13(float value)
{
___m_EmitAccumulator1_13 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PARTICLE_T1882894987_H
#ifndef PARTICLESYSTEMANIMATIONTYPE_T3289377710_H
#define PARTICLESYSTEMANIMATIONTYPE_T3289377710_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystemAnimationType
struct ParticleSystemAnimationType_t3289377710
{
public:
// System.Int32 UnityEngine.ParticleSystemAnimationType::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ParticleSystemAnimationType_t3289377710, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PARTICLESYSTEMANIMATIONTYPE_T3289377710_H
#ifndef PARTICLESYSTEMCURVEMODE_T3859704052_H
#define PARTICLESYSTEMCURVEMODE_T3859704052_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystemCurveMode
struct ParticleSystemCurveMode_t3859704052
{
public:
// System.Int32 UnityEngine.ParticleSystemCurveMode::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ParticleSystemCurveMode_t3859704052, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PARTICLESYSTEMCURVEMODE_T3859704052_H
#ifndef PARTICLESYSTEMSCALINGMODE_T2278533876_H
#define PARTICLESYSTEMSCALINGMODE_T2278533876_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystemScalingMode
struct ParticleSystemScalingMode_t2278533876
{
public:
// System.Int32 UnityEngine.ParticleSystemScalingMode::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ParticleSystemScalingMode_t2278533876, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PARTICLESYSTEMSCALINGMODE_T2278533876_H
#ifndef PARTICLESYSTEMSIMULATIONSPACE_T2969500608_H
#define PARTICLESYSTEMSIMULATIONSPACE_T2969500608_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystemSimulationSpace
struct ParticleSystemSimulationSpace_t2969500608
{
public:
// System.Int32 UnityEngine.ParticleSystemSimulationSpace::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ParticleSystemSimulationSpace_t2969500608, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PARTICLESYSTEMSIMULATIONSPACE_T2969500608_H
#ifndef COMPONENT_T1923634451_H
#define COMPONENT_T1923634451_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Component
struct Component_t1923634451 : public Object_t631007953
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // COMPONENT_T1923634451_H
#ifndef EMITPARAMS_T2216423628_H
#define EMITPARAMS_T2216423628_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystem/EmitParams
struct EmitParams_t2216423628
{
public:
// UnityEngine.ParticleSystem/Particle UnityEngine.ParticleSystem/EmitParams::m_Particle
Particle_t1882894987 ___m_Particle_0;
// System.Boolean UnityEngine.ParticleSystem/EmitParams::m_PositionSet
bool ___m_PositionSet_1;
// System.Boolean UnityEngine.ParticleSystem/EmitParams::m_VelocitySet
bool ___m_VelocitySet_2;
// System.Boolean UnityEngine.ParticleSystem/EmitParams::m_AxisOfRotationSet
bool ___m_AxisOfRotationSet_3;
// System.Boolean UnityEngine.ParticleSystem/EmitParams::m_RotationSet
bool ___m_RotationSet_4;
// System.Boolean UnityEngine.ParticleSystem/EmitParams::m_AngularVelocitySet
bool ___m_AngularVelocitySet_5;
// System.Boolean UnityEngine.ParticleSystem/EmitParams::m_StartSizeSet
bool ___m_StartSizeSet_6;
// System.Boolean UnityEngine.ParticleSystem/EmitParams::m_StartColorSet
bool ___m_StartColorSet_7;
// System.Boolean UnityEngine.ParticleSystem/EmitParams::m_RandomSeedSet
bool ___m_RandomSeedSet_8;
// System.Boolean UnityEngine.ParticleSystem/EmitParams::m_StartLifetimeSet
bool ___m_StartLifetimeSet_9;
// System.Boolean UnityEngine.ParticleSystem/EmitParams::m_ApplyShapeToPosition
bool ___m_ApplyShapeToPosition_10;
public:
inline static int32_t get_offset_of_m_Particle_0() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_Particle_0)); }
inline Particle_t1882894987 get_m_Particle_0() const { return ___m_Particle_0; }
inline Particle_t1882894987 * get_address_of_m_Particle_0() { return &___m_Particle_0; }
inline void set_m_Particle_0(Particle_t1882894987 value)
{
___m_Particle_0 = value;
}
inline static int32_t get_offset_of_m_PositionSet_1() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_PositionSet_1)); }
inline bool get_m_PositionSet_1() const { return ___m_PositionSet_1; }
inline bool* get_address_of_m_PositionSet_1() { return &___m_PositionSet_1; }
inline void set_m_PositionSet_1(bool value)
{
___m_PositionSet_1 = value;
}
inline static int32_t get_offset_of_m_VelocitySet_2() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_VelocitySet_2)); }
inline bool get_m_VelocitySet_2() const { return ___m_VelocitySet_2; }
inline bool* get_address_of_m_VelocitySet_2() { return &___m_VelocitySet_2; }
inline void set_m_VelocitySet_2(bool value)
{
___m_VelocitySet_2 = value;
}
inline static int32_t get_offset_of_m_AxisOfRotationSet_3() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_AxisOfRotationSet_3)); }
inline bool get_m_AxisOfRotationSet_3() const { return ___m_AxisOfRotationSet_3; }
inline bool* get_address_of_m_AxisOfRotationSet_3() { return &___m_AxisOfRotationSet_3; }
inline void set_m_AxisOfRotationSet_3(bool value)
{
___m_AxisOfRotationSet_3 = value;
}
inline static int32_t get_offset_of_m_RotationSet_4() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_RotationSet_4)); }
inline bool get_m_RotationSet_4() const { return ___m_RotationSet_4; }
inline bool* get_address_of_m_RotationSet_4() { return &___m_RotationSet_4; }
inline void set_m_RotationSet_4(bool value)
{
___m_RotationSet_4 = value;
}
inline static int32_t get_offset_of_m_AngularVelocitySet_5() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_AngularVelocitySet_5)); }
inline bool get_m_AngularVelocitySet_5() const { return ___m_AngularVelocitySet_5; }
inline bool* get_address_of_m_AngularVelocitySet_5() { return &___m_AngularVelocitySet_5; }
inline void set_m_AngularVelocitySet_5(bool value)
{
___m_AngularVelocitySet_5 = value;
}
inline static int32_t get_offset_of_m_StartSizeSet_6() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_StartSizeSet_6)); }
inline bool get_m_StartSizeSet_6() const { return ___m_StartSizeSet_6; }
inline bool* get_address_of_m_StartSizeSet_6() { return &___m_StartSizeSet_6; }
inline void set_m_StartSizeSet_6(bool value)
{
___m_StartSizeSet_6 = value;
}
inline static int32_t get_offset_of_m_StartColorSet_7() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_StartColorSet_7)); }
inline bool get_m_StartColorSet_7() const { return ___m_StartColorSet_7; }
inline bool* get_address_of_m_StartColorSet_7() { return &___m_StartColorSet_7; }
inline void set_m_StartColorSet_7(bool value)
{
___m_StartColorSet_7 = value;
}
inline static int32_t get_offset_of_m_RandomSeedSet_8() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_RandomSeedSet_8)); }
inline bool get_m_RandomSeedSet_8() const { return ___m_RandomSeedSet_8; }
inline bool* get_address_of_m_RandomSeedSet_8() { return &___m_RandomSeedSet_8; }
inline void set_m_RandomSeedSet_8(bool value)
{
___m_RandomSeedSet_8 = value;
}
inline static int32_t get_offset_of_m_StartLifetimeSet_9() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_StartLifetimeSet_9)); }
inline bool get_m_StartLifetimeSet_9() const { return ___m_StartLifetimeSet_9; }
inline bool* get_address_of_m_StartLifetimeSet_9() { return &___m_StartLifetimeSet_9; }
inline void set_m_StartLifetimeSet_9(bool value)
{
___m_StartLifetimeSet_9 = value;
}
inline static int32_t get_offset_of_m_ApplyShapeToPosition_10() { return static_cast<int32_t>(offsetof(EmitParams_t2216423628, ___m_ApplyShapeToPosition_10)); }
inline bool get_m_ApplyShapeToPosition_10() const { return ___m_ApplyShapeToPosition_10; }
inline bool* get_address_of_m_ApplyShapeToPosition_10() { return &___m_ApplyShapeToPosition_10; }
inline void set_m_ApplyShapeToPosition_10(bool value)
{
___m_ApplyShapeToPosition_10 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.ParticleSystem/EmitParams
struct EmitParams_t2216423628_marshaled_pinvoke
{
Particle_t1882894987 ___m_Particle_0;
int32_t ___m_PositionSet_1;
int32_t ___m_VelocitySet_2;
int32_t ___m_AxisOfRotationSet_3;
int32_t ___m_RotationSet_4;
int32_t ___m_AngularVelocitySet_5;
int32_t ___m_StartSizeSet_6;
int32_t ___m_StartColorSet_7;
int32_t ___m_RandomSeedSet_8;
int32_t ___m_StartLifetimeSet_9;
int32_t ___m_ApplyShapeToPosition_10;
};
// Native definition for COM marshalling of UnityEngine.ParticleSystem/EmitParams
struct EmitParams_t2216423628_marshaled_com
{
Particle_t1882894987 ___m_Particle_0;
int32_t ___m_PositionSet_1;
int32_t ___m_VelocitySet_2;
int32_t ___m_AxisOfRotationSet_3;
int32_t ___m_RotationSet_4;
int32_t ___m_AngularVelocitySet_5;
int32_t ___m_StartSizeSet_6;
int32_t ___m_StartColorSet_7;
int32_t ___m_RandomSeedSet_8;
int32_t ___m_StartLifetimeSet_9;
int32_t ___m_ApplyShapeToPosition_10;
};
#endif // EMITPARAMS_T2216423628_H
#ifndef MINMAXCURVE_T1067599125_H
#define MINMAXCURVE_T1067599125_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystem/MinMaxCurve
struct MinMaxCurve_t1067599125
{
public:
// UnityEngine.ParticleSystemCurveMode UnityEngine.ParticleSystem/MinMaxCurve::m_Mode
int32_t ___m_Mode_0;
// System.Single UnityEngine.ParticleSystem/MinMaxCurve::m_CurveMultiplier
float ___m_CurveMultiplier_1;
// UnityEngine.AnimationCurve UnityEngine.ParticleSystem/MinMaxCurve::m_CurveMin
AnimationCurve_t3046754366 * ___m_CurveMin_2;
// UnityEngine.AnimationCurve UnityEngine.ParticleSystem/MinMaxCurve::m_CurveMax
AnimationCurve_t3046754366 * ___m_CurveMax_3;
// System.Single UnityEngine.ParticleSystem/MinMaxCurve::m_ConstantMin
float ___m_ConstantMin_4;
// System.Single UnityEngine.ParticleSystem/MinMaxCurve::m_ConstantMax
float ___m_ConstantMax_5;
public:
inline static int32_t get_offset_of_m_Mode_0() { return static_cast<int32_t>(offsetof(MinMaxCurve_t1067599125, ___m_Mode_0)); }
inline int32_t get_m_Mode_0() const { return ___m_Mode_0; }
inline int32_t* get_address_of_m_Mode_0() { return &___m_Mode_0; }
inline void set_m_Mode_0(int32_t value)
{
___m_Mode_0 = value;
}
inline static int32_t get_offset_of_m_CurveMultiplier_1() { return static_cast<int32_t>(offsetof(MinMaxCurve_t1067599125, ___m_CurveMultiplier_1)); }
inline float get_m_CurveMultiplier_1() const { return ___m_CurveMultiplier_1; }
inline float* get_address_of_m_CurveMultiplier_1() { return &___m_CurveMultiplier_1; }
inline void set_m_CurveMultiplier_1(float value)
{
___m_CurveMultiplier_1 = value;
}
inline static int32_t get_offset_of_m_CurveMin_2() { return static_cast<int32_t>(offsetof(MinMaxCurve_t1067599125, ___m_CurveMin_2)); }
inline AnimationCurve_t3046754366 * get_m_CurveMin_2() const { return ___m_CurveMin_2; }
inline AnimationCurve_t3046754366 ** get_address_of_m_CurveMin_2() { return &___m_CurveMin_2; }
inline void set_m_CurveMin_2(AnimationCurve_t3046754366 * value)
{
___m_CurveMin_2 = value;
Il2CppCodeGenWriteBarrier((&___m_CurveMin_2), value);
}
inline static int32_t get_offset_of_m_CurveMax_3() { return static_cast<int32_t>(offsetof(MinMaxCurve_t1067599125, ___m_CurveMax_3)); }
inline AnimationCurve_t3046754366 * get_m_CurveMax_3() const { return ___m_CurveMax_3; }
inline AnimationCurve_t3046754366 ** get_address_of_m_CurveMax_3() { return &___m_CurveMax_3; }
inline void set_m_CurveMax_3(AnimationCurve_t3046754366 * value)
{
___m_CurveMax_3 = value;
Il2CppCodeGenWriteBarrier((&___m_CurveMax_3), value);
}
inline static int32_t get_offset_of_m_ConstantMin_4() { return static_cast<int32_t>(offsetof(MinMaxCurve_t1067599125, ___m_ConstantMin_4)); }
inline float get_m_ConstantMin_4() const { return ___m_ConstantMin_4; }
inline float* get_address_of_m_ConstantMin_4() { return &___m_ConstantMin_4; }
inline void set_m_ConstantMin_4(float value)
{
___m_ConstantMin_4 = value;
}
inline static int32_t get_offset_of_m_ConstantMax_5() { return static_cast<int32_t>(offsetof(MinMaxCurve_t1067599125, ___m_ConstantMax_5)); }
inline float get_m_ConstantMax_5() const { return ___m_ConstantMax_5; }
inline float* get_address_of_m_ConstantMax_5() { return &___m_ConstantMax_5; }
inline void set_m_ConstantMax_5(float value)
{
___m_ConstantMax_5 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// Native definition for P/Invoke marshalling of UnityEngine.ParticleSystem/MinMaxCurve
struct MinMaxCurve_t1067599125_marshaled_pinvoke
{
int32_t ___m_Mode_0;
float ___m_CurveMultiplier_1;
AnimationCurve_t3046754366_marshaled_pinvoke ___m_CurveMin_2;
AnimationCurve_t3046754366_marshaled_pinvoke ___m_CurveMax_3;
float ___m_ConstantMin_4;
float ___m_ConstantMax_5;
};
// Native definition for COM marshalling of UnityEngine.ParticleSystem/MinMaxCurve
struct MinMaxCurve_t1067599125_marshaled_com
{
int32_t ___m_Mode_0;
float ___m_CurveMultiplier_1;
AnimationCurve_t3046754366_marshaled_com* ___m_CurveMin_2;
AnimationCurve_t3046754366_marshaled_com* ___m_CurveMax_3;
float ___m_ConstantMin_4;
float ___m_ConstantMax_5;
};
#endif // MINMAXCURVE_T1067599125_H
#ifndef PARTICLESYSTEM_T1800779281_H
#define PARTICLESYSTEM_T1800779281_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystem
struct ParticleSystem_t1800779281 : public Component_t1923634451
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PARTICLESYSTEM_T1800779281_H
#ifndef RENDERER_T2627027031_H
#define RENDERER_T2627027031_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.Renderer
struct Renderer_t2627027031 : public Component_t1923634451
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // RENDERER_T2627027031_H
#ifndef PARTICLESYSTEMRENDERER_T2065813411_H
#define PARTICLESYSTEMRENDERER_T2065813411_H
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.ParticleSystemRenderer
struct ParticleSystemRenderer_t2065813411 : public Renderer_t2627027031
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif // PARTICLESYSTEMRENDERER_T2065813411_H
// UnityEngine.ParticleSystem/Particle[]
struct ParticleU5BU5D_t3069227754 : public RuntimeArray
{
public:
ALIGN_FIELD (8) Particle_t1882894987 m_Items[1];
public:
inline Particle_t1882894987 GetAt(il2cpp_array_size_t index) const
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items[index];
}
inline Particle_t1882894987 * GetAddressAt(il2cpp_array_size_t index)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
return m_Items + index;
}
inline void SetAt(il2cpp_array_size_t index, Particle_t1882894987 value)
{
IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length);
m_Items[index] = value;
}
inline Particle_t1882894987 GetAtUnchecked(il2cpp_array_size_t index) const
{
return m_Items[index];
}
inline Particle_t1882894987 * GetAddressAtUnchecked(il2cpp_array_size_t index)
{
return m_Items + index;
}
inline void SetAtUnchecked(il2cpp_array_size_t index, Particle_t1882894987 value)
{
m_Items[index] = value;
}
};
extern "C" void AnimationCurve_t3046754366_marshal_pinvoke(const AnimationCurve_t3046754366& unmarshaled, AnimationCurve_t3046754366_marshaled_pinvoke& marshaled);
extern "C" void AnimationCurve_t3046754366_marshal_pinvoke_back(const AnimationCurve_t3046754366_marshaled_pinvoke& marshaled, AnimationCurve_t3046754366& unmarshaled);
extern "C" void AnimationCurve_t3046754366_marshal_pinvoke_cleanup(AnimationCurve_t3046754366_marshaled_pinvoke& marshaled);
extern "C" void AnimationCurve_t3046754366_marshal_com(const AnimationCurve_t3046754366& unmarshaled, AnimationCurve_t3046754366_marshaled_com& marshaled);
extern "C" void AnimationCurve_t3046754366_marshal_com_back(const AnimationCurve_t3046754366_marshaled_com& marshaled, AnimationCurve_t3046754366& unmarshaled);
extern "C" void AnimationCurve_t3046754366_marshal_com_cleanup(AnimationCurve_t3046754366_marshaled_com& marshaled);
// System.Void UnityEngine.ParticleSystem::INTERNAL_CALL_GetParticleCurrentColor(UnityEngine.ParticleSystem,UnityEngine.ParticleSystem/Particle&,UnityEngine.Color32&)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_INTERNAL_CALL_GetParticleCurrentColor_m2229758757 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___self0, Particle_t1882894987 * ___particle1, Color32_t2600501292 * ___value2, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/MainModule::.ctor(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR void MainModule__ctor_m1745438521 (MainModule_t2320046318 * __this, ParticleSystem_t1800779281 * ___particleSystem0, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/TextureSheetAnimationModule::.ctor(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR void TextureSheetAnimationModule__ctor_m932769825 (TextureSheetAnimationModule_t738696839 * __this, ParticleSystem_t1800779281 * ___particleSystem0, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem::INTERNAL_CALL_Emit(UnityEngine.ParticleSystem,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_INTERNAL_CALL_Emit_m662166748 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___self0, int32_t ___count1, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem::Internal_Emit(UnityEngine.ParticleSystem/EmitParams&,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_Internal_Emit_m2240046946 (ParticleSystem_t1800779281 * __this, EmitParams_t2216423628 * ___emitParams0, int32_t ___count1, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/Particle::set_position(UnityEngine.Vector3)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_position_m4147191379 (Particle_t1882894987 * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/Particle::set_velocity(UnityEngine.Vector3)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_velocity_m1686335204 (Particle_t1882894987 * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/Particle::set_lifetime(System.Single)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_lifetime_m1971908220 (Particle_t1882894987 * __this, float ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/Particle::set_startLifetime(System.Single)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_startLifetime_m2608171500 (Particle_t1882894987 * __this, float ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/Particle::set_startSize(System.Single)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_startSize_m2554682920 (Particle_t1882894987 * __this, float ___value0, const RuntimeMethod* method);
// UnityEngine.Vector3 UnityEngine.Vector3::get_zero()
extern "C" IL2CPP_METHOD_ATTR Vector3_t3722313464 Vector3_get_zero_m1409827619 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/Particle::set_rotation3D(UnityEngine.Vector3)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_rotation3D_m2156157200 (Particle_t1882894987 * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/Particle::set_angularVelocity3D(UnityEngine.Vector3)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_angularVelocity3D_m3163963446 (Particle_t1882894987 * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/Particle::set_startColor(UnityEngine.Color32)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_startColor_m3825027702 (Particle_t1882894987 * __this, Color32_t2600501292 ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/Particle::set_randomSeed(System.UInt32)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_randomSeed_m2900137887 (Particle_t1882894987 * __this, uint32_t ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem::Internal_EmitOld(UnityEngine.ParticleSystem/Particle&)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_Internal_EmitOld_m3511379528 (ParticleSystem_t1800779281 * __this, Particle_t1882894987 * ___particle0, const RuntimeMethod* method);
// UnityEngine.ParticleSystemSimulationSpace UnityEngine.ParticleSystem/MainModule::GetSimulationSpace(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_GetSimulationSpace_m148461669 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// UnityEngine.ParticleSystemSimulationSpace UnityEngine.ParticleSystem/MainModule::get_simulationSpace()
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_get_simulationSpace_m2279134456 (MainModule_t2320046318 * __this, const RuntimeMethod* method);
// UnityEngine.ParticleSystemScalingMode UnityEngine.ParticleSystem/MainModule::GetScalingMode(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_GetScalingMode_m990858662 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// UnityEngine.ParticleSystemScalingMode UnityEngine.ParticleSystem/MainModule::get_scalingMode()
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_get_scalingMode_m747393725 (MainModule_t2320046318 * __this, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/MainModule::SetScalingMode(UnityEngine.ParticleSystem,UnityEngine.ParticleSystemScalingMode)
extern "C" IL2CPP_METHOD_ATTR void MainModule_SetScalingMode_m15816227 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, int32_t ___value1, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/MainModule::set_scalingMode(UnityEngine.ParticleSystemScalingMode)
extern "C" IL2CPP_METHOD_ATTR void MainModule_set_scalingMode_m915979420 (MainModule_t2320046318 * __this, int32_t ___value0, const RuntimeMethod* method);
// System.Int32 UnityEngine.ParticleSystem/MainModule::GetMaxParticles(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_GetMaxParticles_m2130637551 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// System.Int32 UnityEngine.ParticleSystem/MainModule::get_maxParticles()
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_get_maxParticles_m2105979121 (MainModule_t2320046318 * __this, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/MainModule::SetMaxParticles(UnityEngine.ParticleSystem,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void MainModule_SetMaxParticles_m2916351937 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, int32_t ___value1, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/MainModule::set_maxParticles(System.Int32)
extern "C" IL2CPP_METHOD_ATTR void MainModule_set_maxParticles_m3383762699 (MainModule_t2320046318 * __this, int32_t ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.AnimationCurve::.ctor()
extern "C" IL2CPP_METHOD_ATTR void AnimationCurve__ctor_m3000526466 (AnimationCurve_t3046754366 * __this, const RuntimeMethod* method);
// UnityEngine.AnimationCurve UnityEngine.ParticleSystem/MinMaxCurve::get_curveMin()
extern "C" IL2CPP_METHOD_ATTR AnimationCurve_t3046754366 * MinMaxCurve_get_curveMin_m1577567431 (MinMaxCurve_t1067599125 * __this, const RuntimeMethod* method);
// System.Single UnityEngine.ParticleSystem/MinMaxCurve::get_constant()
extern "C" IL2CPP_METHOD_ATTR float MinMaxCurve_get_constant_m2963124720 (MinMaxCurve_t1067599125 * __this, const RuntimeMethod* method);
// UnityEngine.AnimationCurve UnityEngine.ParticleSystem/MinMaxCurve::get_curve()
extern "C" IL2CPP_METHOD_ATTR AnimationCurve_t3046754366 * MinMaxCurve_get_curve_m4228822969 (MinMaxCurve_t1067599125 * __this, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/Particle::set_remainingLifetime(System.Single)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_remainingLifetime_m3875738131 (Particle_t1882894987 * __this, float ___value0, const RuntimeMethod* method);
// UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::get_position()
extern "C" IL2CPP_METHOD_ATTR Vector3_t3722313464 Particle_get_position_m855792854 (Particle_t1882894987 * __this, const RuntimeMethod* method);
// System.Single UnityEngine.ParticleSystem/Particle::get_remainingLifetime()
extern "C" IL2CPP_METHOD_ATTR float Particle_get_remainingLifetime_m4053779941 (Particle_t1882894987 * __this, const RuntimeMethod* method);
// System.Single UnityEngine.ParticleSystem/Particle::get_startLifetime()
extern "C" IL2CPP_METHOD_ATTR float Particle_get_startLifetime_m1587267174 (Particle_t1882894987 * __this, const RuntimeMethod* method);
// System.Void UnityEngine.Vector3::.ctor(System.Single,System.Single,System.Single)
extern "C" IL2CPP_METHOD_ATTR void Vector3__ctor_m3353183577 (Vector3_t3722313464 * __this, float p0, float p1, float p2, const RuntimeMethod* method);
// System.Single UnityEngine.ParticleSystem/Particle::get_rotation()
extern "C" IL2CPP_METHOD_ATTR float Particle_get_rotation_m3158189621 (Particle_t1882894987 * __this, const RuntimeMethod* method);
// UnityEngine.Vector3 UnityEngine.Vector3::op_Multiply(UnityEngine.Vector3,System.Single)
extern "C" IL2CPP_METHOD_ATTR Vector3_t3722313464 Vector3_op_Multiply_m3376773913 (RuntimeObject * __this /* static, unused */, Vector3_t3722313464 p0, float p1, const RuntimeMethod* method);
// System.Single UnityEngine.ParticleSystem::GetParticleCurrentSize(UnityEngine.ParticleSystem/Particle&)
extern "C" IL2CPP_METHOD_ATTR float ParticleSystem_GetParticleCurrentSize_m3932820070 (ParticleSystem_t1800779281 * __this, Particle_t1882894987 * ___particle0, const RuntimeMethod* method);
// System.Single UnityEngine.ParticleSystem/Particle::GetCurrentSize(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR float Particle_GetCurrentSize_m1620066418 (Particle_t1882894987 * __this, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// UnityEngine.Color32 UnityEngine.ParticleSystem::GetParticleCurrentColor(UnityEngine.ParticleSystem/Particle&)
extern "C" IL2CPP_METHOD_ATTR Color32_t2600501292 ParticleSystem_GetParticleCurrentColor_m3489023316 (ParticleSystem_t1800779281 * __this, Particle_t1882894987 * ___particle0, const RuntimeMethod* method);
// UnityEngine.Color32 UnityEngine.ParticleSystem/Particle::GetCurrentColor(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR Color32_t2600501292 Particle_GetCurrentColor_m1246398760 (Particle_t1882894987 * __this, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// System.Boolean UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetEnabled(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR bool TextureSheetAnimationModule_GetEnabled_m2810172049 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// System.Boolean UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_enabled()
extern "C" IL2CPP_METHOD_ATTR bool TextureSheetAnimationModule_get_enabled_m2099392666 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method);
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetNumTilesX(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_GetNumTilesX_m1010355971 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_numTilesX()
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_get_numTilesX_m3782231855 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method);
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetNumTilesY(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_GetNumTilesY_m2021848348 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_numTilesY()
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_get_numTilesY_m1053348500 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method);
// UnityEngine.ParticleSystemAnimationType UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetAnimationType(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_GetAnimationType_m2914365387 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// UnityEngine.ParticleSystemAnimationType UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_animation()
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_get_animation_m2249866915 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method);
// System.Void UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetFrameOverTime(UnityEngine.ParticleSystem,UnityEngine.ParticleSystem/MinMaxCurve&)
extern "C" IL2CPP_METHOD_ATTR void TextureSheetAnimationModule_GetFrameOverTime_m371108956 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, MinMaxCurve_t1067599125 * ___curve1, const RuntimeMethod* method);
// UnityEngine.ParticleSystem/MinMaxCurve UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_frameOverTime()
extern "C" IL2CPP_METHOD_ATTR MinMaxCurve_t1067599125 TextureSheetAnimationModule_get_frameOverTime_m3059492834 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method);
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetCycleCount(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_GetCycleCount_m4232892544 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_cycleCount()
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_get_cycleCount_m1231605148 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method);
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetRowIndex(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_GetRowIndex_m3246918826 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method);
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_rowIndex()
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_get_rowIndex_m1602825482 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method);
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Single UnityEngine.ParticleSystem::GetParticleCurrentSize(UnityEngine.ParticleSystem/Particle&)
extern "C" IL2CPP_METHOD_ATTR float ParticleSystem_GetParticleCurrentSize_m3932820070 (ParticleSystem_t1800779281 * __this, Particle_t1882894987 * ___particle0, const RuntimeMethod* method)
{
typedef float (*ParticleSystem_GetParticleCurrentSize_m3932820070_ftn) (ParticleSystem_t1800779281 *, Particle_t1882894987 *);
static ParticleSystem_GetParticleCurrentSize_m3932820070_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (ParticleSystem_GetParticleCurrentSize_m3932820070_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::GetParticleCurrentSize(UnityEngine.ParticleSystem/Particle&)");
float retVal = _il2cpp_icall_func(__this, ___particle0);
return retVal;
}
// UnityEngine.Color32 UnityEngine.ParticleSystem::GetParticleCurrentColor(UnityEngine.ParticleSystem/Particle&)
extern "C" IL2CPP_METHOD_ATTR Color32_t2600501292 ParticleSystem_GetParticleCurrentColor_m3489023316 (ParticleSystem_t1800779281 * __this, Particle_t1882894987 * ___particle0, const RuntimeMethod* method)
{
Color32_t2600501292 V_0;
memset(&V_0, 0, sizeof(V_0));
Color32_t2600501292 V_1;
memset(&V_1, 0, sizeof(V_1));
{
Particle_t1882894987 * L_0 = ___particle0;
ParticleSystem_INTERNAL_CALL_GetParticleCurrentColor_m2229758757(NULL /*static, unused*/, __this, (Particle_t1882894987 *)L_0, (Color32_t2600501292 *)(&V_0), /*hidden argument*/NULL);
Color32_t2600501292 L_1 = V_0;
V_1 = L_1;
goto IL_0011;
}
IL_0011:
{
Color32_t2600501292 L_2 = V_1;
return L_2;
}
}
// System.Void UnityEngine.ParticleSystem::INTERNAL_CALL_GetParticleCurrentColor(UnityEngine.ParticleSystem,UnityEngine.ParticleSystem/Particle&,UnityEngine.Color32&)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_INTERNAL_CALL_GetParticleCurrentColor_m2229758757 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___self0, Particle_t1882894987 * ___particle1, Color32_t2600501292 * ___value2, const RuntimeMethod* method)
{
typedef void (*ParticleSystem_INTERNAL_CALL_GetParticleCurrentColor_m2229758757_ftn) (ParticleSystem_t1800779281 *, Particle_t1882894987 *, Color32_t2600501292 *);
static ParticleSystem_INTERNAL_CALL_GetParticleCurrentColor_m2229758757_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (ParticleSystem_INTERNAL_CALL_GetParticleCurrentColor_m2229758757_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::INTERNAL_CALL_GetParticleCurrentColor(UnityEngine.ParticleSystem,UnityEngine.ParticleSystem/Particle&,UnityEngine.Color32&)");
_il2cpp_icall_func(___self0, ___particle1, ___value2);
}
// UnityEngine.ParticleSystem/MainModule UnityEngine.ParticleSystem::get_main()
extern "C" IL2CPP_METHOD_ATTR MainModule_t2320046318 ParticleSystem_get_main_m3006917117 (ParticleSystem_t1800779281 * __this, const RuntimeMethod* method)
{
MainModule_t2320046318 V_0;
memset(&V_0, 0, sizeof(V_0));
{
MainModule_t2320046318 L_0;
memset(&L_0, 0, sizeof(L_0));
MainModule__ctor_m1745438521((&L_0), __this, /*hidden argument*/NULL);
V_0 = L_0;
goto IL_000d;
}
IL_000d:
{
MainModule_t2320046318 L_1 = V_0;
return L_1;
}
}
// UnityEngine.ParticleSystem/TextureSheetAnimationModule UnityEngine.ParticleSystem::get_textureSheetAnimation()
extern "C" IL2CPP_METHOD_ATTR TextureSheetAnimationModule_t738696839 ParticleSystem_get_textureSheetAnimation_m4276810064 (ParticleSystem_t1800779281 * __this, const RuntimeMethod* method)
{
TextureSheetAnimationModule_t738696839 V_0;
memset(&V_0, 0, sizeof(V_0));
{
TextureSheetAnimationModule_t738696839 L_0;
memset(&L_0, 0, sizeof(L_0));
TextureSheetAnimationModule__ctor_m932769825((&L_0), __this, /*hidden argument*/NULL);
V_0 = L_0;
goto IL_000d;
}
IL_000d:
{
TextureSheetAnimationModule_t738696839 L_1 = V_0;
return L_1;
}
}
// System.Int32 UnityEngine.ParticleSystem::GetParticles(UnityEngine.ParticleSystem/Particle[])
extern "C" IL2CPP_METHOD_ATTR int32_t ParticleSystem_GetParticles_m3661771371 (ParticleSystem_t1800779281 * __this, ParticleU5BU5D_t3069227754* ___particles0, const RuntimeMethod* method)
{
typedef int32_t (*ParticleSystem_GetParticles_m3661771371_ftn) (ParticleSystem_t1800779281 *, ParticleU5BU5D_t3069227754*);
static ParticleSystem_GetParticles_m3661771371_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (ParticleSystem_GetParticles_m3661771371_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::GetParticles(UnityEngine.ParticleSystem/Particle[])");
int32_t retVal = _il2cpp_icall_func(__this, ___particles0);
return retVal;
}
// System.Void UnityEngine.ParticleSystem::Simulate(System.Single,System.Boolean,System.Boolean,System.Boolean)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_Simulate_m1921398215 (ParticleSystem_t1800779281 * __this, float ___t0, bool ___withChildren1, bool ___restart2, bool ___fixedTimeStep3, const RuntimeMethod* method)
{
typedef void (*ParticleSystem_Simulate_m1921398215_ftn) (ParticleSystem_t1800779281 *, float, bool, bool, bool);
static ParticleSystem_Simulate_m1921398215_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (ParticleSystem_Simulate_m1921398215_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::Simulate(System.Single,System.Boolean,System.Boolean,System.Boolean)");
_il2cpp_icall_func(__this, ___t0, ___withChildren1, ___restart2, ___fixedTimeStep3);
}
// System.Void UnityEngine.ParticleSystem::Emit(System.Int32)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_Emit_m2162102900 (ParticleSystem_t1800779281 * __this, int32_t ___count0, const RuntimeMethod* method)
{
{
int32_t L_0 = ___count0;
ParticleSystem_INTERNAL_CALL_Emit_m662166748(NULL /*static, unused*/, __this, L_0, /*hidden argument*/NULL);
return;
}
}
// System.Void UnityEngine.ParticleSystem::INTERNAL_CALL_Emit(UnityEngine.ParticleSystem,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_INTERNAL_CALL_Emit_m662166748 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___self0, int32_t ___count1, const RuntimeMethod* method)
{
typedef void (*ParticleSystem_INTERNAL_CALL_Emit_m662166748_ftn) (ParticleSystem_t1800779281 *, int32_t);
static ParticleSystem_INTERNAL_CALL_Emit_m662166748_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (ParticleSystem_INTERNAL_CALL_Emit_m662166748_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::INTERNAL_CALL_Emit(UnityEngine.ParticleSystem,System.Int32)");
_il2cpp_icall_func(___self0, ___count1);
}
// System.Void UnityEngine.ParticleSystem::Internal_EmitOld(UnityEngine.ParticleSystem/Particle&)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_Internal_EmitOld_m3511379528 (ParticleSystem_t1800779281 * __this, Particle_t1882894987 * ___particle0, const RuntimeMethod* method)
{
typedef void (*ParticleSystem_Internal_EmitOld_m3511379528_ftn) (ParticleSystem_t1800779281 *, Particle_t1882894987 *);
static ParticleSystem_Internal_EmitOld_m3511379528_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (ParticleSystem_Internal_EmitOld_m3511379528_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::Internal_EmitOld(UnityEngine.ParticleSystem/Particle&)");
_il2cpp_icall_func(__this, ___particle0);
}
// System.Void UnityEngine.ParticleSystem::Emit(UnityEngine.ParticleSystem/EmitParams,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_Emit_m1241484254 (ParticleSystem_t1800779281 * __this, EmitParams_t2216423628 ___emitParams0, int32_t ___count1, const RuntimeMethod* method)
{
{
int32_t L_0 = ___count1;
ParticleSystem_Internal_Emit_m2240046946(__this, (EmitParams_t2216423628 *)(&___emitParams0), L_0, /*hidden argument*/NULL);
return;
}
}
// System.Void UnityEngine.ParticleSystem::Internal_Emit(UnityEngine.ParticleSystem/EmitParams&,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_Internal_Emit_m2240046946 (ParticleSystem_t1800779281 * __this, EmitParams_t2216423628 * ___emitParams0, int32_t ___count1, const RuntimeMethod* method)
{
typedef void (*ParticleSystem_Internal_Emit_m2240046946_ftn) (ParticleSystem_t1800779281 *, EmitParams_t2216423628 *, int32_t);
static ParticleSystem_Internal_Emit_m2240046946_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (ParticleSystem_Internal_Emit_m2240046946_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem::Internal_Emit(UnityEngine.ParticleSystem/EmitParams&,System.Int32)");
_il2cpp_icall_func(__this, ___emitParams0, ___count1);
}
// System.Void UnityEngine.ParticleSystem::Emit(UnityEngine.Vector3,UnityEngine.Vector3,System.Single,System.Single,UnityEngine.Color32)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_Emit_m497964751 (ParticleSystem_t1800779281 * __this, Vector3_t3722313464 ___position0, Vector3_t3722313464 ___velocity1, float ___size2, float ___lifetime3, Color32_t2600501292 ___color4, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (ParticleSystem_Emit_m497964751_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
Particle_t1882894987 V_0;
memset(&V_0, 0, sizeof(V_0));
{
il2cpp_codegen_initobj((&V_0), sizeof(Particle_t1882894987 ));
Vector3_t3722313464 L_0 = ___position0;
Particle_set_position_m4147191379((Particle_t1882894987 *)(&V_0), L_0, /*hidden argument*/NULL);
Vector3_t3722313464 L_1 = ___velocity1;
Particle_set_velocity_m1686335204((Particle_t1882894987 *)(&V_0), L_1, /*hidden argument*/NULL);
float L_2 = ___lifetime3;
Particle_set_lifetime_m1971908220((Particle_t1882894987 *)(&V_0), L_2, /*hidden argument*/NULL);
float L_3 = ___lifetime3;
Particle_set_startLifetime_m2608171500((Particle_t1882894987 *)(&V_0), L_3, /*hidden argument*/NULL);
float L_4 = ___size2;
Particle_set_startSize_m2554682920((Particle_t1882894987 *)(&V_0), L_4, /*hidden argument*/NULL);
IL2CPP_RUNTIME_CLASS_INIT(Vector3_t3722313464_il2cpp_TypeInfo_var);
Vector3_t3722313464 L_5 = Vector3_get_zero_m1409827619(NULL /*static, unused*/, /*hidden argument*/NULL);
Particle_set_rotation3D_m2156157200((Particle_t1882894987 *)(&V_0), L_5, /*hidden argument*/NULL);
Vector3_t3722313464 L_6 = Vector3_get_zero_m1409827619(NULL /*static, unused*/, /*hidden argument*/NULL);
Particle_set_angularVelocity3D_m3163963446((Particle_t1882894987 *)(&V_0), L_6, /*hidden argument*/NULL);
Color32_t2600501292 L_7 = ___color4;
Particle_set_startColor_m3825027702((Particle_t1882894987 *)(&V_0), L_7, /*hidden argument*/NULL);
Particle_set_randomSeed_m2900137887((Particle_t1882894987 *)(&V_0), 5, /*hidden argument*/NULL);
ParticleSystem_Internal_EmitOld_m3511379528(__this, (Particle_t1882894987 *)(&V_0), /*hidden argument*/NULL);
return;
}
}
// System.Void UnityEngine.ParticleSystem::Emit(UnityEngine.ParticleSystem/Particle)
extern "C" IL2CPP_METHOD_ATTR void ParticleSystem_Emit_m4116897928 (ParticleSystem_t1800779281 * __this, Particle_t1882894987 ___particle0, const RuntimeMethod* method)
{
{
ParticleSystem_Internal_EmitOld_m3511379528(__this, (Particle_t1882894987 *)(&___particle0), /*hidden argument*/NULL);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Conversion methods for marshalling of: UnityEngine.ParticleSystem/EmitParams
extern "C" void EmitParams_t2216423628_marshal_pinvoke(const EmitParams_t2216423628& unmarshaled, EmitParams_t2216423628_marshaled_pinvoke& marshaled)
{
marshaled.___m_Particle_0 = unmarshaled.get_m_Particle_0();
marshaled.___m_PositionSet_1 = static_cast<int32_t>(unmarshaled.get_m_PositionSet_1());
marshaled.___m_VelocitySet_2 = static_cast<int32_t>(unmarshaled.get_m_VelocitySet_2());
marshaled.___m_AxisOfRotationSet_3 = static_cast<int32_t>(unmarshaled.get_m_AxisOfRotationSet_3());
marshaled.___m_RotationSet_4 = static_cast<int32_t>(unmarshaled.get_m_RotationSet_4());
marshaled.___m_AngularVelocitySet_5 = static_cast<int32_t>(unmarshaled.get_m_AngularVelocitySet_5());
marshaled.___m_StartSizeSet_6 = static_cast<int32_t>(unmarshaled.get_m_StartSizeSet_6());
marshaled.___m_StartColorSet_7 = static_cast<int32_t>(unmarshaled.get_m_StartColorSet_7());
marshaled.___m_RandomSeedSet_8 = static_cast<int32_t>(unmarshaled.get_m_RandomSeedSet_8());
marshaled.___m_StartLifetimeSet_9 = static_cast<int32_t>(unmarshaled.get_m_StartLifetimeSet_9());
marshaled.___m_ApplyShapeToPosition_10 = static_cast<int32_t>(unmarshaled.get_m_ApplyShapeToPosition_10());
}
extern "C" void EmitParams_t2216423628_marshal_pinvoke_back(const EmitParams_t2216423628_marshaled_pinvoke& marshaled, EmitParams_t2216423628& unmarshaled)
{
Particle_t1882894987 unmarshaled_m_Particle_temp_0;
memset(&unmarshaled_m_Particle_temp_0, 0, sizeof(unmarshaled_m_Particle_temp_0));
unmarshaled_m_Particle_temp_0 = marshaled.___m_Particle_0;
unmarshaled.set_m_Particle_0(unmarshaled_m_Particle_temp_0);
bool unmarshaled_m_PositionSet_temp_1 = false;
unmarshaled_m_PositionSet_temp_1 = static_cast<bool>(marshaled.___m_PositionSet_1);
unmarshaled.set_m_PositionSet_1(unmarshaled_m_PositionSet_temp_1);
bool unmarshaled_m_VelocitySet_temp_2 = false;
unmarshaled_m_VelocitySet_temp_2 = static_cast<bool>(marshaled.___m_VelocitySet_2);
unmarshaled.set_m_VelocitySet_2(unmarshaled_m_VelocitySet_temp_2);
bool unmarshaled_m_AxisOfRotationSet_temp_3 = false;
unmarshaled_m_AxisOfRotationSet_temp_3 = static_cast<bool>(marshaled.___m_AxisOfRotationSet_3);
unmarshaled.set_m_AxisOfRotationSet_3(unmarshaled_m_AxisOfRotationSet_temp_3);
bool unmarshaled_m_RotationSet_temp_4 = false;
unmarshaled_m_RotationSet_temp_4 = static_cast<bool>(marshaled.___m_RotationSet_4);
unmarshaled.set_m_RotationSet_4(unmarshaled_m_RotationSet_temp_4);
bool unmarshaled_m_AngularVelocitySet_temp_5 = false;
unmarshaled_m_AngularVelocitySet_temp_5 = static_cast<bool>(marshaled.___m_AngularVelocitySet_5);
unmarshaled.set_m_AngularVelocitySet_5(unmarshaled_m_AngularVelocitySet_temp_5);
bool unmarshaled_m_StartSizeSet_temp_6 = false;
unmarshaled_m_StartSizeSet_temp_6 = static_cast<bool>(marshaled.___m_StartSizeSet_6);
unmarshaled.set_m_StartSizeSet_6(unmarshaled_m_StartSizeSet_temp_6);
bool unmarshaled_m_StartColorSet_temp_7 = false;
unmarshaled_m_StartColorSet_temp_7 = static_cast<bool>(marshaled.___m_StartColorSet_7);
unmarshaled.set_m_StartColorSet_7(unmarshaled_m_StartColorSet_temp_7);
bool unmarshaled_m_RandomSeedSet_temp_8 = false;
unmarshaled_m_RandomSeedSet_temp_8 = static_cast<bool>(marshaled.___m_RandomSeedSet_8);
unmarshaled.set_m_RandomSeedSet_8(unmarshaled_m_RandomSeedSet_temp_8);
bool unmarshaled_m_StartLifetimeSet_temp_9 = false;
unmarshaled_m_StartLifetimeSet_temp_9 = static_cast<bool>(marshaled.___m_StartLifetimeSet_9);
unmarshaled.set_m_StartLifetimeSet_9(unmarshaled_m_StartLifetimeSet_temp_9);
bool unmarshaled_m_ApplyShapeToPosition_temp_10 = false;
unmarshaled_m_ApplyShapeToPosition_temp_10 = static_cast<bool>(marshaled.___m_ApplyShapeToPosition_10);
unmarshaled.set_m_ApplyShapeToPosition_10(unmarshaled_m_ApplyShapeToPosition_temp_10);
}
// Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/EmitParams
extern "C" void EmitParams_t2216423628_marshal_pinvoke_cleanup(EmitParams_t2216423628_marshaled_pinvoke& marshaled)
{
}
// Conversion methods for marshalling of: UnityEngine.ParticleSystem/EmitParams
extern "C" void EmitParams_t2216423628_marshal_com(const EmitParams_t2216423628& unmarshaled, EmitParams_t2216423628_marshaled_com& marshaled)
{
marshaled.___m_Particle_0 = unmarshaled.get_m_Particle_0();
marshaled.___m_PositionSet_1 = static_cast<int32_t>(unmarshaled.get_m_PositionSet_1());
marshaled.___m_VelocitySet_2 = static_cast<int32_t>(unmarshaled.get_m_VelocitySet_2());
marshaled.___m_AxisOfRotationSet_3 = static_cast<int32_t>(unmarshaled.get_m_AxisOfRotationSet_3());
marshaled.___m_RotationSet_4 = static_cast<int32_t>(unmarshaled.get_m_RotationSet_4());
marshaled.___m_AngularVelocitySet_5 = static_cast<int32_t>(unmarshaled.get_m_AngularVelocitySet_5());
marshaled.___m_StartSizeSet_6 = static_cast<int32_t>(unmarshaled.get_m_StartSizeSet_6());
marshaled.___m_StartColorSet_7 = static_cast<int32_t>(unmarshaled.get_m_StartColorSet_7());
marshaled.___m_RandomSeedSet_8 = static_cast<int32_t>(unmarshaled.get_m_RandomSeedSet_8());
marshaled.___m_StartLifetimeSet_9 = static_cast<int32_t>(unmarshaled.get_m_StartLifetimeSet_9());
marshaled.___m_ApplyShapeToPosition_10 = static_cast<int32_t>(unmarshaled.get_m_ApplyShapeToPosition_10());
}
extern "C" void EmitParams_t2216423628_marshal_com_back(const EmitParams_t2216423628_marshaled_com& marshaled, EmitParams_t2216423628& unmarshaled)
{
Particle_t1882894987 unmarshaled_m_Particle_temp_0;
memset(&unmarshaled_m_Particle_temp_0, 0, sizeof(unmarshaled_m_Particle_temp_0));
unmarshaled_m_Particle_temp_0 = marshaled.___m_Particle_0;
unmarshaled.set_m_Particle_0(unmarshaled_m_Particle_temp_0);
bool unmarshaled_m_PositionSet_temp_1 = false;
unmarshaled_m_PositionSet_temp_1 = static_cast<bool>(marshaled.___m_PositionSet_1);
unmarshaled.set_m_PositionSet_1(unmarshaled_m_PositionSet_temp_1);
bool unmarshaled_m_VelocitySet_temp_2 = false;
unmarshaled_m_VelocitySet_temp_2 = static_cast<bool>(marshaled.___m_VelocitySet_2);
unmarshaled.set_m_VelocitySet_2(unmarshaled_m_VelocitySet_temp_2);
bool unmarshaled_m_AxisOfRotationSet_temp_3 = false;
unmarshaled_m_AxisOfRotationSet_temp_3 = static_cast<bool>(marshaled.___m_AxisOfRotationSet_3);
unmarshaled.set_m_AxisOfRotationSet_3(unmarshaled_m_AxisOfRotationSet_temp_3);
bool unmarshaled_m_RotationSet_temp_4 = false;
unmarshaled_m_RotationSet_temp_4 = static_cast<bool>(marshaled.___m_RotationSet_4);
unmarshaled.set_m_RotationSet_4(unmarshaled_m_RotationSet_temp_4);
bool unmarshaled_m_AngularVelocitySet_temp_5 = false;
unmarshaled_m_AngularVelocitySet_temp_5 = static_cast<bool>(marshaled.___m_AngularVelocitySet_5);
unmarshaled.set_m_AngularVelocitySet_5(unmarshaled_m_AngularVelocitySet_temp_5);
bool unmarshaled_m_StartSizeSet_temp_6 = false;
unmarshaled_m_StartSizeSet_temp_6 = static_cast<bool>(marshaled.___m_StartSizeSet_6);
unmarshaled.set_m_StartSizeSet_6(unmarshaled_m_StartSizeSet_temp_6);
bool unmarshaled_m_StartColorSet_temp_7 = false;
unmarshaled_m_StartColorSet_temp_7 = static_cast<bool>(marshaled.___m_StartColorSet_7);
unmarshaled.set_m_StartColorSet_7(unmarshaled_m_StartColorSet_temp_7);
bool unmarshaled_m_RandomSeedSet_temp_8 = false;
unmarshaled_m_RandomSeedSet_temp_8 = static_cast<bool>(marshaled.___m_RandomSeedSet_8);
unmarshaled.set_m_RandomSeedSet_8(unmarshaled_m_RandomSeedSet_temp_8);
bool unmarshaled_m_StartLifetimeSet_temp_9 = false;
unmarshaled_m_StartLifetimeSet_temp_9 = static_cast<bool>(marshaled.___m_StartLifetimeSet_9);
unmarshaled.set_m_StartLifetimeSet_9(unmarshaled_m_StartLifetimeSet_temp_9);
bool unmarshaled_m_ApplyShapeToPosition_temp_10 = false;
unmarshaled_m_ApplyShapeToPosition_temp_10 = static_cast<bool>(marshaled.___m_ApplyShapeToPosition_10);
unmarshaled.set_m_ApplyShapeToPosition_10(unmarshaled_m_ApplyShapeToPosition_temp_10);
}
// Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/EmitParams
extern "C" void EmitParams_t2216423628_marshal_com_cleanup(EmitParams_t2216423628_marshaled_com& marshaled)
{
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Conversion methods for marshalling of: UnityEngine.ParticleSystem/MainModule
extern "C" void MainModule_t2320046318_marshal_pinvoke(const MainModule_t2320046318& unmarshaled, MainModule_t2320046318_marshaled_pinvoke& marshaled)
{
Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'MainModule': Reference type field marshaling is not supported.");
IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL, NULL);
}
extern "C" void MainModule_t2320046318_marshal_pinvoke_back(const MainModule_t2320046318_marshaled_pinvoke& marshaled, MainModule_t2320046318& unmarshaled)
{
Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'MainModule': Reference type field marshaling is not supported.");
IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL, NULL);
}
// Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/MainModule
extern "C" void MainModule_t2320046318_marshal_pinvoke_cleanup(MainModule_t2320046318_marshaled_pinvoke& marshaled)
{
}
// Conversion methods for marshalling of: UnityEngine.ParticleSystem/MainModule
extern "C" void MainModule_t2320046318_marshal_com(const MainModule_t2320046318& unmarshaled, MainModule_t2320046318_marshaled_com& marshaled)
{
Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'MainModule': Reference type field marshaling is not supported.");
IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL, NULL);
}
extern "C" void MainModule_t2320046318_marshal_com_back(const MainModule_t2320046318_marshaled_com& marshaled, MainModule_t2320046318& unmarshaled)
{
Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'MainModule': Reference type field marshaling is not supported.");
IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL, NULL);
}
// Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/MainModule
extern "C" void MainModule_t2320046318_marshal_com_cleanup(MainModule_t2320046318_marshaled_com& marshaled)
{
}
// System.Void UnityEngine.ParticleSystem/MainModule::.ctor(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR void MainModule__ctor_m1745438521 (MainModule_t2320046318 * __this, ParticleSystem_t1800779281 * ___particleSystem0, const RuntimeMethod* method)
{
{
ParticleSystem_t1800779281 * L_0 = ___particleSystem0;
__this->set_m_ParticleSystem_0(L_0);
return;
}
}
extern "C" void MainModule__ctor_m1745438521_AdjustorThunk (RuntimeObject * __this, ParticleSystem_t1800779281 * ___particleSystem0, const RuntimeMethod* method)
{
MainModule_t2320046318 * _thisAdjusted = reinterpret_cast<MainModule_t2320046318 *>(__this + 1);
MainModule__ctor_m1745438521(_thisAdjusted, ___particleSystem0, method);
}
// UnityEngine.ParticleSystemSimulationSpace UnityEngine.ParticleSystem/MainModule::get_simulationSpace()
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_get_simulationSpace_m2279134456 (MainModule_t2320046318 * __this, const RuntimeMethod* method)
{
int32_t V_0 = 0;
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
int32_t L_1 = MainModule_GetSimulationSpace_m148461669(NULL /*static, unused*/, L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
int32_t L_2 = V_0;
return L_2;
}
}
extern "C" int32_t MainModule_get_simulationSpace_m2279134456_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
MainModule_t2320046318 * _thisAdjusted = reinterpret_cast<MainModule_t2320046318 *>(__this + 1);
return MainModule_get_simulationSpace_m2279134456(_thisAdjusted, method);
}
// UnityEngine.ParticleSystemScalingMode UnityEngine.ParticleSystem/MainModule::get_scalingMode()
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_get_scalingMode_m747393725 (MainModule_t2320046318 * __this, const RuntimeMethod* method)
{
int32_t V_0 = 0;
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
int32_t L_1 = MainModule_GetScalingMode_m990858662(NULL /*static, unused*/, L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
int32_t L_2 = V_0;
return L_2;
}
}
extern "C" int32_t MainModule_get_scalingMode_m747393725_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
MainModule_t2320046318 * _thisAdjusted = reinterpret_cast<MainModule_t2320046318 *>(__this + 1);
return MainModule_get_scalingMode_m747393725(_thisAdjusted, method);
}
// System.Void UnityEngine.ParticleSystem/MainModule::set_scalingMode(UnityEngine.ParticleSystemScalingMode)
extern "C" IL2CPP_METHOD_ATTR void MainModule_set_scalingMode_m915979420 (MainModule_t2320046318 * __this, int32_t ___value0, const RuntimeMethod* method)
{
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
int32_t L_1 = ___value0;
MainModule_SetScalingMode_m15816227(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL);
return;
}
}
extern "C" void MainModule_set_scalingMode_m915979420_AdjustorThunk (RuntimeObject * __this, int32_t ___value0, const RuntimeMethod* method)
{
MainModule_t2320046318 * _thisAdjusted = reinterpret_cast<MainModule_t2320046318 *>(__this + 1);
MainModule_set_scalingMode_m915979420(_thisAdjusted, ___value0, method);
}
// System.Int32 UnityEngine.ParticleSystem/MainModule::get_maxParticles()
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_get_maxParticles_m2105979121 (MainModule_t2320046318 * __this, const RuntimeMethod* method)
{
int32_t V_0 = 0;
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
int32_t L_1 = MainModule_GetMaxParticles_m2130637551(NULL /*static, unused*/, L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
int32_t L_2 = V_0;
return L_2;
}
}
extern "C" int32_t MainModule_get_maxParticles_m2105979121_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
MainModule_t2320046318 * _thisAdjusted = reinterpret_cast<MainModule_t2320046318 *>(__this + 1);
return MainModule_get_maxParticles_m2105979121(_thisAdjusted, method);
}
// System.Void UnityEngine.ParticleSystem/MainModule::set_maxParticles(System.Int32)
extern "C" IL2CPP_METHOD_ATTR void MainModule_set_maxParticles_m3383762699 (MainModule_t2320046318 * __this, int32_t ___value0, const RuntimeMethod* method)
{
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
int32_t L_1 = ___value0;
MainModule_SetMaxParticles_m2916351937(NULL /*static, unused*/, L_0, L_1, /*hidden argument*/NULL);
return;
}
}
extern "C" void MainModule_set_maxParticles_m3383762699_AdjustorThunk (RuntimeObject * __this, int32_t ___value0, const RuntimeMethod* method)
{
MainModule_t2320046318 * _thisAdjusted = reinterpret_cast<MainModule_t2320046318 *>(__this + 1);
MainModule_set_maxParticles_m3383762699(_thisAdjusted, ___value0, method);
}
// UnityEngine.ParticleSystemSimulationSpace UnityEngine.ParticleSystem/MainModule::GetSimulationSpace(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_GetSimulationSpace_m148461669 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
typedef int32_t (*MainModule_GetSimulationSpace_m148461669_ftn) (ParticleSystem_t1800779281 *);
static MainModule_GetSimulationSpace_m148461669_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (MainModule_GetSimulationSpace_m148461669_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::GetSimulationSpace(UnityEngine.ParticleSystem)");
int32_t retVal = _il2cpp_icall_func(___system0);
return retVal;
}
// System.Void UnityEngine.ParticleSystem/MainModule::SetScalingMode(UnityEngine.ParticleSystem,UnityEngine.ParticleSystemScalingMode)
extern "C" IL2CPP_METHOD_ATTR void MainModule_SetScalingMode_m15816227 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, int32_t ___value1, const RuntimeMethod* method)
{
typedef void (*MainModule_SetScalingMode_m15816227_ftn) (ParticleSystem_t1800779281 *, int32_t);
static MainModule_SetScalingMode_m15816227_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (MainModule_SetScalingMode_m15816227_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::SetScalingMode(UnityEngine.ParticleSystem,UnityEngine.ParticleSystemScalingMode)");
_il2cpp_icall_func(___system0, ___value1);
}
// UnityEngine.ParticleSystemScalingMode UnityEngine.ParticleSystem/MainModule::GetScalingMode(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_GetScalingMode_m990858662 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
typedef int32_t (*MainModule_GetScalingMode_m990858662_ftn) (ParticleSystem_t1800779281 *);
static MainModule_GetScalingMode_m990858662_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (MainModule_GetScalingMode_m990858662_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::GetScalingMode(UnityEngine.ParticleSystem)");
int32_t retVal = _il2cpp_icall_func(___system0);
return retVal;
}
// System.Void UnityEngine.ParticleSystem/MainModule::SetMaxParticles(UnityEngine.ParticleSystem,System.Int32)
extern "C" IL2CPP_METHOD_ATTR void MainModule_SetMaxParticles_m2916351937 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, int32_t ___value1, const RuntimeMethod* method)
{
typedef void (*MainModule_SetMaxParticles_m2916351937_ftn) (ParticleSystem_t1800779281 *, int32_t);
static MainModule_SetMaxParticles_m2916351937_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (MainModule_SetMaxParticles_m2916351937_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::SetMaxParticles(UnityEngine.ParticleSystem,System.Int32)");
_il2cpp_icall_func(___system0, ___value1);
}
// System.Int32 UnityEngine.ParticleSystem/MainModule::GetMaxParticles(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t MainModule_GetMaxParticles_m2130637551 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
typedef int32_t (*MainModule_GetMaxParticles_m2130637551_ftn) (ParticleSystem_t1800779281 *);
static MainModule_GetMaxParticles_m2130637551_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (MainModule_GetMaxParticles_m2130637551_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/MainModule::GetMaxParticles(UnityEngine.ParticleSystem)");
int32_t retVal = _il2cpp_icall_func(___system0);
return retVal;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Conversion methods for marshalling of: UnityEngine.ParticleSystem/MinMaxCurve
extern "C" void MinMaxCurve_t1067599125_marshal_pinvoke(const MinMaxCurve_t1067599125& unmarshaled, MinMaxCurve_t1067599125_marshaled_pinvoke& marshaled)
{
marshaled.___m_Mode_0 = unmarshaled.get_m_Mode_0();
marshaled.___m_CurveMultiplier_1 = unmarshaled.get_m_CurveMultiplier_1();
if (unmarshaled.get_m_CurveMin_2() != NULL) AnimationCurve_t3046754366_marshal_pinvoke(*unmarshaled.get_m_CurveMin_2(), marshaled.___m_CurveMin_2);
if (unmarshaled.get_m_CurveMax_3() != NULL) AnimationCurve_t3046754366_marshal_pinvoke(*unmarshaled.get_m_CurveMax_3(), marshaled.___m_CurveMax_3);
marshaled.___m_ConstantMin_4 = unmarshaled.get_m_ConstantMin_4();
marshaled.___m_ConstantMax_5 = unmarshaled.get_m_ConstantMax_5();
}
extern "C" void MinMaxCurve_t1067599125_marshal_pinvoke_back(const MinMaxCurve_t1067599125_marshaled_pinvoke& marshaled, MinMaxCurve_t1067599125& unmarshaled)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (MinMaxCurve_t1067599125_pinvoke_FromNativeMethodDefinition_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
int32_t unmarshaled_m_Mode_temp_0 = 0;
unmarshaled_m_Mode_temp_0 = marshaled.___m_Mode_0;
unmarshaled.set_m_Mode_0(unmarshaled_m_Mode_temp_0);
float unmarshaled_m_CurveMultiplier_temp_1 = 0.0f;
unmarshaled_m_CurveMultiplier_temp_1 = marshaled.___m_CurveMultiplier_1;
unmarshaled.set_m_CurveMultiplier_1(unmarshaled_m_CurveMultiplier_temp_1);
unmarshaled.set_m_CurveMin_2((AnimationCurve_t3046754366 *)il2cpp_codegen_object_new(AnimationCurve_t3046754366_il2cpp_TypeInfo_var));
AnimationCurve__ctor_m3000526466(unmarshaled.get_m_CurveMin_2(), NULL);
AnimationCurve_t3046754366_marshal_pinvoke_back(marshaled.___m_CurveMin_2, *unmarshaled.get_m_CurveMin_2());
unmarshaled.set_m_CurveMax_3((AnimationCurve_t3046754366 *)il2cpp_codegen_object_new(AnimationCurve_t3046754366_il2cpp_TypeInfo_var));
AnimationCurve__ctor_m3000526466(unmarshaled.get_m_CurveMax_3(), NULL);
AnimationCurve_t3046754366_marshal_pinvoke_back(marshaled.___m_CurveMax_3, *unmarshaled.get_m_CurveMax_3());
float unmarshaled_m_ConstantMin_temp_4 = 0.0f;
unmarshaled_m_ConstantMin_temp_4 = marshaled.___m_ConstantMin_4;
unmarshaled.set_m_ConstantMin_4(unmarshaled_m_ConstantMin_temp_4);
float unmarshaled_m_ConstantMax_temp_5 = 0.0f;
unmarshaled_m_ConstantMax_temp_5 = marshaled.___m_ConstantMax_5;
unmarshaled.set_m_ConstantMax_5(unmarshaled_m_ConstantMax_temp_5);
}
// Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/MinMaxCurve
extern "C" void MinMaxCurve_t1067599125_marshal_pinvoke_cleanup(MinMaxCurve_t1067599125_marshaled_pinvoke& marshaled)
{
AnimationCurve_t3046754366_marshal_pinvoke_cleanup(marshaled.___m_CurveMin_2);
AnimationCurve_t3046754366_marshal_pinvoke_cleanup(marshaled.___m_CurveMax_3);
}
// Conversion methods for marshalling of: UnityEngine.ParticleSystem/MinMaxCurve
extern "C" void MinMaxCurve_t1067599125_marshal_com(const MinMaxCurve_t1067599125& unmarshaled, MinMaxCurve_t1067599125_marshaled_com& marshaled)
{
marshaled.___m_Mode_0 = unmarshaled.get_m_Mode_0();
marshaled.___m_CurveMultiplier_1 = unmarshaled.get_m_CurveMultiplier_1();
if (unmarshaled.get_m_CurveMin_2() != NULL) AnimationCurve_t3046754366_marshal_com(*unmarshaled.get_m_CurveMin_2(), *marshaled.___m_CurveMin_2);
if (unmarshaled.get_m_CurveMax_3() != NULL) AnimationCurve_t3046754366_marshal_com(*unmarshaled.get_m_CurveMax_3(), *marshaled.___m_CurveMax_3);
marshaled.___m_ConstantMin_4 = unmarshaled.get_m_ConstantMin_4();
marshaled.___m_ConstantMax_5 = unmarshaled.get_m_ConstantMax_5();
}
extern "C" void MinMaxCurve_t1067599125_marshal_com_back(const MinMaxCurve_t1067599125_marshaled_com& marshaled, MinMaxCurve_t1067599125& unmarshaled)
{
int32_t unmarshaled_m_Mode_temp_0 = 0;
unmarshaled_m_Mode_temp_0 = marshaled.___m_Mode_0;
unmarshaled.set_m_Mode_0(unmarshaled_m_Mode_temp_0);
float unmarshaled_m_CurveMultiplier_temp_1 = 0.0f;
unmarshaled_m_CurveMultiplier_temp_1 = marshaled.___m_CurveMultiplier_1;
unmarshaled.set_m_CurveMultiplier_1(unmarshaled_m_CurveMultiplier_temp_1);
if (unmarshaled.get_m_CurveMin_2() != NULL)
{
AnimationCurve__ctor_m3000526466(unmarshaled.get_m_CurveMin_2(), NULL);
AnimationCurve_t3046754366_marshal_com_back(*marshaled.___m_CurveMin_2, *unmarshaled.get_m_CurveMin_2());
}
if (unmarshaled.get_m_CurveMax_3() != NULL)
{
AnimationCurve__ctor_m3000526466(unmarshaled.get_m_CurveMax_3(), NULL);
AnimationCurve_t3046754366_marshal_com_back(*marshaled.___m_CurveMax_3, *unmarshaled.get_m_CurveMax_3());
}
float unmarshaled_m_ConstantMin_temp_4 = 0.0f;
unmarshaled_m_ConstantMin_temp_4 = marshaled.___m_ConstantMin_4;
unmarshaled.set_m_ConstantMin_4(unmarshaled_m_ConstantMin_temp_4);
float unmarshaled_m_ConstantMax_temp_5 = 0.0f;
unmarshaled_m_ConstantMax_temp_5 = marshaled.___m_ConstantMax_5;
unmarshaled.set_m_ConstantMax_5(unmarshaled_m_ConstantMax_temp_5);
}
// Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/MinMaxCurve
extern "C" void MinMaxCurve_t1067599125_marshal_com_cleanup(MinMaxCurve_t1067599125_marshaled_com& marshaled)
{
if (&(*marshaled.___m_CurveMin_2) != NULL) AnimationCurve_t3046754366_marshal_com_cleanup(*marshaled.___m_CurveMin_2);
if (&(*marshaled.___m_CurveMax_3) != NULL) AnimationCurve_t3046754366_marshal_com_cleanup(*marshaled.___m_CurveMax_3);
}
// UnityEngine.AnimationCurve UnityEngine.ParticleSystem/MinMaxCurve::get_curveMin()
extern "C" IL2CPP_METHOD_ATTR AnimationCurve_t3046754366 * MinMaxCurve_get_curveMin_m1577567431 (MinMaxCurve_t1067599125 * __this, const RuntimeMethod* method)
{
AnimationCurve_t3046754366 * V_0 = NULL;
{
AnimationCurve_t3046754366 * L_0 = __this->get_m_CurveMin_2();
V_0 = L_0;
goto IL_000d;
}
IL_000d:
{
AnimationCurve_t3046754366 * L_1 = V_0;
return L_1;
}
}
extern "C" AnimationCurve_t3046754366 * MinMaxCurve_get_curveMin_m1577567431_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
MinMaxCurve_t1067599125 * _thisAdjusted = reinterpret_cast<MinMaxCurve_t1067599125 *>(__this + 1);
return MinMaxCurve_get_curveMin_m1577567431(_thisAdjusted, method);
}
// System.Single UnityEngine.ParticleSystem/MinMaxCurve::get_constant()
extern "C" IL2CPP_METHOD_ATTR float MinMaxCurve_get_constant_m2963124720 (MinMaxCurve_t1067599125 * __this, const RuntimeMethod* method)
{
float V_0 = 0.0f;
{
float L_0 = __this->get_m_ConstantMax_5();
V_0 = L_0;
goto IL_000d;
}
IL_000d:
{
float L_1 = V_0;
return L_1;
}
}
extern "C" float MinMaxCurve_get_constant_m2963124720_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
MinMaxCurve_t1067599125 * _thisAdjusted = reinterpret_cast<MinMaxCurve_t1067599125 *>(__this + 1);
return MinMaxCurve_get_constant_m2963124720(_thisAdjusted, method);
}
// UnityEngine.AnimationCurve UnityEngine.ParticleSystem/MinMaxCurve::get_curve()
extern "C" IL2CPP_METHOD_ATTR AnimationCurve_t3046754366 * MinMaxCurve_get_curve_m4228822969 (MinMaxCurve_t1067599125 * __this, const RuntimeMethod* method)
{
AnimationCurve_t3046754366 * V_0 = NULL;
{
AnimationCurve_t3046754366 * L_0 = __this->get_m_CurveMax_3();
V_0 = L_0;
goto IL_000d;
}
IL_000d:
{
AnimationCurve_t3046754366 * L_1 = V_0;
return L_1;
}
}
extern "C" AnimationCurve_t3046754366 * MinMaxCurve_get_curve_m4228822969_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
MinMaxCurve_t1067599125 * _thisAdjusted = reinterpret_cast<MinMaxCurve_t1067599125 *>(__this + 1);
return MinMaxCurve_get_curve_m4228822969(_thisAdjusted, method);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void UnityEngine.ParticleSystem/Particle::set_lifetime(System.Single)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_lifetime_m1971908220 (Particle_t1882894987 * __this, float ___value0, const RuntimeMethod* method)
{
{
float L_0 = ___value0;
Particle_set_remainingLifetime_m3875738131((Particle_t1882894987 *)__this, L_0, /*hidden argument*/NULL);
return;
}
}
extern "C" void Particle_set_lifetime_m1971908220_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
Particle_set_lifetime_m1971908220(_thisAdjusted, ___value0, method);
}
// UnityEngine.Vector3 UnityEngine.ParticleSystem/Particle::get_position()
extern "C" IL2CPP_METHOD_ATTR Vector3_t3722313464 Particle_get_position_m855792854 (Particle_t1882894987 * __this, const RuntimeMethod* method)
{
Vector3_t3722313464 V_0;
memset(&V_0, 0, sizeof(V_0));
{
Vector3_t3722313464 L_0 = __this->get_m_Position_0();
V_0 = L_0;
goto IL_000d;
}
IL_000d:
{
Vector3_t3722313464 L_1 = V_0;
return L_1;
}
}
extern "C" Vector3_t3722313464 Particle_get_position_m855792854_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
return Particle_get_position_m855792854(_thisAdjusted, method);
}
// System.Void UnityEngine.ParticleSystem/Particle::set_position(UnityEngine.Vector3)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_position_m4147191379 (Particle_t1882894987 * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method)
{
{
Vector3_t3722313464 L_0 = ___value0;
__this->set_m_Position_0(L_0);
return;
}
}
extern "C" void Particle_set_position_m4147191379_AdjustorThunk (RuntimeObject * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
Particle_set_position_m4147191379(_thisAdjusted, ___value0, method);
}
// System.Void UnityEngine.ParticleSystem/Particle::set_velocity(UnityEngine.Vector3)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_velocity_m1686335204 (Particle_t1882894987 * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method)
{
{
Vector3_t3722313464 L_0 = ___value0;
__this->set_m_Velocity_1(L_0);
return;
}
}
extern "C" void Particle_set_velocity_m1686335204_AdjustorThunk (RuntimeObject * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
Particle_set_velocity_m1686335204(_thisAdjusted, ___value0, method);
}
// System.Single UnityEngine.ParticleSystem/Particle::get_remainingLifetime()
extern "C" IL2CPP_METHOD_ATTR float Particle_get_remainingLifetime_m4053779941 (Particle_t1882894987 * __this, const RuntimeMethod* method)
{
float V_0 = 0.0f;
{
float L_0 = __this->get_m_Lifetime_10();
V_0 = L_0;
goto IL_000d;
}
IL_000d:
{
float L_1 = V_0;
return L_1;
}
}
extern "C" float Particle_get_remainingLifetime_m4053779941_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
return Particle_get_remainingLifetime_m4053779941(_thisAdjusted, method);
}
// System.Void UnityEngine.ParticleSystem/Particle::set_remainingLifetime(System.Single)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_remainingLifetime_m3875738131 (Particle_t1882894987 * __this, float ___value0, const RuntimeMethod* method)
{
{
float L_0 = ___value0;
__this->set_m_Lifetime_10(L_0);
return;
}
}
extern "C" void Particle_set_remainingLifetime_m3875738131_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
Particle_set_remainingLifetime_m3875738131(_thisAdjusted, ___value0, method);
}
// System.Single UnityEngine.ParticleSystem/Particle::get_startLifetime()
extern "C" IL2CPP_METHOD_ATTR float Particle_get_startLifetime_m1587267174 (Particle_t1882894987 * __this, const RuntimeMethod* method)
{
float V_0 = 0.0f;
{
float L_0 = __this->get_m_StartLifetime_11();
V_0 = L_0;
goto IL_000d;
}
IL_000d:
{
float L_1 = V_0;
return L_1;
}
}
extern "C" float Particle_get_startLifetime_m1587267174_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
return Particle_get_startLifetime_m1587267174(_thisAdjusted, method);
}
// System.Void UnityEngine.ParticleSystem/Particle::set_startLifetime(System.Single)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_startLifetime_m2608171500 (Particle_t1882894987 * __this, float ___value0, const RuntimeMethod* method)
{
{
float L_0 = ___value0;
__this->set_m_StartLifetime_11(L_0);
return;
}
}
extern "C" void Particle_set_startLifetime_m2608171500_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
Particle_set_startLifetime_m2608171500(_thisAdjusted, ___value0, method);
}
// System.Void UnityEngine.ParticleSystem/Particle::set_startColor(UnityEngine.Color32)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_startColor_m3825027702 (Particle_t1882894987 * __this, Color32_t2600501292 ___value0, const RuntimeMethod* method)
{
{
Color32_t2600501292 L_0 = ___value0;
__this->set_m_StartColor_8(L_0);
return;
}
}
extern "C" void Particle_set_startColor_m3825027702_AdjustorThunk (RuntimeObject * __this, Color32_t2600501292 ___value0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
Particle_set_startColor_m3825027702(_thisAdjusted, ___value0, method);
}
// System.Void UnityEngine.ParticleSystem/Particle::set_randomSeed(System.UInt32)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_randomSeed_m2900137887 (Particle_t1882894987 * __this, uint32_t ___value0, const RuntimeMethod* method)
{
{
uint32_t L_0 = ___value0;
__this->set_m_RandomSeed_9(L_0);
return;
}
}
extern "C" void Particle_set_randomSeed_m2900137887_AdjustorThunk (RuntimeObject * __this, uint32_t ___value0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
Particle_set_randomSeed_m2900137887(_thisAdjusted, ___value0, method);
}
// System.Void UnityEngine.ParticleSystem/Particle::set_startSize(System.Single)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_startSize_m2554682920 (Particle_t1882894987 * __this, float ___value0, const RuntimeMethod* method)
{
{
float L_0 = ___value0;
float L_1 = ___value0;
float L_2 = ___value0;
Vector3_t3722313464 L_3;
memset(&L_3, 0, sizeof(L_3));
Vector3__ctor_m3353183577((&L_3), L_0, L_1, L_2, /*hidden argument*/NULL);
__this->set_m_StartSize_7(L_3);
return;
}
}
extern "C" void Particle_set_startSize_m2554682920_AdjustorThunk (RuntimeObject * __this, float ___value0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
Particle_set_startSize_m2554682920(_thisAdjusted, ___value0, method);
}
// System.Single UnityEngine.ParticleSystem/Particle::get_rotation()
extern "C" IL2CPP_METHOD_ATTR float Particle_get_rotation_m3158189621 (Particle_t1882894987 * __this, const RuntimeMethod* method)
{
float V_0 = 0.0f;
{
Vector3_t3722313464 * L_0 = __this->get_address_of_m_Rotation_5();
float L_1 = L_0->get_z_4();
V_0 = ((float)il2cpp_codegen_multiply((float)L_1, (float)(57.29578f)));
goto IL_0018;
}
IL_0018:
{
float L_2 = V_0;
return L_2;
}
}
extern "C" float Particle_get_rotation_m3158189621_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
return Particle_get_rotation_m3158189621(_thisAdjusted, method);
}
// System.Void UnityEngine.ParticleSystem/Particle::set_rotation3D(UnityEngine.Vector3)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_rotation3D_m2156157200 (Particle_t1882894987 * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (Particle_set_rotation3D_m2156157200_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
{
Vector3_t3722313464 L_0 = ___value0;
IL2CPP_RUNTIME_CLASS_INIT(Vector3_t3722313464_il2cpp_TypeInfo_var);
Vector3_t3722313464 L_1 = Vector3_op_Multiply_m3376773913(NULL /*static, unused*/, L_0, (0.0174532924f), /*hidden argument*/NULL);
__this->set_m_Rotation_5(L_1);
return;
}
}
extern "C" void Particle_set_rotation3D_m2156157200_AdjustorThunk (RuntimeObject * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
Particle_set_rotation3D_m2156157200(_thisAdjusted, ___value0, method);
}
// System.Void UnityEngine.ParticleSystem/Particle::set_angularVelocity3D(UnityEngine.Vector3)
extern "C" IL2CPP_METHOD_ATTR void Particle_set_angularVelocity3D_m3163963446 (Particle_t1882894987 * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_method (Particle_set_angularVelocity3D_m3163963446_MetadataUsageId);
s_Il2CppMethodInitialized = true;
}
{
Vector3_t3722313464 L_0 = ___value0;
IL2CPP_RUNTIME_CLASS_INIT(Vector3_t3722313464_il2cpp_TypeInfo_var);
Vector3_t3722313464 L_1 = Vector3_op_Multiply_m3376773913(NULL /*static, unused*/, L_0, (0.0174532924f), /*hidden argument*/NULL);
__this->set_m_AngularVelocity_6(L_1);
return;
}
}
extern "C" void Particle_set_angularVelocity3D_m3163963446_AdjustorThunk (RuntimeObject * __this, Vector3_t3722313464 ___value0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
Particle_set_angularVelocity3D_m3163963446(_thisAdjusted, ___value0, method);
}
// System.Single UnityEngine.ParticleSystem/Particle::GetCurrentSize(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR float Particle_GetCurrentSize_m1620066418 (Particle_t1882894987 * __this, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
float V_0 = 0.0f;
{
ParticleSystem_t1800779281 * L_0 = ___system0;
NullCheck(L_0);
float L_1 = ParticleSystem_GetParticleCurrentSize_m3932820070(L_0, (Particle_t1882894987 *)__this, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_000e;
}
IL_000e:
{
float L_2 = V_0;
return L_2;
}
}
extern "C" float Particle_GetCurrentSize_m1620066418_AdjustorThunk (RuntimeObject * __this, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
return Particle_GetCurrentSize_m1620066418(_thisAdjusted, ___system0, method);
}
// UnityEngine.Color32 UnityEngine.ParticleSystem/Particle::GetCurrentColor(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR Color32_t2600501292 Particle_GetCurrentColor_m1246398760 (Particle_t1882894987 * __this, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
Color32_t2600501292 V_0;
memset(&V_0, 0, sizeof(V_0));
{
ParticleSystem_t1800779281 * L_0 = ___system0;
NullCheck(L_0);
Color32_t2600501292 L_1 = ParticleSystem_GetParticleCurrentColor_m3489023316(L_0, (Particle_t1882894987 *)__this, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_000e;
}
IL_000e:
{
Color32_t2600501292 L_2 = V_0;
return L_2;
}
}
extern "C" Color32_t2600501292 Particle_GetCurrentColor_m1246398760_AdjustorThunk (RuntimeObject * __this, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
Particle_t1882894987 * _thisAdjusted = reinterpret_cast<Particle_t1882894987 *>(__this + 1);
return Particle_GetCurrentColor_m1246398760(_thisAdjusted, ___system0, method);
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// Conversion methods for marshalling of: UnityEngine.ParticleSystem/TextureSheetAnimationModule
extern "C" void TextureSheetAnimationModule_t738696839_marshal_pinvoke(const TextureSheetAnimationModule_t738696839& unmarshaled, TextureSheetAnimationModule_t738696839_marshaled_pinvoke& marshaled)
{
Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'TextureSheetAnimationModule': Reference type field marshaling is not supported.");
IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL, NULL);
}
extern "C" void TextureSheetAnimationModule_t738696839_marshal_pinvoke_back(const TextureSheetAnimationModule_t738696839_marshaled_pinvoke& marshaled, TextureSheetAnimationModule_t738696839& unmarshaled)
{
Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'TextureSheetAnimationModule': Reference type field marshaling is not supported.");
IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL, NULL);
}
// Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/TextureSheetAnimationModule
extern "C" void TextureSheetAnimationModule_t738696839_marshal_pinvoke_cleanup(TextureSheetAnimationModule_t738696839_marshaled_pinvoke& marshaled)
{
}
// Conversion methods for marshalling of: UnityEngine.ParticleSystem/TextureSheetAnimationModule
extern "C" void TextureSheetAnimationModule_t738696839_marshal_com(const TextureSheetAnimationModule_t738696839& unmarshaled, TextureSheetAnimationModule_t738696839_marshaled_com& marshaled)
{
Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'TextureSheetAnimationModule': Reference type field marshaling is not supported.");
IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL, NULL);
}
extern "C" void TextureSheetAnimationModule_t738696839_marshal_com_back(const TextureSheetAnimationModule_t738696839_marshaled_com& marshaled, TextureSheetAnimationModule_t738696839& unmarshaled)
{
Exception_t* ___m_ParticleSystem_0Exception = il2cpp_codegen_get_marshal_directive_exception("Cannot marshal field 'm_ParticleSystem' of type 'TextureSheetAnimationModule': Reference type field marshaling is not supported.");
IL2CPP_RAISE_MANAGED_EXCEPTION(___m_ParticleSystem_0Exception, NULL, NULL);
}
// Conversion method for clean up from marshalling of: UnityEngine.ParticleSystem/TextureSheetAnimationModule
extern "C" void TextureSheetAnimationModule_t738696839_marshal_com_cleanup(TextureSheetAnimationModule_t738696839_marshaled_com& marshaled)
{
}
// System.Void UnityEngine.ParticleSystem/TextureSheetAnimationModule::.ctor(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR void TextureSheetAnimationModule__ctor_m932769825 (TextureSheetAnimationModule_t738696839 * __this, ParticleSystem_t1800779281 * ___particleSystem0, const RuntimeMethod* method)
{
{
ParticleSystem_t1800779281 * L_0 = ___particleSystem0;
__this->set_m_ParticleSystem_0(L_0);
return;
}
}
extern "C" void TextureSheetAnimationModule__ctor_m932769825_AdjustorThunk (RuntimeObject * __this, ParticleSystem_t1800779281 * ___particleSystem0, const RuntimeMethod* method)
{
TextureSheetAnimationModule_t738696839 * _thisAdjusted = reinterpret_cast<TextureSheetAnimationModule_t738696839 *>(__this + 1);
TextureSheetAnimationModule__ctor_m932769825(_thisAdjusted, ___particleSystem0, method);
}
// System.Boolean UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_enabled()
extern "C" IL2CPP_METHOD_ATTR bool TextureSheetAnimationModule_get_enabled_m2099392666 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method)
{
bool V_0 = false;
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
bool L_1 = TextureSheetAnimationModule_GetEnabled_m2810172049(NULL /*static, unused*/, L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
bool L_2 = V_0;
return L_2;
}
}
extern "C" bool TextureSheetAnimationModule_get_enabled_m2099392666_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
TextureSheetAnimationModule_t738696839 * _thisAdjusted = reinterpret_cast<TextureSheetAnimationModule_t738696839 *>(__this + 1);
return TextureSheetAnimationModule_get_enabled_m2099392666(_thisAdjusted, method);
}
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_numTilesX()
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_get_numTilesX_m3782231855 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method)
{
int32_t V_0 = 0;
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
int32_t L_1 = TextureSheetAnimationModule_GetNumTilesX_m1010355971(NULL /*static, unused*/, L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
int32_t L_2 = V_0;
return L_2;
}
}
extern "C" int32_t TextureSheetAnimationModule_get_numTilesX_m3782231855_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
TextureSheetAnimationModule_t738696839 * _thisAdjusted = reinterpret_cast<TextureSheetAnimationModule_t738696839 *>(__this + 1);
return TextureSheetAnimationModule_get_numTilesX_m3782231855(_thisAdjusted, method);
}
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_numTilesY()
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_get_numTilesY_m1053348500 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method)
{
int32_t V_0 = 0;
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
int32_t L_1 = TextureSheetAnimationModule_GetNumTilesY_m2021848348(NULL /*static, unused*/, L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
int32_t L_2 = V_0;
return L_2;
}
}
extern "C" int32_t TextureSheetAnimationModule_get_numTilesY_m1053348500_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
TextureSheetAnimationModule_t738696839 * _thisAdjusted = reinterpret_cast<TextureSheetAnimationModule_t738696839 *>(__this + 1);
return TextureSheetAnimationModule_get_numTilesY_m1053348500(_thisAdjusted, method);
}
// UnityEngine.ParticleSystemAnimationType UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_animation()
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_get_animation_m2249866915 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method)
{
int32_t V_0 = 0;
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
int32_t L_1 = TextureSheetAnimationModule_GetAnimationType_m2914365387(NULL /*static, unused*/, L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
int32_t L_2 = V_0;
return L_2;
}
}
extern "C" int32_t TextureSheetAnimationModule_get_animation_m2249866915_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
TextureSheetAnimationModule_t738696839 * _thisAdjusted = reinterpret_cast<TextureSheetAnimationModule_t738696839 *>(__this + 1);
return TextureSheetAnimationModule_get_animation_m2249866915(_thisAdjusted, method);
}
// UnityEngine.ParticleSystem/MinMaxCurve UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_frameOverTime()
extern "C" IL2CPP_METHOD_ATTR MinMaxCurve_t1067599125 TextureSheetAnimationModule_get_frameOverTime_m3059492834 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method)
{
MinMaxCurve_t1067599125 V_0;
memset(&V_0, 0, sizeof(V_0));
MinMaxCurve_t1067599125 V_1;
memset(&V_1, 0, sizeof(V_1));
{
il2cpp_codegen_initobj((&V_0), sizeof(MinMaxCurve_t1067599125 ));
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
TextureSheetAnimationModule_GetFrameOverTime_m371108956(NULL /*static, unused*/, L_0, (MinMaxCurve_t1067599125 *)(&V_0), /*hidden argument*/NULL);
MinMaxCurve_t1067599125 L_1 = V_0;
V_1 = L_1;
goto IL_001d;
}
IL_001d:
{
MinMaxCurve_t1067599125 L_2 = V_1;
return L_2;
}
}
extern "C" MinMaxCurve_t1067599125 TextureSheetAnimationModule_get_frameOverTime_m3059492834_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
TextureSheetAnimationModule_t738696839 * _thisAdjusted = reinterpret_cast<TextureSheetAnimationModule_t738696839 *>(__this + 1);
return TextureSheetAnimationModule_get_frameOverTime_m3059492834(_thisAdjusted, method);
}
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_cycleCount()
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_get_cycleCount_m1231605148 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method)
{
int32_t V_0 = 0;
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
int32_t L_1 = TextureSheetAnimationModule_GetCycleCount_m4232892544(NULL /*static, unused*/, L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
int32_t L_2 = V_0;
return L_2;
}
}
extern "C" int32_t TextureSheetAnimationModule_get_cycleCount_m1231605148_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
TextureSheetAnimationModule_t738696839 * _thisAdjusted = reinterpret_cast<TextureSheetAnimationModule_t738696839 *>(__this + 1);
return TextureSheetAnimationModule_get_cycleCount_m1231605148(_thisAdjusted, method);
}
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::get_rowIndex()
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_get_rowIndex_m1602825482 (TextureSheetAnimationModule_t738696839 * __this, const RuntimeMethod* method)
{
int32_t V_0 = 0;
{
ParticleSystem_t1800779281 * L_0 = __this->get_m_ParticleSystem_0();
int32_t L_1 = TextureSheetAnimationModule_GetRowIndex_m3246918826(NULL /*static, unused*/, L_0, /*hidden argument*/NULL);
V_0 = L_1;
goto IL_0012;
}
IL_0012:
{
int32_t L_2 = V_0;
return L_2;
}
}
extern "C" int32_t TextureSheetAnimationModule_get_rowIndex_m1602825482_AdjustorThunk (RuntimeObject * __this, const RuntimeMethod* method)
{
TextureSheetAnimationModule_t738696839 * _thisAdjusted = reinterpret_cast<TextureSheetAnimationModule_t738696839 *>(__this + 1);
return TextureSheetAnimationModule_get_rowIndex_m1602825482(_thisAdjusted, method);
}
// System.Boolean UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetEnabled(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR bool TextureSheetAnimationModule_GetEnabled_m2810172049 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
typedef bool (*TextureSheetAnimationModule_GetEnabled_m2810172049_ftn) (ParticleSystem_t1800779281 *);
static TextureSheetAnimationModule_GetEnabled_m2810172049_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (TextureSheetAnimationModule_GetEnabled_m2810172049_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetEnabled(UnityEngine.ParticleSystem)");
bool retVal = _il2cpp_icall_func(___system0);
return retVal;
}
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetNumTilesX(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_GetNumTilesX_m1010355971 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
typedef int32_t (*TextureSheetAnimationModule_GetNumTilesX_m1010355971_ftn) (ParticleSystem_t1800779281 *);
static TextureSheetAnimationModule_GetNumTilesX_m1010355971_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (TextureSheetAnimationModule_GetNumTilesX_m1010355971_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetNumTilesX(UnityEngine.ParticleSystem)");
int32_t retVal = _il2cpp_icall_func(___system0);
return retVal;
}
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetNumTilesY(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_GetNumTilesY_m2021848348 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
typedef int32_t (*TextureSheetAnimationModule_GetNumTilesY_m2021848348_ftn) (ParticleSystem_t1800779281 *);
static TextureSheetAnimationModule_GetNumTilesY_m2021848348_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (TextureSheetAnimationModule_GetNumTilesY_m2021848348_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetNumTilesY(UnityEngine.ParticleSystem)");
int32_t retVal = _il2cpp_icall_func(___system0);
return retVal;
}
// UnityEngine.ParticleSystemAnimationType UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetAnimationType(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_GetAnimationType_m2914365387 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
typedef int32_t (*TextureSheetAnimationModule_GetAnimationType_m2914365387_ftn) (ParticleSystem_t1800779281 *);
static TextureSheetAnimationModule_GetAnimationType_m2914365387_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (TextureSheetAnimationModule_GetAnimationType_m2914365387_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetAnimationType(UnityEngine.ParticleSystem)");
int32_t retVal = _il2cpp_icall_func(___system0);
return retVal;
}
// System.Void UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetFrameOverTime(UnityEngine.ParticleSystem,UnityEngine.ParticleSystem/MinMaxCurve&)
extern "C" IL2CPP_METHOD_ATTR void TextureSheetAnimationModule_GetFrameOverTime_m371108956 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, MinMaxCurve_t1067599125 * ___curve1, const RuntimeMethod* method)
{
typedef void (*TextureSheetAnimationModule_GetFrameOverTime_m371108956_ftn) (ParticleSystem_t1800779281 *, MinMaxCurve_t1067599125 *);
static TextureSheetAnimationModule_GetFrameOverTime_m371108956_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (TextureSheetAnimationModule_GetFrameOverTime_m371108956_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetFrameOverTime(UnityEngine.ParticleSystem,UnityEngine.ParticleSystem/MinMaxCurve&)");
_il2cpp_icall_func(___system0, ___curve1);
}
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetCycleCount(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_GetCycleCount_m4232892544 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
typedef int32_t (*TextureSheetAnimationModule_GetCycleCount_m4232892544_ftn) (ParticleSystem_t1800779281 *);
static TextureSheetAnimationModule_GetCycleCount_m4232892544_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (TextureSheetAnimationModule_GetCycleCount_m4232892544_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetCycleCount(UnityEngine.ParticleSystem)");
int32_t retVal = _il2cpp_icall_func(___system0);
return retVal;
}
// System.Int32 UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetRowIndex(UnityEngine.ParticleSystem)
extern "C" IL2CPP_METHOD_ATTR int32_t TextureSheetAnimationModule_GetRowIndex_m3246918826 (RuntimeObject * __this /* static, unused */, ParticleSystem_t1800779281 * ___system0, const RuntimeMethod* method)
{
typedef int32_t (*TextureSheetAnimationModule_GetRowIndex_m3246918826_ftn) (ParticleSystem_t1800779281 *);
static TextureSheetAnimationModule_GetRowIndex_m3246918826_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (TextureSheetAnimationModule_GetRowIndex_m3246918826_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystem/TextureSheetAnimationModule::GetRowIndex(UnityEngine.ParticleSystem)");
int32_t retVal = _il2cpp_icall_func(___system0);
return retVal;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int32 UnityEngine.ParticleSystemRenderer::Internal_GetMeshCount()
extern "C" IL2CPP_METHOD_ATTR int32_t ParticleSystemRenderer_Internal_GetMeshCount_m2639012328 (ParticleSystemRenderer_t2065813411 * __this, const RuntimeMethod* method)
{
typedef int32_t (*ParticleSystemRenderer_Internal_GetMeshCount_m2639012328_ftn) (ParticleSystemRenderer_t2065813411 *);
static ParticleSystemRenderer_Internal_GetMeshCount_m2639012328_ftn _il2cpp_icall_func;
if (!_il2cpp_icall_func)
_il2cpp_icall_func = (ParticleSystemRenderer_Internal_GetMeshCount_m2639012328_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.ParticleSystemRenderer::Internal_GetMeshCount()");
int32_t retVal = _il2cpp_icall_func(__this);
return retVal;
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| 47.090504 | 284 | 0.834082 | [
"object"
] |
a1cd4b9f3ec46a78da2f90a2e0243b4a07be0853 | 9,570 | cpp | C++ | Data_Structures/splay_tree/splay_tree_beats.cpp | phibrainDK/Library_Templates | 88f34eb08de78a20828f8362d97da7dad3b28ced | [
"MIT"
] | null | null | null | Data_Structures/splay_tree/splay_tree_beats.cpp | phibrainDK/Library_Templates | 88f34eb08de78a20828f8362d97da7dad3b28ced | [
"MIT"
] | null | null | null | Data_Structures/splay_tree/splay_tree_beats.cpp | phibrainDK/Library_Templates | 88f34eb08de78a20828f8362d97da7dad3b28ced | [
"MIT"
] | null | null | null | // #################################################################################################
// # You told me #
// # At your absolute best, you still won't be good enough for the wrong person #
// # At your worst, you'll still be worth it to the right person #
// # It was good while it lasted, good bye #
// # I believe I really loved you... to that point that I always wanted to hear your voice #
// # But before my hand could reach you... you seem to be slowly disappearing from my sight #
// #################################################################################################
// #pragma GCC optimize ("Ofast,unroll-loops")
// #pragma GCC target ("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#include <bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#define pb push_back
#define ff first
#define ss second
#define tm1 first
#define tm2 second.first
#define tm3 second.second
#define sz(x) ll(x.size())
#define fill(x, v) memset(x, v, sizeof(x))
#define all(v) (v).begin(), (v).end()
#define FER(i,a,b) for(ll i=ll(a); i< ll(b); ++i)
#define IFR(i,a,b) for(ll i=ll(a); i>=ll(b); i-- )
#define fastio ios_base::sync_with_stdio(0); cin.tie(0)
// #define N 6800005
#define mod1 1000000007
// #define mod1 998244353
#define mod2 1000000009
#define bas 987625403
#define sqr(x) 1LL * (x) * (x)
#define INF (ll) 1e9
using namespace std;
using namespace __gnu_pbds;
typedef long long ll;
typedef pair<ll, ll> ii;
typedef pair<ii, ll> tri;
typedef vector<ll> vi;
typedef vector<ii> vii;
typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> S_t;
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
struct custom_Hash {
static uint64_t splitmix64(uint64_t x) {
x += 0x9e3779b97f4a7c15;
x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
return x ^ (x >> 31);
}
size_t operator()(uint64_t x) const {
static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
return splitmix64(x + FIXED_RANDOM);
}
};
#define trace(...) fff(#__VA_ARGS__, __VA_ARGS__)
template<typename t> void fff(const char* x, t&& val1) { cout << x << " : " << val1 << "\n";}
template<typename t1, typename... t2> void fff(const char* x, t1&& val1, t2&&... val2){
const char* xd = strchr(x + 1, ',');
cout.write(x, xd - x) << " : " <<val1 << " | ";
fff(xd + 1, val2...);
}
inline ll add(ll a, ll b, ll mod) { return a + b < mod? a + b : a + b - mod;}
inline ll rem(ll a, ll b, ll mod) { return a >= b ? a - b : a - b + mod;}
inline ll mul(ll a, ll b, ll mod) { return 1LL * a * b % mod;}
inline void Mul(ll &a, ll b, ll mod) { a = 1LL * a * b % mod;}
inline ll bp(ll a, long long p, ll mod){
ll ret;
for(ret = 1; p; p >>= 1, Mul(a, a, mod)) (p & 1) && (Mul(ret, a, mod), 1);
return ret;
}
static inline void read(ll &result) {
bool minus = false;
char ch;
ch = getchar();
while (true) {
if (ch == '-') break;
if (ch >= '0' and ch <= '9') break;
ch = getchar();
}
(ch == '-') ? minus = true: result = ch - '0';
while (true) {
ch = getchar();
if (ch < '0' or ch > '9') break;
result = (result << 3) + (result << 1) + (ch - '0');
}
if(minus) result = -result;
}
struct T{
ll val, ta, sum, fmx, smx, cmx;
bool t;
T(){}
T(ll val, ll ta, ll sum, bool t, ll fmx, ll smx, ll cmx) :
val(val), ta(ta), sum(sum), t(t), fmx(fmx), smx(smx), cmx(cmx){}
inline T Op(T a, T b){
if(a.fmx < b.fmx){
a.cmx = 0;
a.smx = a.fmx;
a.fmx = b.fmx;
}
if(a.fmx == b.fmx){
a.cmx += b.cmx;
a.smx = max(a.smx, b.smx);
}
else a.smx = max(a.smx, b.fmx);
a.sum += b.sum;
return a;
}
inline void Umin(ll x){
sum += (x - fmx) * cmx;
val = min(val, x);
fmx = x;
}
};
struct STB{
T nil;
vector<T> tree;
vi L, R, P, ar;
ll n, root;
inline void preprocess(){
nil = T(0, 0, 0, false, -INF, -INF, 0);
tree.pb(nil);
L.pb(0);
R.pb(0);
P.pb(0);
}
inline void updpro(T val, ll id){
if(val.fmx < tree[id].fmx){
tree[id].Umin(val.fmx);
}
}
inline void proh(ll id){
if(L[id]) updpro(tree[id], L[id]);
if(R[id]) updpro(tree[id], R[id]);
}
inline void upd(ll x){
ll idl = L[x], idr = R[x];
tree[x].ta = tree[idl].ta + tree[idr].ta + 1;
T cur = nil;
cur.fmx = tree[x].val;
cur.smx = -INF;
cur.cmx = 1;
cur.sum = tree[x].val;
if(R[x]) cur = cur.Op(cur, tree[R[x]]);
if(L[x]) cur = cur.Op(tree[L[x]], cur);
tree[x].fmx = cur.fmx;
tree[x].smx = cur.smx;
tree[x].cmx = cur.cmx;
tree[x].sum = cur.sum;
}
inline void push(ll id){
if(id == 0) return;
proh(id);
if(tree[id].t){
swap(L[id], R[id]);
tree[L[id]].t = !tree[L[id]].t;
tree[R[id]].t = !tree[R[id]].t;
tree[id].t = false;
}
}
inline void set(ll idx, ll idy, ll d){
if(!idx) {
P[idy] = idx;
return;
}
if(d == 0){
L[idx] = idy;
if(idy) P[idy] = idx;
}
else{
R[idx] = idy;
if(idy) P[idy] = idx;
}
}
inline ll get(ll idx, ll idy) { return L[idx] == idy? 0 : 1;}
inline void rot(ll x, ll d){
if(d == 0){
ll y = L[x], z = P[x];
set(x, R[y], d);
set(y, x, 1);
set(z, y, get(z, x));
upd(x), upd(y);
}
else{
ll y = R[x], z = P[x];
set(x, L[y], d);
set(y, x, 0);
set(z, y, get(z, x));
upd(x), upd(y);
}
}
inline void splay(ll x){
push(x);
while(P[x]){
ll y = P[x], z = P[y];
ll dy = get(y, x), dz = get(z, y);
if(!z) rot(y, dy);
else if(dy == dz) rot(z, dz), rot(y, dy);
else rot(y, dy), rot(z, dz);
}
upd(x);
}
inline ll getnode(ll x, ll pos){
while(push(x), tree[L[x]].ta != pos){
pos < tree[L[x]].ta? x = L[x] : (pos -= tree[L[x]].ta + 1, x = R[x]);
}
return splay(x), x;
}
inline ii split(ll x, ll l){
ll t1, t2;
if(!l) return ii{0, x};
else{
t1 = getnode(x, l - 1);
t2 = R[t1];
R[t1] = 0;
P[t1] = 0;
P[t2] = 0;
upd(t1);
return ii{t1, t2};
}
}
inline ll unir(ll x, ll y){
if(!y) return x;
if(!x) return y;
x = getnode(x, tree[x].ta - 1);
set(x, y, 1);
upd(x);
return x;
}
inline void UpdMinimo(ll id, ll val){
if(tree[id].fmx <= val) return;
if(tree[id].smx < val and tree[id].fmx > val){
tree[id].Umin(val);
return;
}
tree[id].val = min(tree[id].val, val);
proh(id);
if(L[id]) UpdMinimo(L[id], val);
if(R[id]) UpdMinimo(R[id], val);
upd(id);
return;
}
inline void UpdMin(ll l, ll r, ll val){
ll t1, t2, t3;
auto ret = split(root, r);
auto ket = split(ret.ff, l);
t1 = ket.ff, t2 = ket.ss, t3 = ret.ss;
UpdMinimo(t2, val);
root = unir(t1, unir(t2, t3));
}
inline ll que(ll l, ll r){
ll t1, t2, t3;
auto ret = split(root, r);
auto ket = split(ret.ff, l);
t1 = ket.ff, t2 = ket.ss, t3 = ret.ss;
ll ans = tree[t2].sum;
root = unir(unir(t1, t2), t3);
return ans;
}
inline void Delete(ll l, ll r){
ll t1, t2, t3;
auto ret = split(root, r);
auto ket = split(ret.ff, l);
t1 = ket.ff, t2 = ket.ss, t3 = ret.ss;
root = unir(t1, t3);
}
inline void Insert(ll p, ll val){
T cur = nil;
cur = T(val, 1, val, false, val, -INF, 1);
tree.pb(cur);
R.pb(0);
L.pb(0);
P.pb(0);
ll cur_id = sz(tree) - 1;
ll m = tree[root].ta;
if(m == p){
root = unir(root, cur_id);
return;
}
if(p == 0){
root = unir(cur_id, root);
return;
}
ll t1, t2;
auto ret = split(root, p);
t1 = ret.ff, t2 = ret.ss;
root = unir(t1, unir(cur_id, t2));
}
inline ll Build(ll l, ll r){
if(l == r) return 0;
ll mid = (l + r)>>1;
T x;
x = T(ar[mid], 1, ar[mid], false, ar[mid], -INF, 1);
tree.pb(x);
L.pb(0);
R.pb(0);
P.pb(0);
ll cur_id = sz(tree) - 1;
set(cur_id, Build(l, mid), 0);
set(cur_id, Build(mid + 1, r), 1);
upd(cur_id);
return cur_id;
}
inline void build(){
root = Build(0, n);
}
}st;
int main() {
fastio;
ll n, q; cin >> n >> q;
st.n = n;
FER(i, 0, n) cin >> st.ar[i];
st.preprocess();
st.build();
FER(i, 0, q) {
// answer queries
}
return 0;
} | 29 | 100 | 0.446708 | [
"vector"
] |
a1cf7fbcf16f2f6d58513a2a84e8e2c5a4483f8c | 7,152 | cpp | C++ | third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2020-09-15T08:43:34.000Z | 2020-09-15T08:43:34.000Z | third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/core/css/resolver/CSSVariableResolver.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "core/css/resolver/CSSVariableResolver.h"
#include "core/CSSPropertyNames.h"
#include "core/CSSValueKeywords.h"
#include "core/StyleBuilderFunctions.h"
#include "core/StylePropertyShorthand.h"
#include "core/css/CSSValuePool.h"
#include "core/css/CSSVariableData.h"
#include "core/css/CSSVariableReferenceValue.h"
#include "core/css/parser/CSSParserToken.h"
#include "core/css/parser/CSSParserTokenRange.h"
#include "core/css/parser/CSSPropertyParser.h"
#include "core/css/resolver/StyleBuilder.h"
#include "core/css/resolver/StyleResolverState.h"
#include "core/style/StyleVariableData.h"
#include "wtf/Vector.h"
namespace blink {
bool CSSVariableResolver::resolveFallback(CSSParserTokenRange range, Vector<CSSParserToken>& result)
{
if (range.atEnd())
return false;
ASSERT(range.peek().type() == CommaToken);
range.consume();
return resolveTokenRange(range, result);
}
CSSVariableData* CSSVariableResolver::valueForCustomProperty(AtomicString name)
{
if (m_variablesSeen.contains(name)) {
m_cycleStartPoints.add(name);
return nullptr;
}
if (!m_styleVariableData)
return nullptr;
CSSVariableData* variableData = m_styleVariableData->getVariable(name);
if (!variableData)
return nullptr;
if (!variableData->needsVariableResolution())
return variableData;
RefPtr<CSSVariableData> newVariableData = resolveCustomProperty(name, *variableData);
m_styleVariableData->setVariable(name, newVariableData);
return newVariableData.get();
}
PassRefPtr<CSSVariableData> CSSVariableResolver::resolveCustomProperty(AtomicString name, const CSSVariableData& variableData)
{
ASSERT(variableData.needsVariableResolution());
Vector<CSSParserToken> tokens;
m_variablesSeen.add(name);
bool success = resolveTokenRange(variableData.tokens(), tokens);
m_variablesSeen.remove(name);
// The old variable data holds onto the backing string the new resolved CSSVariableData
// relies on. Ensure it will live beyond us overwriting the RefPtr in StyleVariableData.
ASSERT(variableData.refCount() > 1);
if (!success || !m_cycleStartPoints.isEmpty()) {
m_cycleStartPoints.remove(name);
return nullptr;
}
return CSSVariableData::createResolved(tokens, variableData);
}
bool CSSVariableResolver::resolveVariableReference(CSSParserTokenRange range, Vector<CSSParserToken>& result)
{
range.consumeWhitespace();
ASSERT(range.peek().type() == IdentToken);
AtomicString variableName = range.consumeIncludingWhitespace().value();
ASSERT(range.atEnd() || (range.peek().type() == CommaToken));
CSSVariableData* variableData = valueForCustomProperty(variableName);
if (!variableData)
return resolveFallback(range, result);
result.appendVector(variableData->tokens());
Vector<CSSParserToken> trash;
resolveFallback(range, trash);
return true;
}
void CSSVariableResolver::resolveApplyAtRule(CSSParserTokenRange& range,
Vector<CSSParserToken>& result)
{
ASSERT(range.peek().type() == AtKeywordToken && range.peek().valueEqualsIgnoringASCIICase("apply"));
range.consumeIncludingWhitespace();
const CSSParserToken& variableName = range.consumeIncludingWhitespace();
// TODO(timloh): Should we actually be consuming this?
if (range.peek().type() == SemicolonToken)
range.consume();
CSSVariableData* variableData = valueForCustomProperty(variableName.value());
if (!variableData)
return; // Invalid custom property
CSSParserTokenRange rule = variableData->tokenRange();
rule.consumeWhitespace();
if (rule.peek().type() != LeftBraceToken)
return;
CSSParserTokenRange ruleContents = rule.consumeBlock();
rule.consumeWhitespace();
if (!rule.atEnd())
return;
result.appendRange(ruleContents.begin(), ruleContents.end());
}
bool CSSVariableResolver::resolveTokenRange(CSSParserTokenRange range,
Vector<CSSParserToken>& result)
{
bool success = true;
while (!range.atEnd()) {
if (range.peek().functionId() == CSSValueVar) {
success &= resolveVariableReference(range.consumeBlock(), result);
} else if (range.peek().type() == AtKeywordToken && range.peek().valueEqualsIgnoringASCIICase("apply")
&& RuntimeEnabledFeatures::cssApplyAtRulesEnabled()) {
resolveApplyAtRule(range, result);
} else {
result.append(range.consume());
}
}
return success;
}
CSSValue* CSSVariableResolver::resolveVariableReferences(StyleVariableData* styleVariableData, CSSPropertyID id, const CSSVariableReferenceValue& value)
{
ASSERT(!isShorthandProperty(id));
CSSVariableResolver resolver(styleVariableData);
Vector<CSSParserToken> tokens;
if (!resolver.resolveTokenRange(value.variableDataValue()->tokens(), tokens))
return cssValuePool().createUnsetValue();
CSSValue* result = CSSPropertyParser::parseSingleValue(id, tokens, strictCSSParserContext());
if (!result)
return cssValuePool().createUnsetValue();
return result;
}
void CSSVariableResolver::resolveAndApplyVariableReferences(StyleResolverState& state, CSSPropertyID id, const CSSVariableReferenceValue& value)
{
CSSVariableResolver resolver(state.style()->variables());
Vector<CSSParserToken> tokens;
if (resolver.resolveTokenRange(value.variableDataValue()->tokens(), tokens)) {
CSSParserContext context(HTMLStandardMode, 0);
HeapVector<CSSProperty, 256> parsedProperties;
// TODO: Non-shorthands should just call CSSPropertyParser::parseSingleValue
if (CSSPropertyParser::parseValue(id, false, CSSParserTokenRange(tokens), context, parsedProperties, StyleRule::RuleType::Style)) {
unsigned parsedPropertiesCount = parsedProperties.size();
for (unsigned i = 0; i < parsedPropertiesCount; ++i)
StyleBuilder::applyProperty(parsedProperties[i].id(), state, parsedProperties[i].value());
return;
}
}
CSSUnsetValue* unset = cssValuePool().createUnsetValue();
if (isShorthandProperty(id)) {
StylePropertyShorthand shorthand = shorthandForProperty(id);
for (unsigned i = 0; i < shorthand.length(); i++)
StyleBuilder::applyProperty(shorthand.properties()[i], state, unset);
return;
}
StyleBuilder::applyProperty(id, state, unset);
}
void CSSVariableResolver::resolveVariableDefinitions(StyleVariableData* variables)
{
if (!variables)
return;
CSSVariableResolver resolver(variables);
for (auto& variable : variables->m_data) {
if (variable.value && variable.value->needsVariableResolution())
variable.value = resolver.resolveCustomProperty(variable.key, *variable.value);
}
}
CSSVariableResolver::CSSVariableResolver(StyleVariableData* styleVariableData)
: m_styleVariableData(styleVariableData)
{
}
} // namespace blink
| 36.865979 | 152 | 0.723294 | [
"vector"
] |
a1d081d4b4401853dc6665b0056e8a64087a6029 | 4,934 | cxx | C++ | scipy/spatial/ckdtree/src/query_ball_point.cxx | xu-hong-/scipy | f737001cf0a75654efe09a1de5cdf5d1895bda59 | [
"BSD-3-Clause"
] | 6,989 | 2017-07-18T06:23:18.000Z | 2022-03-31T15:58:36.000Z | scipy/spatial/ckdtree/src/query_ball_point.cxx | xu-hong-/scipy | f737001cf0a75654efe09a1de5cdf5d1895bda59 | [
"BSD-3-Clause"
] | 1,978 | 2017-07-18T09:17:58.000Z | 2022-03-31T14:28:43.000Z | scipy/spatial/ckdtree/src/query_ball_point.cxx | xu-hong-/scipy | f737001cf0a75654efe09a1de5cdf5d1895bda59 | [
"BSD-3-Clause"
] | 1,228 | 2017-07-18T09:03:13.000Z | 2022-03-29T05:57:40.000Z | #include <Python.h>
#include "numpy/arrayobject.h"
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <string>
#include <sstream>
#include <new>
#include <typeinfo>
#include <stdexcept>
#include <ios>
#define CKDTREE_METHODS_IMPL
#include "ckdtree_decl.h"
#include "ckdtree_methods.h"
#include "cpp_exc.h"
#include "rectangle.h"
static void
traverse_no_checking(const ckdtree *self,
std::vector<npy_intp> *results,
const ckdtreenode *node)
{
const npy_intp *indices = self->raw_indices;
const ckdtreenode *lnode;
npy_intp i;
if (node->split_dim == -1) { /* leaf node */
lnode = node;
const npy_intp start = lnode->start_idx;
const npy_intp end = lnode->end_idx;
for (i = start; i < end; ++i)
results->push_back(indices[i]);
}
else {
traverse_no_checking(self, results, node->less);
traverse_no_checking(self, results, node->greater);
}
}
template <typename MinMaxDist> static void
traverse_checking(const ckdtree *self,
std::vector<npy_intp> *results,
const ckdtreenode *node,
RectRectDistanceTracker<MinMaxDist> *tracker)
{
const ckdtreenode *lnode;
npy_float64 d;
npy_intp i;
if (tracker->min_distance > tracker->upper_bound * tracker->epsfac)
return;
else if (tracker->max_distance < tracker->upper_bound / tracker->epsfac)
traverse_no_checking(self, results, node);
else if (node->split_dim == -1) { /* leaf node */
/* brute-force */
lnode = node;
const npy_float64 p = tracker->p;
const npy_float64 tub = tracker->upper_bound;
const npy_float64 *tpt = tracker->rect1.mins;
const npy_float64 *data = self->raw_data;
const npy_intp *indices = self->raw_indices;
const npy_intp m = self->m;
const npy_intp start = lnode->start_idx;
const npy_intp end = lnode->end_idx;
prefetch_datapoint(data + indices[start] * m, m);
if (start < end)
prefetch_datapoint(data + indices[start+1] * m, m);
for (i = start; i < end; ++i) {
if (i < end-2)
prefetch_datapoint(data + indices[i+2] * m, m);
d = MinMaxDist::distance_p(self, data + indices[i] * m, tpt, p, m, tub);
if (d <= tub) {
results->push_back((npy_intp) indices[i]);
}
}
}
else {
tracker->push_less_of(2, node);
traverse_checking(self, results, node->less, tracker);
tracker->pop();
tracker->push_greater_of(2, node);
traverse_checking(self, results, node->greater, tracker);
tracker->pop();
}
}
extern "C" PyObject*
query_ball_point(const ckdtree *self, const npy_float64 *x,
const npy_float64 r, const npy_float64 p, const npy_float64 eps,
const npy_intp n_queries, std::vector<npy_intp> **results)
{
#define HANDLE(cond, kls) \
if(cond) { \
RectRectDistanceTracker<kls> tracker(self, point, rect, p, eps, r); \
traverse_checking(self, results[i], self->ctree, &tracker); \
} else
/* release the GIL */
NPY_BEGIN_ALLOW_THREADS
{
try {
for (npy_intp i=0; i < n_queries; ++i) {
const npy_intp m = self->m;
Rectangle rect(m, self->raw_mins, self->raw_maxes);
if (NPY_LIKELY(self->raw_boxsize_data == NULL)) {
Rectangle point(m, x + i * m, x + i * m);
HANDLE(NPY_LIKELY(p == 2), MinkowskiDistP2)
HANDLE(p == 1, MinkowskiDistP1)
HANDLE(ckdtree_isinf(p), MinkowskiDistPinf)
HANDLE(1, MinkowskiDistPp)
{}
} else {
Rectangle point(m, x + i * m, x + i * m);
int j;
for(j=0; j<m; ++j) {
point.maxes[j] = point.mins[j] = _wrap(point.mins[j], self->raw_boxsize_data[j]);
}
HANDLE(NPY_LIKELY(p == 2), BoxMinkowskiDistP2)
HANDLE(p == 1, BoxMinkowskiDistP1)
HANDLE(ckdtree_isinf(p), BoxMinkowskiDistPinf)
HANDLE(1, BoxMinkowskiDistPp)
{}
}
}
}
catch(...) {
translate_cpp_exception_with_gil();
}
}
/* reacquire the GIL */
NPY_END_ALLOW_THREADS
if (PyErr_Occurred())
/* true if a C++ exception was translated */
return NULL;
else {
/* return None if there were no errors */
Py_RETURN_NONE;
}
}
| 31.832258 | 105 | 0.534657 | [
"vector"
] |
a1dd42e6f53dfb2b27ad37961ef0eb4042ff9a47 | 6,691 | cpp | C++ | Bull-Engine/Primitive.cpp | Sersius/Bull-Engine | d97c7ed4725eb9bef776ffbe9e5a13bed200cfd0 | [
"MIT"
] | null | null | null | Bull-Engine/Primitive.cpp | Sersius/Bull-Engine | d97c7ed4725eb9bef776ffbe9e5a13bed200cfd0 | [
"MIT"
] | null | null | null | Bull-Engine/Primitive.cpp | Sersius/Bull-Engine | d97c7ed4725eb9bef776ffbe9e5a13bed200cfd0 | [
"MIT"
] | null | null | null |
#include "Globals.h"
#include "Primitive.h"
#include "Glew/include/glew.h"
#include <gl/GL.h>
#include <gl/GLU.h>
// ------------------------------------------------------------
Primitive::Primitive() : transform(IdentityMatrix), color(White), wire(false), axis(false), type(PrimitiveTypes::Primitive_Point)
{}
// ------------------------------------------------------------
PrimitiveTypes Primitive::GetType() const
{
return type;
}
// ------------------------------------------------------------
void Primitive::Render() const
{
glPushMatrix();
glMultMatrixf(transform.M);
if(axis == true)
{
// Draw Axis Grid
glLineWidth(2.0f);
glBegin(GL_LINES);
glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(1.0f, 0.0f, 0.0f);
glVertex3f(1.0f, 0.1f, 0.0f); glVertex3f(1.1f, -0.1f, 0.0f);
glVertex3f(1.1f, 0.1f, 0.0f); glVertex3f(1.0f, -0.1f, 0.0f);
glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 1.0f, 0.0f);
glVertex3f(-0.05f, 1.25f, 0.0f); glVertex3f(0.0f, 1.15f, 0.0f);
glVertex3f(0.05f, 1.25f, 0.0f); glVertex3f(0.0f, 1.15f, 0.0f);
glVertex3f(0.0f, 1.15f, 0.0f); glVertex3f(0.0f, 1.05f, 0.0f);
glColor4f(0.0f, 0.0f, 1.0f, 1.0f);
glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f);
glVertex3f(-0.05f, 0.1f, 1.05f); glVertex3f(0.05f, 0.1f, 1.05f);
glVertex3f(0.05f, 0.1f, 1.05f); glVertex3f(-0.05f, -0.1f, 1.05f);
glVertex3f(-0.05f, -0.1f, 1.05f); glVertex3f(0.05f, -0.1f, 1.05f);
glEnd();
glLineWidth(1.0f);
}
glColor3f(color.r, color.g, color.b);
if(wire)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
InnerRender();
glPopMatrix();
}
// ------------------------------------------------------------
void Primitive::InnerRender() const
{
glPointSize(5.0f);
glBegin(GL_POINTS);
glVertex3f(0.0f, 0.0f, 0.0f);
glEnd();
glPointSize(1.0f);
}
// ------------------------------------------------------------
void Primitive::SetPos(float x, float y, float z)
{
transform.translate(x, y, z);
}
// ------------------------------------------------------------
void Primitive::SetRotation(float angle, const vec3 &u)
{
transform.rotate(angle, u);
}
// ------------------------------------------------------------
void Primitive::Scale(float x, float y, float z)
{
transform.scale(x, y, z);
}
// CUBE ============================================
Cube::Cube() : Primitive(), size(1.0f, 1.0f, 1.0f)
{
type = PrimitiveTypes::Primitive_Cube;
}
Cube::Cube(float sizeX, float sizeY, float sizeZ) : Primitive(), size(sizeX, sizeY, sizeZ)
{
type = PrimitiveTypes::Primitive_Cube;
float sx = size.x;
float sy = size.y;
float sz = size.z;
vertex = new float[72]{ sx, sy, sz, -sx, sy, sz, -sx, -sy, sz, sx, -sy, sz, // FRONT
sx, sy, sz, sx, -sy, sz, sx, -sy, -sz, sx, sy, -sz, // TOP
sx, sy, sz, sx, sy, -sz, -sx, sy, -sz, -sx, sy, sz, // RIGHT
-sx, sy, sz, -sx, sy, -sz, -sx, -sy, -sz, -sx, -sy, sz, // LEFT
-sx, -sy, -sz, sx, -sy, -sz, sx, -sy, sz, -sx, -sy, sz, // BOTTOM
sx, -sy, -sz, -sx, -sy, -sz, -sx, sy, -sz, sx, sy, -sz // BACK
};
glGenBuffers(1, (GLuint*) &(my_id));
glBindBuffer(GL_ARRAY_BUFFER, my_id);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 72, vertex, GL_STATIC_DRAW);
indices = new uint[36]{ 0, 1, 2, 2, 3, 0, // FRONT
4, 5, 6, 6, 7, 4, // TOP
8, 9, 10, 10,11,8, // RIGHT
12,13,14, 14,15,12, // LEFT
16,17,18, 18,19,16, // BOTTOM
20,21,22, 22,23,20 // BACK
};
glGenBuffers(1, (GLuint*) &(my_indices));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, my_indices);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(uint) * 36, indices, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void Cube::InnerRender() const
{
glEnableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, my_id);
glVertexPointer(3, GL_FLOAT, 0, NULL);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, my_indices);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, NULL);
glDisableClientState(GL_VERTEX_ARRAY);
}
// SPHERE ============================================
//Sphere::Sphere() : Primitive(), radius(1.0f)
//{
// type = PrimitiveTypes::Primitive_Sphere;
//}
//
//Sphere::Sphere(float radius) : Primitive(), radius(radius)
//{
// type = PrimitiveTypes::Primitive_Sphere;
//}
//
//void Sphere::InnerRender() const
//{
// //glutSolidSphere(radius, 25, 25);
//}
// CYLINDER ============================================
Cylinder::Cylinder() : Primitive(), radius(1.0f), height(1.0f)
{
type = PrimitiveTypes::Primitive_Cylinder;
}
Cylinder::Cylinder(float radius, float height) : Primitive(), radius(radius), height(height)
{
type = PrimitiveTypes::Primitive_Cylinder;
}
void Cylinder::InnerRender() const
{
int n = 30;
// Cylinder Bottom
glBegin(GL_POLYGON);
for(int i = 360; i >= 0; i -= (360 / n))
{
float a = i * M_PI / 180; // degrees to radians
glVertex3f(-height*0.5f, radius * cos(a), radius * sin(a));
}
glEnd();
// Cylinder Top
glBegin(GL_POLYGON);
glNormal3f(0.0f, 0.0f, 1.0f);
for(int i = 0; i <= 360; i += (360 / n))
{
float a = i * M_PI / 180; // degrees to radians
glVertex3f(height * 0.5f, radius * cos(a), radius * sin(a));
}
glEnd();
// Cylinder "Cover"
glBegin(GL_QUAD_STRIP);
for(int i = 0; i < 480; i += (360 / n))
{
float a = i * M_PI / 180; // degrees to radians
glVertex3f(height*0.5f, radius * cos(a), radius * sin(a) );
glVertex3f(-height*0.5f, radius * cos(a), radius * sin(a) );
}
glEnd();
}
// LINE ==================================================
Line::Line() : Primitive(), origin(0, 0, 0), destination(1, 1, 1)
{
type = PrimitiveTypes::Primitive_Line;
}
Line::Line(float x, float y, float z) : Primitive(), origin(0, 0, 0), destination(x, y, z)
{
type = PrimitiveTypes::Primitive_Line;
}
void Line::InnerRender() const
{
glLineWidth(2.0f);
glBegin(GL_LINES);
glVertex3f(origin.x, origin.y, origin.z);
glVertex3f(destination.x, destination.y, destination.z);
glEnd();
glLineWidth(1.0f);
}
// PLANE ==================================================
PlaneG::PlaneG() : Primitive(), normal(0, 1, 0), constant(1)
{
type = PrimitiveTypes::Primitive_Plane;
}
PlaneG::PlaneG(float x, float y, float z, float d) : Primitive(), normal(x, y, z), constant(d)
{
type = PrimitiveTypes::Primitive_Plane;
}
void PlaneG::InnerRender() const
{
glLineWidth(1.0f);
glBegin(GL_LINES);
float d = 200.0f;
for(float i = -d; i <= d; i += 1.0f)
{
glVertex3f(i, 0.0f, -d);
glVertex3f(i, 0.0f, d);
glVertex3f(-d, 0.0f, i);
glVertex3f(d, 0.0f, i);
}
glEnd();
} | 24.330909 | 129 | 0.564191 | [
"render",
"transform"
] |
a1de3d7894f6cb22cd2957c769b1deb0e6a1451c | 92,149 | cc | C++ | storage/innobase/row/row0ins.cc | hervewenjie/mysql | 49a37eda4e2cc87e20ba99e2c29ffac2fc322359 | [
"BSD-3-Clause"
] | null | null | null | storage/innobase/row/row0ins.cc | hervewenjie/mysql | 49a37eda4e2cc87e20ba99e2c29ffac2fc322359 | [
"BSD-3-Clause"
] | null | null | null | storage/innobase/row/row0ins.cc | hervewenjie/mysql | 49a37eda4e2cc87e20ba99e2c29ffac2fc322359 | [
"BSD-3-Clause"
] | null | null | null | /*****************************************************************************
Copyright (c) 1996, 2014, Oracle and/or its affiliates. All Rights Reserved.
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA
*****************************************************************************/
/**************************************************//**
@file row/row0ins.cc
Insert into a table
Created 4/20/1996 Heikki Tuuri
*******************************************************/
#include "row0ins.h"
#ifdef UNIV_NONINL
#include "row0ins.ic"
#endif
#include "ha_prototypes.h"
#include "dict0dict.h"
#include "dict0boot.h"
#include "trx0rec.h"
#include "trx0undo.h"
#include "btr0btr.h"
#include "btr0cur.h"
#include "mach0data.h"
#include "que0que.h"
#include "row0upd.h"
#include "row0sel.h"
#include "row0row.h"
#include "row0log.h"
#include "rem0cmp.h"
#include "lock0lock.h"
#include "log0log.h"
#include "eval0eval.h"
#include "data0data.h"
#include "usr0sess.h"
#include "buf0lru.h"
#include "fts0fts.h"
#include "fts0types.h"
#include "m_string.h"
/*************************************************************************
IMPORTANT NOTE: Any operation that generates redo MUST check that there
is enough space in the redo log before for that operation. This is
done by calling log_free_check(). The reason for checking the
availability of the redo log space before the start of the operation is
that we MUST not hold any synchonization objects when performing the
check.
If you make a change in this module make sure that no codepath is
introduced where a call to log_free_check() is bypassed. */
/*********************************************************************//**
Creates an insert node struct.
@return own: insert node struct */
UNIV_INTERN
ins_node_t*
ins_node_create(
/*============*/
ulint ins_type, /*!< in: INS_VALUES, ... */
dict_table_t* table, /*!< in: table where to insert */
mem_heap_t* heap) /*!< in: mem heap where created */
{
ins_node_t* node;
node = static_cast<ins_node_t*>(
mem_heap_alloc(heap, sizeof(ins_node_t)));
node->common.type = QUE_NODE_INSERT;
node->ins_type = ins_type;
node->state = INS_NODE_SET_IX_LOCK;
node->table = table;
node->index = NULL;
node->entry = NULL;
node->select = NULL;
node->trx_id = 0;
node->entry_sys_heap = mem_heap_create(128);
node->magic_n = INS_NODE_MAGIC_N;
return(node);
}
/***********************************************************//**
Creates an entry template for each index of a table. */
static
void
ins_node_create_entry_list(
/*=======================*/
ins_node_t* node) /*!< in: row insert node */
{
dict_index_t* index;
dtuple_t* entry;
ut_ad(node->entry_sys_heap);
UT_LIST_INIT(node->entry_list);
/* We will include all indexes (include those corrupted
secondary indexes) in the entry list. Filteration of
these corrupted index will be done in row_ins() */
for (index = dict_table_get_first_index(node->table);
index != 0;
index = dict_table_get_next_index(index)) {
entry = row_build_index_entry(
node->row, NULL, index, node->entry_sys_heap);
UT_LIST_ADD_LAST(tuple_list, node->entry_list, entry);
}
}
/*****************************************************************//**
Adds system field buffers to a row. */
static
void
row_ins_alloc_sys_fields(
/*=====================*/
ins_node_t* node) /*!< in: insert node */
{
dtuple_t* row;
dict_table_t* table;
mem_heap_t* heap;
const dict_col_t* col;
dfield_t* dfield;
byte* ptr;
row = node->row;
table = node->table;
heap = node->entry_sys_heap;
ut_ad(row && table && heap);
ut_ad(dtuple_get_n_fields(row) == dict_table_get_n_cols(table));
/* allocate buffer to hold the needed system created hidden columns. */
uint len = DATA_ROW_ID_LEN + DATA_TRX_ID_LEN + DATA_ROLL_PTR_LEN;
ptr = static_cast<byte*>(mem_heap_zalloc(heap, len));
/* 1. Populate row-id */
col = dict_table_get_sys_col(table, DATA_ROW_ID);
dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
dfield_set_data(dfield, ptr, DATA_ROW_ID_LEN);
node->row_id_buf = ptr;
ptr += DATA_ROW_ID_LEN;
/* 2. Populate trx id */
col = dict_table_get_sys_col(table, DATA_TRX_ID);
dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
dfield_set_data(dfield, ptr, DATA_TRX_ID_LEN);
node->trx_id_buf = ptr;
ptr += DATA_TRX_ID_LEN;
/* 3. Populate roll ptr */
col = dict_table_get_sys_col(table, DATA_ROLL_PTR);
dfield = dtuple_get_nth_field(row, dict_col_get_no(col));
dfield_set_data(dfield, ptr, DATA_ROLL_PTR_LEN);
}
/*********************************************************************//**
Sets a new row to insert for an INS_DIRECT node. This function is only used
if we have constructed the row separately, which is a rare case; this
function is quite slow. */
UNIV_INTERN
void
ins_node_set_new_row(
/*=================*/
ins_node_t* node, /*!< in: insert node */
dtuple_t* row) /*!< in: new row (or first row) for the node */
{
node->state = INS_NODE_SET_IX_LOCK;
node->index = NULL;
node->entry = NULL;
node->row = row;
mem_heap_empty(node->entry_sys_heap);
/* Create templates for index entries */
ins_node_create_entry_list(node);
/* Allocate from entry_sys_heap buffers for sys fields */
row_ins_alloc_sys_fields(node);
/* As we allocated a new trx id buf, the trx id should be written
there again: */
node->trx_id = 0;
}
/*******************************************************************//**
Does an insert operation by updating a delete-marked existing record
in the index. This situation can occur if the delete-marked record is
kept in the index for consistent reads.
@return DB_SUCCESS or error code */
static __attribute__((nonnull, warn_unused_result))
dberr_t
row_ins_sec_index_entry_by_modify(
/*==============================*/
ulint flags, /*!< in: undo logging and locking flags */
ulint mode, /*!< in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
depending on whether mtr holds just a leaf
latch or also a tree latch */
btr_cur_t* cursor, /*!< in: B-tree cursor */
ulint** offsets,/*!< in/out: offsets on cursor->page_cur.rec */
mem_heap_t* offsets_heap,
/*!< in/out: memory heap that can be emptied */
mem_heap_t* heap, /*!< in/out: memory heap */
const dtuple_t* entry, /*!< in: index entry to insert */
que_thr_t* thr, /*!< in: query thread */
mtr_t* mtr) /*!< in: mtr; must be committed before
latching any further pages */
{
big_rec_t* dummy_big_rec;
upd_t* update;
rec_t* rec;
dberr_t err;
rec = btr_cur_get_rec(cursor);
ut_ad(!dict_index_is_clust(cursor->index));
ut_ad(rec_offs_validate(rec, cursor->index, *offsets));
ut_ad(!entry->info_bits);
/* We know that in the alphabetical ordering, entry and rec are
identified. But in their binary form there may be differences if
there are char fields in them. Therefore we have to calculate the
difference. */
update = row_upd_build_sec_rec_difference_binary(
rec, cursor->index, *offsets, entry, heap);
if (!rec_get_deleted_flag(rec, rec_offs_comp(*offsets))) {
/* We should never insert in place of a record that
has not been delete-marked. The only exception is when
online CREATE INDEX copied the changes that we already
made to the clustered index, and completed the
secondary index creation before we got here. In this
case, the change would already be there. The CREATE
INDEX should be waiting for a MySQL meta-data lock
upgrade at least until this INSERT or UPDATE
returns. After that point, the TEMP_INDEX_PREFIX
would be dropped from the index name in
commit_inplace_alter_table(). */
ut_a(update->n_fields == 0);
ut_a(*cursor->index->name == TEMP_INDEX_PREFIX);
ut_ad(!dict_index_is_online_ddl(cursor->index));
return(DB_SUCCESS);
}
if (mode == BTR_MODIFY_LEAF) {
/* Try an optimistic updating of the record, keeping changes
within the page */
/* TODO: pass only *offsets */
err = btr_cur_optimistic_update(
flags | BTR_KEEP_SYS_FLAG, cursor,
offsets, &offsets_heap, update, 0, thr,
thr_get_trx(thr)->id, mtr);
switch (err) {
case DB_OVERFLOW:
case DB_UNDERFLOW:
case DB_ZIP_OVERFLOW:
err = DB_FAIL;
default:
break;
}
} else {
ut_a(mode == BTR_MODIFY_TREE);
if (buf_LRU_buf_pool_running_out()) {
return(DB_LOCK_TABLE_FULL);
}
err = btr_cur_pessimistic_update(
flags | BTR_KEEP_SYS_FLAG, cursor,
offsets, &offsets_heap,
heap, &dummy_big_rec, update, 0,
thr, thr_get_trx(thr)->id, mtr);
ut_ad(!dummy_big_rec);
}
return(err);
}
/*******************************************************************//**
Does an insert operation by delete unmarking and updating a delete marked
existing record in the index. This situation can occur if the delete marked
record is kept in the index for consistent reads.
@return DB_SUCCESS, DB_FAIL, or error code */
static __attribute__((nonnull, warn_unused_result))
dberr_t
row_ins_clust_index_entry_by_modify(
/*================================*/
ulint flags, /*!< in: undo logging and locking flags */
ulint mode, /*!< in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
depending on whether mtr holds just a leaf
latch or also a tree latch */
btr_cur_t* cursor, /*!< in: B-tree cursor */
ulint** offsets,/*!< out: offsets on cursor->page_cur.rec */
mem_heap_t** offsets_heap,
/*!< in/out: pointer to memory heap that can
be emptied, or NULL */
mem_heap_t* heap, /*!< in/out: memory heap */
big_rec_t** big_rec,/*!< out: possible big rec vector of fields
which have to be stored externally by the
caller */
const dtuple_t* entry, /*!< in: index entry to insert */
que_thr_t* thr, /*!< in: query thread */
mtr_t* mtr) /*!< in: mtr; must be committed before
latching any further pages */
{
const rec_t* rec;
const upd_t* update;
dberr_t err;
ut_ad(dict_index_is_clust(cursor->index));
*big_rec = NULL;
rec = btr_cur_get_rec(cursor);
ut_ad(rec_get_deleted_flag(rec,
dict_table_is_comp(cursor->index->table)));
/* Build an update vector containing all the fields to be modified;
NOTE that this vector may NOT contain system columns trx_id or
roll_ptr */
update = row_upd_build_difference_binary(
cursor->index, entry, rec, NULL, true,
thr_get_trx(thr), heap);
if (mode != BTR_MODIFY_TREE) {
ut_ad((mode & ~BTR_ALREADY_S_LATCHED) == BTR_MODIFY_LEAF);
/* Try optimistic updating of the record, keeping changes
within the page */
err = btr_cur_optimistic_update(
flags, cursor, offsets, offsets_heap, update, 0, thr,
thr_get_trx(thr)->id, mtr);
switch (err) {
case DB_OVERFLOW:
case DB_UNDERFLOW:
case DB_ZIP_OVERFLOW:
err = DB_FAIL;
default:
break;
}
} else {
if (buf_LRU_buf_pool_running_out()) {
return(DB_LOCK_TABLE_FULL);
}
err = btr_cur_pessimistic_update(
flags | BTR_KEEP_POS_FLAG,
cursor, offsets, offsets_heap, heap,
big_rec, update, 0, thr, thr_get_trx(thr)->id, mtr);
}
return(err);
}
/*********************************************************************//**
Returns TRUE if in a cascaded update/delete an ancestor node of node
updates (not DELETE, but UPDATE) table.
@return TRUE if an ancestor updates table */
static
ibool
row_ins_cascade_ancestor_updates_table(
/*===================================*/
que_node_t* node, /*!< in: node in a query graph */
dict_table_t* table) /*!< in: table */
{
que_node_t* parent;
for (parent = que_node_get_parent(node);
que_node_get_type(parent) == QUE_NODE_UPDATE;
parent = que_node_get_parent(parent)) {
upd_node_t* upd_node;
upd_node = static_cast<upd_node_t*>(parent);
if (upd_node->table == table && upd_node->is_delete == FALSE) {
return(TRUE);
}
}
return(FALSE);
}
/*********************************************************************//**
Returns the number of ancestor UPDATE or DELETE nodes of a
cascaded update/delete node.
@return number of ancestors */
static __attribute__((nonnull, warn_unused_result))
ulint
row_ins_cascade_n_ancestors(
/*========================*/
que_node_t* node) /*!< in: node in a query graph */
{
que_node_t* parent;
ulint n_ancestors = 0;
for (parent = que_node_get_parent(node);
que_node_get_type(parent) == QUE_NODE_UPDATE;
parent = que_node_get_parent(parent)) {
n_ancestors++;
}
return(n_ancestors);
}
/******************************************************************//**
Calculates the update vector node->cascade->update for a child table in
a cascaded update.
@return number of fields in the calculated update vector; the value
can also be 0 if no foreign key fields changed; the returned value is
ULINT_UNDEFINED if the column type in the child table is too short to
fit the new value in the parent table: that means the update fails */
static __attribute__((nonnull, warn_unused_result))
ulint
row_ins_cascade_calc_update_vec(
/*============================*/
upd_node_t* node, /*!< in: update node of the parent
table */
dict_foreign_t* foreign, /*!< in: foreign key constraint whose
type is != 0 */
mem_heap_t* heap, /*!< in: memory heap to use as
temporary storage */
trx_t* trx, /*!< in: update transaction */
ibool* fts_col_affected)/*!< out: is FTS column affected */
{
upd_node_t* cascade = node->cascade_node;
dict_table_t* table = foreign->foreign_table;
dict_index_t* index = foreign->foreign_index;
upd_t* update;
dict_table_t* parent_table;
dict_index_t* parent_index;
upd_t* parent_update;
ulint n_fields_updated;
ulint parent_field_no;
ulint i;
ulint j;
ibool doc_id_updated = FALSE;
ulint doc_id_pos = 0;
doc_id_t new_doc_id = FTS_NULL_DOC_ID;
ut_a(node);
ut_a(foreign);
ut_a(cascade);
ut_a(table);
ut_a(index);
/* Calculate the appropriate update vector which will set the fields
in the child index record to the same value (possibly padded with
spaces if the column is a fixed length CHAR or FIXBINARY column) as
the referenced index record will get in the update. */
parent_table = node->table;
ut_a(parent_table == foreign->referenced_table);
parent_index = foreign->referenced_index;
parent_update = node->update;
update = cascade->update;
update->info_bits = 0;
update->n_fields = foreign->n_fields;
n_fields_updated = 0;
*fts_col_affected = FALSE;
if (table->fts) {
doc_id_pos = dict_table_get_nth_col_pos(
table, table->fts->doc_col);
}
for (i = 0; i < foreign->n_fields; i++) {
parent_field_no = dict_table_get_nth_col_pos(
parent_table,
dict_index_get_nth_col_no(parent_index, i));
for (j = 0; j < parent_update->n_fields; j++) {
const upd_field_t* parent_ufield
= &parent_update->fields[j];
if (parent_ufield->field_no == parent_field_no) {
ulint min_size;
const dict_col_t* col;
ulint ufield_len;
upd_field_t* ufield;
col = dict_index_get_nth_col(index, i);
/* A field in the parent index record is
updated. Let us make the update vector
field for the child table. */
ufield = update->fields + n_fields_updated;
ufield->field_no
= dict_table_get_nth_col_pos(
table, dict_col_get_no(col));
ufield->orig_len = 0;
ufield->exp = NULL;
ufield->new_val = parent_ufield->new_val;
ufield_len = dfield_get_len(&ufield->new_val);
/* Clear the "external storage" flag */
dfield_set_len(&ufield->new_val, ufield_len);
/* Do not allow a NOT NULL column to be
updated as NULL */
if (dfield_is_null(&ufield->new_val)
&& (col->prtype & DATA_NOT_NULL)) {
return(ULINT_UNDEFINED);
}
/* If the new value would not fit in the
column, do not allow the update */
if (!dfield_is_null(&ufield->new_val)
&& dtype_get_at_most_n_mbchars(
col->prtype, col->mbminmaxlen,
col->len,
ufield_len,
static_cast<char*>(
dfield_get_data(
&ufield->new_val)))
< ufield_len) {
return(ULINT_UNDEFINED);
}
/* If the parent column type has a different
length than the child column type, we may
need to pad with spaces the new value of the
child column */
min_size = dict_col_get_min_size(col);
/* Because UNIV_SQL_NULL (the marker
of SQL NULL values) exceeds all possible
values of min_size, the test below will
not hold for SQL NULL columns. */
if (min_size > ufield_len) {
byte* pad;
ulint pad_len;
byte* padded_data;
ulint mbminlen;
padded_data = static_cast<byte*>(
mem_heap_alloc(
heap, min_size));
pad = padded_data + ufield_len;
pad_len = min_size - ufield_len;
memcpy(padded_data,
dfield_get_data(&ufield
->new_val),
ufield_len);
mbminlen = dict_col_get_mbminlen(col);
ut_ad(!(ufield_len % mbminlen));
ut_ad(!(min_size % mbminlen));
if (mbminlen == 1
&& dtype_get_charset_coll(
col->prtype)
== DATA_MYSQL_BINARY_CHARSET_COLL) {
/* Do not pad BINARY columns */
return(ULINT_UNDEFINED);
}
row_mysql_pad_col(mbminlen,
pad, pad_len);
dfield_set_data(&ufield->new_val,
padded_data, min_size);
}
/* Check whether the current column has
FTS index on it */
if (table->fts
&& dict_table_is_fts_column(
table->fts->indexes,
dict_col_get_no(col))
!= ULINT_UNDEFINED) {
*fts_col_affected = TRUE;
}
/* If Doc ID is updated, check whether the
Doc ID is valid */
if (table->fts
&& ufield->field_no == doc_id_pos) {
doc_id_t n_doc_id;
n_doc_id =
table->fts->cache->next_doc_id;
new_doc_id = fts_read_doc_id(
static_cast<const byte*>(
dfield_get_data(
&ufield->new_val)));
if (new_doc_id <= 0) {
fprintf(stderr,
"InnoDB: FTS Doc ID "
"must be larger than "
"0 \n");
return(ULINT_UNDEFINED);
}
if (new_doc_id < n_doc_id) {
fprintf(stderr,
"InnoDB: FTS Doc ID "
"must be larger than "
IB_ID_FMT" for table",
n_doc_id -1);
ut_print_name(stderr, trx,
TRUE,
table->name);
putc('\n', stderr);
return(ULINT_UNDEFINED);
}
*fts_col_affected = TRUE;
doc_id_updated = TRUE;
}
n_fields_updated++;
}
}
}
/* Generate a new Doc ID if FTS index columns get updated */
if (table->fts && *fts_col_affected) {
if (DICT_TF2_FLAG_IS_SET(table, DICT_TF2_FTS_HAS_DOC_ID)) {
doc_id_t doc_id;
upd_field_t* ufield;
ut_ad(!doc_id_updated);
ufield = update->fields + n_fields_updated;
fts_get_next_doc_id(table, &trx->fts_next_doc_id);
doc_id = fts_update_doc_id(table, ufield,
&trx->fts_next_doc_id);
n_fields_updated++;
fts_trx_add_op(trx, table, doc_id, FTS_INSERT, NULL);
} else {
if (doc_id_updated) {
ut_ad(new_doc_id);
fts_trx_add_op(trx, table, new_doc_id,
FTS_INSERT, NULL);
} else {
fprintf(stderr, "InnoDB: FTS Doc ID must be "
"updated along with FTS indexed "
"column for table ");
ut_print_name(stderr, trx, TRUE, table->name);
putc('\n', stderr);
return(ULINT_UNDEFINED);
}
}
}
update->n_fields = n_fields_updated;
return(n_fields_updated);
}
/*********************************************************************//**
Set detailed error message associated with foreign key errors for
the given transaction. */
static
void
row_ins_set_detailed(
/*=================*/
trx_t* trx, /*!< in: transaction */
dict_foreign_t* foreign) /*!< in: foreign key constraint */
{
ut_ad(!srv_read_only_mode);
mutex_enter(&srv_misc_tmpfile_mutex);
rewind(srv_misc_tmpfile);
if (os_file_set_eof(srv_misc_tmpfile)) {
ut_print_name(srv_misc_tmpfile, trx, TRUE,
foreign->foreign_table_name);
dict_print_info_on_foreign_key_in_create_format(
srv_misc_tmpfile, trx, foreign, FALSE);
trx_set_detailed_error_from_file(trx, srv_misc_tmpfile);
} else {
trx_set_detailed_error(trx, "temp file operation failed");
}
mutex_exit(&srv_misc_tmpfile_mutex);
}
/*********************************************************************//**
Acquires dict_foreign_err_mutex, rewinds dict_foreign_err_file
and displays information about the given transaction.
The caller must release dict_foreign_err_mutex. */
static
void
row_ins_foreign_trx_print(
/*======================*/
trx_t* trx) /*!< in: transaction */
{
ulint n_rec_locks;
ulint n_trx_locks;
ulint heap_size;
if (srv_read_only_mode) {
return;
}
lock_mutex_enter();
n_rec_locks = lock_number_of_rows_locked(&trx->lock);
n_trx_locks = UT_LIST_GET_LEN(trx->lock.trx_locks);
heap_size = mem_heap_get_size(trx->lock.lock_heap);
lock_mutex_exit();
mutex_enter(&trx_sys->mutex);
mutex_enter(&dict_foreign_err_mutex);
rewind(dict_foreign_err_file);
ut_print_timestamp(dict_foreign_err_file);
fputs(" Transaction:\n", dict_foreign_err_file);
trx_print_low(dict_foreign_err_file, trx, 600,
n_rec_locks, n_trx_locks, heap_size);
mutex_exit(&trx_sys->mutex);
ut_ad(mutex_own(&dict_foreign_err_mutex));
}
/*********************************************************************//**
Reports a foreign key error associated with an update or a delete of a
parent table index entry. */
static
void
row_ins_foreign_report_err(
/*=======================*/
const char* errstr, /*!< in: error string from the viewpoint
of the parent table */
que_thr_t* thr, /*!< in: query thread whose run_node
is an update node */
dict_foreign_t* foreign, /*!< in: foreign key constraint */
const rec_t* rec, /*!< in: a matching index record in the
child table */
const dtuple_t* entry) /*!< in: index entry in the parent
table */
{
if (srv_read_only_mode) {
return;
}
FILE* ef = dict_foreign_err_file;
trx_t* trx = thr_get_trx(thr);
row_ins_set_detailed(trx, foreign);
row_ins_foreign_trx_print(trx);
fputs("Foreign key constraint fails for table ", ef);
ut_print_name(ef, trx, TRUE, foreign->foreign_table_name);
fputs(":\n", ef);
dict_print_info_on_foreign_key_in_create_format(ef, trx, foreign,
TRUE);
putc('\n', ef);
fputs(errstr, ef);
fputs(" in parent table, in index ", ef);
ut_print_name(ef, trx, FALSE, foreign->referenced_index->name);
if (entry) {
fputs(" tuple:\n", ef);
dtuple_print(ef, entry);
}
fputs("\nBut in child table ", ef);
ut_print_name(ef, trx, TRUE, foreign->foreign_table_name);
fputs(", in index ", ef);
ut_print_name(ef, trx, FALSE, foreign->foreign_index->name);
if (rec) {
fputs(", there is a record:\n", ef);
rec_print(ef, rec, foreign->foreign_index);
} else {
fputs(", the record is not available\n", ef);
}
putc('\n', ef);
mutex_exit(&dict_foreign_err_mutex);
}
/*********************************************************************//**
Reports a foreign key error to dict_foreign_err_file when we are trying
to add an index entry to a child table. Note that the adding may be the result
of an update, too. */
static
void
row_ins_foreign_report_add_err(
/*===========================*/
trx_t* trx, /*!< in: transaction */
dict_foreign_t* foreign, /*!< in: foreign key constraint */
const rec_t* rec, /*!< in: a record in the parent table:
it does not match entry because we
have an error! */
const dtuple_t* entry) /*!< in: index entry to insert in the
child table */
{
if (srv_read_only_mode) {
return;
}
FILE* ef = dict_foreign_err_file;
row_ins_set_detailed(trx, foreign);
row_ins_foreign_trx_print(trx);
fputs("Foreign key constraint fails for table ", ef);
ut_print_name(ef, trx, TRUE, foreign->foreign_table_name);
fputs(":\n", ef);
dict_print_info_on_foreign_key_in_create_format(ef, trx, foreign,
TRUE);
fputs("\nTrying to add in child table, in index ", ef);
ut_print_name(ef, trx, FALSE, foreign->foreign_index->name);
if (entry) {
fputs(" tuple:\n", ef);
/* TODO: DB_TRX_ID and DB_ROLL_PTR may be uninitialized.
It would be better to only display the user columns. */
dtuple_print(ef, entry);
}
fputs("\nBut in parent table ", ef);
ut_print_name(ef, trx, TRUE, foreign->referenced_table_name);
fputs(", in index ", ef);
ut_print_name(ef, trx, FALSE, foreign->referenced_index->name);
fputs(",\nthe closest match we can find is record:\n", ef);
if (rec && page_rec_is_supremum(rec)) {
/* If the cursor ended on a supremum record, it is better
to report the previous record in the error message, so that
the user gets a more descriptive error message. */
rec = page_rec_get_prev_const(rec);
}
if (rec) {
rec_print(ef, rec, foreign->referenced_index);
}
putc('\n', ef);
mutex_exit(&dict_foreign_err_mutex);
}
/*********************************************************************//**
Invalidate the query cache for the given table. */
static
void
row_ins_invalidate_query_cache(
/*===========================*/
que_thr_t* thr, /*!< in: query thread whose run_node
is an update node */
const char* name) /*!< in: table name prefixed with
database name and a '/' character */
{
char* buf;
char* ptr;
ulint len = strlen(name) + 1;
buf = mem_strdupl(name, len);
ptr = strchr(buf, '/');
ut_a(ptr);
*ptr = '\0';
innobase_invalidate_query_cache(thr_get_trx(thr), buf, len);
mem_free(buf);
}
/*********************************************************************//**
Perform referential actions or checks when a parent row is deleted or updated
and the constraint had an ON DELETE or ON UPDATE condition which was not
RESTRICT.
@return DB_SUCCESS, DB_LOCK_WAIT, or error code */
static __attribute__((nonnull, warn_unused_result))
dberr_t
row_ins_foreign_check_on_constraint(
/*================================*/
que_thr_t* thr, /*!< in: query thread whose run_node
is an update node */
dict_foreign_t* foreign, /*!< in: foreign key constraint whose
type is != 0 */
btr_pcur_t* pcur, /*!< in: cursor placed on a matching
index record in the child table */
dtuple_t* entry, /*!< in: index entry in the parent
table */
mtr_t* mtr) /*!< in: mtr holding the latch of pcur
page */
{
upd_node_t* node;
upd_node_t* cascade;
dict_table_t* table = foreign->foreign_table;
dict_index_t* index;
dict_index_t* clust_index;
dtuple_t* ref;
mem_heap_t* upd_vec_heap = NULL;
const rec_t* rec;
const rec_t* clust_rec;
const buf_block_t* clust_block;
upd_t* update;
ulint n_to_update;
dberr_t err;
ulint i;
trx_t* trx;
mem_heap_t* tmp_heap = NULL;
doc_id_t doc_id = FTS_NULL_DOC_ID;
ibool fts_col_affacted = FALSE;
ut_a(thr);
ut_a(foreign);
ut_a(pcur);
ut_a(mtr);
trx = thr_get_trx(thr);
/* Since we are going to delete or update a row, we have to invalidate
the MySQL query cache for table. A deadlock of threads is not possible
here because the caller of this function does not hold any latches with
the sync0sync.h rank above the lock_sys_t::mutex. The query cache mutex
has a rank just above the lock_sys_t::mutex. */
row_ins_invalidate_query_cache(thr, table->name);
node = static_cast<upd_node_t*>(thr->run_node);
if (node->is_delete && 0 == (foreign->type
& (DICT_FOREIGN_ON_DELETE_CASCADE
| DICT_FOREIGN_ON_DELETE_SET_NULL))) {
row_ins_foreign_report_err("Trying to delete",
thr, foreign,
btr_pcur_get_rec(pcur), entry);
return(DB_ROW_IS_REFERENCED);
}
if (!node->is_delete && 0 == (foreign->type
& (DICT_FOREIGN_ON_UPDATE_CASCADE
| DICT_FOREIGN_ON_UPDATE_SET_NULL))) {
/* This is an UPDATE */
row_ins_foreign_report_err("Trying to update",
thr, foreign,
btr_pcur_get_rec(pcur), entry);
return(DB_ROW_IS_REFERENCED);
}
if (node->cascade_node == NULL) {
/* Extend our query graph by creating a child to current
update node. The child is used in the cascade or set null
operation. */
node->cascade_heap = mem_heap_create(128);
node->cascade_node = row_create_update_node_for_mysql(
table, node->cascade_heap);
que_node_set_parent(node->cascade_node, node);
}
/* Initialize cascade_node to do the operation we want. Note that we
use the SAME cascade node to do all foreign key operations of the
SQL DELETE: the table of the cascade node may change if there are
several child tables to the table where the delete is done! */
cascade = node->cascade_node;
cascade->table = table;
cascade->foreign = foreign;
if (node->is_delete
&& (foreign->type & DICT_FOREIGN_ON_DELETE_CASCADE)) {
cascade->is_delete = TRUE;
} else {
cascade->is_delete = FALSE;
if (foreign->n_fields > cascade->update_n_fields) {
/* We have to make the update vector longer */
cascade->update = upd_create(foreign->n_fields,
node->cascade_heap);
cascade->update_n_fields = foreign->n_fields;
}
}
/* We do not allow cyclic cascaded updating (DELETE is allowed,
but not UPDATE) of the same table, as this can lead to an infinite
cycle. Check that we are not updating the same table which is
already being modified in this cascade chain. We have to check
this also because the modification of the indexes of a 'parent'
table may still be incomplete, and we must avoid seeing the indexes
of the parent table in an inconsistent state! */
if (!cascade->is_delete
&& row_ins_cascade_ancestor_updates_table(cascade, table)) {
/* We do not know if this would break foreign key
constraints, but play safe and return an error */
err = DB_ROW_IS_REFERENCED;
row_ins_foreign_report_err(
"Trying an update, possibly causing a cyclic"
" cascaded update\n"
"in the child table,", thr, foreign,
btr_pcur_get_rec(pcur), entry);
goto nonstandard_exit_func;
}
if (row_ins_cascade_n_ancestors(cascade) >= 15) {
err = DB_ROW_IS_REFERENCED;
row_ins_foreign_report_err(
"Trying a too deep cascaded delete or update\n",
thr, foreign, btr_pcur_get_rec(pcur), entry);
goto nonstandard_exit_func;
}
index = btr_pcur_get_btr_cur(pcur)->index;
ut_a(index == foreign->foreign_index);
rec = btr_pcur_get_rec(pcur);
tmp_heap = mem_heap_create(256);
if (dict_index_is_clust(index)) {
/* pcur is already positioned in the clustered index of
the child table */
clust_index = index;
clust_rec = rec;
clust_block = btr_pcur_get_block(pcur);
} else {
/* We have to look for the record in the clustered index
in the child table */
clust_index = dict_table_get_first_index(table);
ref = row_build_row_ref(ROW_COPY_POINTERS, index, rec,
tmp_heap);
btr_pcur_open_with_no_init(clust_index, ref,
PAGE_CUR_LE, BTR_SEARCH_LEAF,
cascade->pcur, 0, mtr);
clust_rec = btr_pcur_get_rec(cascade->pcur);
clust_block = btr_pcur_get_block(cascade->pcur);
if (!page_rec_is_user_rec(clust_rec)
|| btr_pcur_get_low_match(cascade->pcur)
< dict_index_get_n_unique(clust_index)) {
fputs("InnoDB: error in cascade of a foreign key op\n"
"InnoDB: ", stderr);
dict_index_name_print(stderr, trx, index);
fputs("\n"
"InnoDB: record ", stderr);
rec_print(stderr, rec, index);
fputs("\n"
"InnoDB: clustered record ", stderr);
rec_print(stderr, clust_rec, clust_index);
fputs("\n"
"InnoDB: Submit a detailed bug report to"
" http://bugs.mysql.com\n", stderr);
ut_ad(0);
err = DB_SUCCESS;
goto nonstandard_exit_func;
}
}
/* Set an X-lock on the row to delete or update in the child table */
err = lock_table(0, table, LOCK_IX, thr);
if (err == DB_SUCCESS) {
/* Here it suffices to use a LOCK_REC_NOT_GAP type lock;
we already have a normal shared lock on the appropriate
gap if the search criterion was not unique */
err = lock_clust_rec_read_check_and_lock_alt(
0, clust_block, clust_rec, clust_index,
LOCK_X, LOCK_REC_NOT_GAP, thr);
}
if (err != DB_SUCCESS) {
goto nonstandard_exit_func;
}
if (rec_get_deleted_flag(clust_rec, dict_table_is_comp(table))) {
/* This can happen if there is a circular reference of
rows such that cascading delete comes to delete a row
already in the process of being delete marked */
err = DB_SUCCESS;
goto nonstandard_exit_func;
}
if (table->fts) {
doc_id = fts_get_doc_id_from_rec(table, clust_rec, tmp_heap);
}
if (node->is_delete
? (foreign->type & DICT_FOREIGN_ON_DELETE_SET_NULL)
: (foreign->type & DICT_FOREIGN_ON_UPDATE_SET_NULL)) {
/* Build the appropriate update vector which sets
foreign->n_fields first fields in rec to SQL NULL */
update = cascade->update;
update->info_bits = 0;
update->n_fields = foreign->n_fields;
UNIV_MEM_INVALID(update->fields,
update->n_fields * sizeof *update->fields);
for (i = 0; i < foreign->n_fields; i++) {
upd_field_t* ufield = &update->fields[i];
ufield->field_no = dict_table_get_nth_col_pos(
table,
dict_index_get_nth_col_no(index, i));
ufield->orig_len = 0;
ufield->exp = NULL;
dfield_set_null(&ufield->new_val);
if (table->fts && dict_table_is_fts_column(
table->fts->indexes,
dict_index_get_nth_col_no(index, i))
!= ULINT_UNDEFINED) {
fts_col_affacted = TRUE;
}
}
if (fts_col_affacted) {
fts_trx_add_op(trx, table, doc_id, FTS_DELETE, NULL);
}
} else if (table->fts && cascade->is_delete) {
/* DICT_FOREIGN_ON_DELETE_CASCADE case */
for (i = 0; i < foreign->n_fields; i++) {
if (table->fts && dict_table_is_fts_column(
table->fts->indexes,
dict_index_get_nth_col_no(index, i))
!= ULINT_UNDEFINED) {
fts_col_affacted = TRUE;
}
}
if (fts_col_affacted) {
fts_trx_add_op(trx, table, doc_id, FTS_DELETE, NULL);
}
}
if (!node->is_delete
&& (foreign->type & DICT_FOREIGN_ON_UPDATE_CASCADE)) {
/* Build the appropriate update vector which sets changing
foreign->n_fields first fields in rec to new values */
upd_vec_heap = mem_heap_create(256);
n_to_update = row_ins_cascade_calc_update_vec(
node, foreign, upd_vec_heap, trx, &fts_col_affacted);
if (n_to_update == ULINT_UNDEFINED) {
err = DB_ROW_IS_REFERENCED;
row_ins_foreign_report_err(
"Trying a cascaded update where the"
" updated value in the child\n"
"table would not fit in the length"
" of the column, or the value would\n"
"be NULL and the column is"
" declared as not NULL in the child table,",
thr, foreign, btr_pcur_get_rec(pcur), entry);
goto nonstandard_exit_func;
}
if (cascade->update->n_fields == 0) {
/* The update does not change any columns referred
to in this foreign key constraint: no need to do
anything */
err = DB_SUCCESS;
goto nonstandard_exit_func;
}
/* Mark the old Doc ID as deleted */
if (fts_col_affacted) {
ut_ad(table->fts);
fts_trx_add_op(trx, table, doc_id, FTS_DELETE, NULL);
}
}
/* Store pcur position and initialize or store the cascade node
pcur stored position */
btr_pcur_store_position(pcur, mtr);
if (index == clust_index) {
btr_pcur_copy_stored_position(cascade->pcur, pcur);
} else {
btr_pcur_store_position(cascade->pcur, mtr);
}
mtr_commit(mtr);
ut_a(cascade->pcur->rel_pos == BTR_PCUR_ON);
cascade->state = UPD_NODE_UPDATE_CLUSTERED;
err = row_update_cascade_for_mysql(thr, cascade,
foreign->foreign_table);
if (foreign->foreign_table->n_foreign_key_checks_running == 0) {
fprintf(stderr,
"InnoDB: error: table %s has the counter 0"
" though there is\n"
"InnoDB: a FOREIGN KEY check running on it.\n",
foreign->foreign_table->name);
}
/* Release the data dictionary latch for a while, so that we do not
starve other threads from doing CREATE TABLE etc. if we have a huge
cascaded operation running. The counter n_foreign_key_checks_running
will prevent other users from dropping or ALTERing the table when we
release the latch. */
row_mysql_unfreeze_data_dictionary(thr_get_trx(thr));
DEBUG_SYNC_C("innodb_dml_cascade_dict_unfreeze");
row_mysql_freeze_data_dictionary(thr_get_trx(thr));
mtr_start(mtr);
/* Restore pcur position */
btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, mtr);
if (tmp_heap) {
mem_heap_free(tmp_heap);
}
if (upd_vec_heap) {
mem_heap_free(upd_vec_heap);
}
return(err);
nonstandard_exit_func:
if (tmp_heap) {
mem_heap_free(tmp_heap);
}
if (upd_vec_heap) {
mem_heap_free(upd_vec_heap);
}
btr_pcur_store_position(pcur, mtr);
mtr_commit(mtr);
mtr_start(mtr);
btr_pcur_restore_position(BTR_SEARCH_LEAF, pcur, mtr);
return(err);
}
/*********************************************************************//**
Sets a shared lock on a record. Used in locking possible duplicate key
records and also in checking foreign key constraints.
@return DB_SUCCESS, DB_SUCCESS_LOCKED_REC, or error code */
static
dberr_t
row_ins_set_shared_rec_lock(
/*========================*/
ulint type, /*!< in: LOCK_ORDINARY, LOCK_GAP, or
LOCK_REC_NOT_GAP type lock */
const buf_block_t* block, /*!< in: buffer block of rec */
const rec_t* rec, /*!< in: record */
dict_index_t* index, /*!< in: index */
const ulint* offsets,/*!< in: rec_get_offsets(rec, index) */
que_thr_t* thr) /*!< in: query thread */
{
dberr_t err;
ut_ad(rec_offs_validate(rec, index, offsets));
if (dict_index_is_clust(index)) {
err = lock_clust_rec_read_check_and_lock(
0, block, rec, index, offsets, LOCK_S, type, thr);
} else {
err = lock_sec_rec_read_check_and_lock(
0, block, rec, index, offsets, LOCK_S, type, thr);
}
return(err);
}
/*********************************************************************//**
Sets a exclusive lock on a record. Used in locking possible duplicate key
records
@return DB_SUCCESS, DB_SUCCESS_LOCKED_REC, or error code */
static
dberr_t
row_ins_set_exclusive_rec_lock(
/*===========================*/
ulint type, /*!< in: LOCK_ORDINARY, LOCK_GAP, or
LOCK_REC_NOT_GAP type lock */
const buf_block_t* block, /*!< in: buffer block of rec */
const rec_t* rec, /*!< in: record */
dict_index_t* index, /*!< in: index */
const ulint* offsets,/*!< in: rec_get_offsets(rec, index) */
que_thr_t* thr) /*!< in: query thread */
{
dberr_t err;
ut_ad(rec_offs_validate(rec, index, offsets));
if (dict_index_is_clust(index)) {
err = lock_clust_rec_read_check_and_lock(
0, block, rec, index, offsets, LOCK_X, type, thr);
} else {
err = lock_sec_rec_read_check_and_lock(
0, block, rec, index, offsets, LOCK_X, type, thr);
}
return(err);
}
/***************************************************************//**
Checks if foreign key constraint fails for an index entry. Sets shared locks
which lock either the success or the failure of the constraint. NOTE that
the caller must have a shared latch on dict_operation_lock.
@return DB_SUCCESS, DB_NO_REFERENCED_ROW, or DB_ROW_IS_REFERENCED */
UNIV_INTERN
dberr_t
row_ins_check_foreign_constraint(
/*=============================*/
ibool check_ref,/*!< in: TRUE if we want to check that
the referenced table is ok, FALSE if we
want to check the foreign key table */
dict_foreign_t* foreign,/*!< in: foreign constraint; NOTE that the
tables mentioned in it must be in the
dictionary cache if they exist at all */
dict_table_t* table, /*!< in: if check_ref is TRUE, then the foreign
table, else the referenced table */
dtuple_t* entry, /*!< in: index entry for index */
que_thr_t* thr) /*!< in: query thread */
{
dberr_t err;
upd_node_t* upd_node;
dict_table_t* check_table;
dict_index_t* check_index;
ulint n_fields_cmp;
btr_pcur_t pcur;
int cmp;
ulint i;
mtr_t mtr;
trx_t* trx = thr_get_trx(thr);
mem_heap_t* heap = NULL;
ulint offsets_[REC_OFFS_NORMAL_SIZE];
ulint* offsets = offsets_;
rec_offs_init(offsets_);
run_again:
#ifdef UNIV_SYNC_DEBUG
ut_ad(rw_lock_own(&dict_operation_lock, RW_LOCK_SHARED));
#endif /* UNIV_SYNC_DEBUG */
err = DB_SUCCESS;
if (trx->check_foreigns == FALSE) {
/* The user has suppressed foreign key checks currently for
this session */
goto exit_func;
}
/* If any of the foreign key fields in entry is SQL NULL, we
suppress the foreign key check: this is compatible with Oracle,
for example */
for (i = 0; i < foreign->n_fields; i++) {
if (UNIV_SQL_NULL == dfield_get_len(
dtuple_get_nth_field(entry, i))) {
goto exit_func;
}
}
if (que_node_get_type(thr->run_node) == QUE_NODE_UPDATE) {
upd_node = static_cast<upd_node_t*>(thr->run_node);
if (!(upd_node->is_delete) && upd_node->foreign == foreign) {
/* If a cascaded update is done as defined by a
foreign key constraint, do not check that
constraint for the child row. In ON UPDATE CASCADE
the update of the parent row is only half done when
we come here: if we would check the constraint here
for the child row it would fail.
A QUESTION remains: if in the child table there are
several constraints which refer to the same parent
table, we should merge all updates to the child as
one update? And the updates can be contradictory!
Currently we just perform the update associated
with each foreign key constraint, one after
another, and the user has problems predicting in
which order they are performed. */
goto exit_func;
}
}
if (check_ref) {
check_table = foreign->referenced_table;
check_index = foreign->referenced_index;
} else {
check_table = foreign->foreign_table;
check_index = foreign->foreign_index;
}
if (check_table == NULL
|| check_table->ibd_file_missing
|| check_index == NULL) {
if (!srv_read_only_mode && check_ref) {
FILE* ef = dict_foreign_err_file;
row_ins_set_detailed(trx, foreign);
row_ins_foreign_trx_print(trx);
fputs("Foreign key constraint fails for table ", ef);
ut_print_name(ef, trx, TRUE,
foreign->foreign_table_name);
fputs(":\n", ef);
dict_print_info_on_foreign_key_in_create_format(
ef, trx, foreign, TRUE);
fputs("\nTrying to add to index ", ef);
ut_print_name(ef, trx, FALSE,
foreign->foreign_index->name);
fputs(" tuple:\n", ef);
dtuple_print(ef, entry);
fputs("\nBut the parent table ", ef);
ut_print_name(ef, trx, TRUE,
foreign->referenced_table_name);
fputs("\nor its .ibd file does"
" not currently exist!\n", ef);
mutex_exit(&dict_foreign_err_mutex);
err = DB_NO_REFERENCED_ROW;
}
goto exit_func;
}
if (check_table != table) {
/* We already have a LOCK_IX on table, but not necessarily
on check_table */
err = lock_table(0, check_table, LOCK_IS, thr);
if (err != DB_SUCCESS) {
goto do_possible_lock_wait;
}
}
mtr_start(&mtr);
/* Store old value on n_fields_cmp */
n_fields_cmp = dtuple_get_n_fields_cmp(entry);
dtuple_set_n_fields_cmp(entry, foreign->n_fields);
btr_pcur_open(check_index, entry, PAGE_CUR_GE,
BTR_SEARCH_LEAF, &pcur, &mtr);
/* Scan index records and check if there is a matching record */
do {
const rec_t* rec = btr_pcur_get_rec(&pcur);
const buf_block_t* block = btr_pcur_get_block(&pcur);
SRV_CORRUPT_TABLE_CHECK(block,
{
err = DB_CORRUPTION;
goto exit_loop;
});
if (page_rec_is_infimum(rec)) {
continue;
}
offsets = rec_get_offsets(rec, check_index,
offsets, ULINT_UNDEFINED, &heap);
if (page_rec_is_supremum(rec)) {
err = row_ins_set_shared_rec_lock(LOCK_ORDINARY, block,
rec, check_index,
offsets, thr);
switch (err) {
case DB_SUCCESS_LOCKED_REC:
case DB_SUCCESS:
continue;
default:
goto end_scan;
}
}
cmp = cmp_dtuple_rec(entry, rec, offsets);
if (cmp == 0) {
if (rec_get_deleted_flag(rec,
rec_offs_comp(offsets))) {
err = row_ins_set_shared_rec_lock(
LOCK_ORDINARY, block,
rec, check_index, offsets, thr);
switch (err) {
case DB_SUCCESS_LOCKED_REC:
case DB_SUCCESS:
break;
default:
goto end_scan;
}
} else {
/* Found a matching record. Lock only
a record because we can allow inserts
into gaps */
err = row_ins_set_shared_rec_lock(
LOCK_REC_NOT_GAP, block,
rec, check_index, offsets, thr);
switch (err) {
case DB_SUCCESS_LOCKED_REC:
case DB_SUCCESS:
break;
default:
goto end_scan;
}
if (check_ref) {
err = DB_SUCCESS;
goto end_scan;
} else if (foreign->type != 0) {
/* There is an ON UPDATE or ON DELETE
condition: check them in a separate
function */
err = row_ins_foreign_check_on_constraint(
thr, foreign, &pcur, entry,
&mtr);
if (err != DB_SUCCESS) {
/* Since reporting a plain
"duplicate key" error
message to the user in
cases where a long CASCADE
operation would lead to a
duplicate key in some
other table is very
confusing, map duplicate
key errors resulting from
FK constraints to a
separate error code. */
if (err == DB_DUPLICATE_KEY) {
err = DB_FOREIGN_DUPLICATE_KEY;
}
goto end_scan;
}
/* row_ins_foreign_check_on_constraint
may have repositioned pcur on a
different block */
block = btr_pcur_get_block(&pcur);
} else {
row_ins_foreign_report_err(
"Trying to delete or update",
thr, foreign, rec, entry);
err = DB_ROW_IS_REFERENCED;
goto end_scan;
}
}
} else {
ut_a(cmp < 0);
err = row_ins_set_shared_rec_lock(
LOCK_GAP, block,
rec, check_index, offsets, thr);
switch (err) {
case DB_SUCCESS_LOCKED_REC:
case DB_SUCCESS:
if (check_ref) {
err = DB_NO_REFERENCED_ROW;
row_ins_foreign_report_add_err(
trx, foreign, rec, entry);
} else {
err = DB_SUCCESS;
}
default:
break;
}
goto end_scan;
}
} while (btr_pcur_move_to_next(&pcur, &mtr));
exit_loop:
if (check_ref) {
row_ins_foreign_report_add_err(
trx, foreign, btr_pcur_get_rec(&pcur), entry);
err = DB_NO_REFERENCED_ROW;
} else {
err = DB_SUCCESS;
}
end_scan:
btr_pcur_close(&pcur);
mtr_commit(&mtr);
/* Restore old value */
dtuple_set_n_fields_cmp(entry, n_fields_cmp);
do_possible_lock_wait:
if (err == DB_LOCK_WAIT) {
bool verified = false;
trx->error_state = err;
que_thr_stop_for_mysql(thr);
lock_wait_suspend_thread(thr);
if (check_table->to_be_dropped) {
/* The table is being dropped. We shall timeout
this operation */
err = DB_LOCK_WAIT_TIMEOUT;
goto exit_func;
}
/* We had temporarily released dict_operation_lock in
above lock sleep wait, now we have the lock again, and
we will need to re-check whether the foreign key has been
dropped. We only need to verify if the table is referenced
table case (check_ref == 0), since MDL lock will prevent
concurrent DDL and DML on the same table */
if (!check_ref) {
for (dict_foreign_set::iterator it
= table->referenced_set.begin();
it != table->referenced_set.end();
++it) {
if (*it == foreign) {
verified = true;
break;
}
}
} else {
verified = true;
}
if (!verified) {
err = DB_DICT_CHANGED;
} else if (trx->error_state == DB_SUCCESS) {
goto run_again;
} else {
err = trx->error_state;
}
}
exit_func:
if (UNIV_LIKELY_NULL(heap)) {
mem_heap_free(heap);
}
if (UNIV_UNLIKELY(trx->fake_changes)) {
err = DB_SUCCESS;
}
return(err);
}
/***************************************************************//**
Checks if foreign key constraints fail for an index entry. If index
is not mentioned in any constraint, this function does nothing,
Otherwise does searches to the indexes of referenced tables and
sets shared locks which lock either the success or the failure of
a constraint.
@return DB_SUCCESS or error code */
static __attribute__((nonnull, warn_unused_result))
dberr_t
row_ins_check_foreign_constraints(
/*==============================*/
dict_table_t* table, /*!< in: table */
dict_index_t* index, /*!< in: index */
dtuple_t* entry, /*!< in: index entry for index */
que_thr_t* thr) /*!< in: query thread */
{
dict_foreign_t* foreign;
dberr_t err;
trx_t* trx;
ibool got_s_lock = FALSE;
trx = thr_get_trx(thr);
DEBUG_SYNC_C_IF_THD(thr_get_trx(thr)->mysql_thd,
"foreign_constraint_check_for_ins");
for (dict_foreign_set::iterator it = table->foreign_set.begin();
it != table->foreign_set.end();
++it) {
foreign = *it;
if (foreign->foreign_index == index) {
dict_table_t* ref_table = NULL;
dict_table_t* foreign_table = foreign->foreign_table;
dict_table_t* referenced_table
= foreign->referenced_table;
if (referenced_table == NULL) {
ref_table = dict_table_open_on_name(
foreign->referenced_table_name_lookup,
FALSE, FALSE, DICT_ERR_IGNORE_NONE);
}
if (0 == trx->dict_operation_lock_mode) {
got_s_lock = TRUE;
row_mysql_freeze_data_dictionary(trx);
}
if (referenced_table) {
os_inc_counter(dict_sys->mutex,
foreign_table
->n_foreign_key_checks_running);
}
/* NOTE that if the thread ends up waiting for a lock
we will release dict_operation_lock temporarily!
But the counter on the table protects the referenced
table from being dropped while the check is running. */
err = row_ins_check_foreign_constraint(
TRUE, foreign, table, entry, thr);
DBUG_EXECUTE_IF("row_ins_dict_change_err",
err = DB_DICT_CHANGED;);
if (referenced_table) {
os_dec_counter(dict_sys->mutex,
foreign_table
->n_foreign_key_checks_running);
}
if (got_s_lock) {
row_mysql_unfreeze_data_dictionary(trx);
}
if (ref_table != NULL) {
dict_table_close(ref_table, FALSE, FALSE);
}
if (err != DB_SUCCESS) {
return(err);
}
}
}
return(DB_SUCCESS);
}
/***************************************************************//**
Checks if a unique key violation to rec would occur at the index entry
insert.
@return TRUE if error */
static
ibool
row_ins_dupl_error_with_rec(
/*========================*/
const rec_t* rec, /*!< in: user record; NOTE that we assume
that the caller already has a record lock on
the record! */
const dtuple_t* entry, /*!< in: entry to insert */
dict_index_t* index, /*!< in: index */
const ulint* offsets)/*!< in: rec_get_offsets(rec, index) */
{
ulint matched_fields;
ulint matched_bytes;
ulint n_unique;
ulint i;
ut_ad(rec_offs_validate(rec, index, offsets));
n_unique = dict_index_get_n_unique(index);
matched_fields = 0;
matched_bytes = 0;
cmp_dtuple_rec_with_match(entry, rec, offsets,
&matched_fields, &matched_bytes);
if (matched_fields < n_unique) {
return(FALSE);
}
/* In a unique secondary index we allow equal key values if they
contain SQL NULLs */
if (!dict_index_is_clust(index)) {
for (i = 0; i < n_unique; i++) {
if (dfield_is_null(dtuple_get_nth_field(entry, i))) {
return(FALSE);
}
}
}
return(!rec_get_deleted_flag(rec, rec_offs_comp(offsets)));
}
/***************************************************************//**
Scans a unique non-clustered index at a given index entry to determine
whether a uniqueness violation has occurred for the key value of the entry.
Set shared locks on possible duplicate records.
@return DB_SUCCESS, DB_DUPLICATE_KEY, or DB_LOCK_WAIT */
static __attribute__((nonnull, warn_unused_result))
dberr_t
row_ins_scan_sec_index_for_duplicate(
/*=================================*/
ulint flags, /*!< in: undo logging and locking flags */
dict_index_t* index, /*!< in: non-clustered unique index */
dtuple_t* entry, /*!< in: index entry */
que_thr_t* thr, /*!< in: query thread */
bool s_latch,/*!< in: whether index->lock is being held */
mtr_t* mtr, /*!< in/out: mini-transaction */
mem_heap_t* offsets_heap)
/*!< in/out: memory heap that can be emptied */
{
ulint n_unique;
int cmp;
ulint n_fields_cmp;
btr_pcur_t pcur;
dberr_t err = DB_SUCCESS;
ulint allow_duplicates;
ulint* offsets = NULL;
#ifdef UNIV_SYNC_DEBUG
ut_ad(s_latch == rw_lock_own(&index->lock, RW_LOCK_SHARED));
#endif /* UNIV_SYNC_DEBUG */
n_unique = dict_index_get_n_unique(index);
/* If the secondary index is unique, but one of the fields in the
n_unique first fields is NULL, a unique key violation cannot occur,
since we define NULL != NULL in this case */
for (ulint i = 0; i < n_unique; i++) {
if (UNIV_SQL_NULL == dfield_get_len(
dtuple_get_nth_field(entry, i))) {
return(DB_SUCCESS);
}
}
/* Store old value on n_fields_cmp */
n_fields_cmp = dtuple_get_n_fields_cmp(entry);
dtuple_set_n_fields_cmp(entry, n_unique);
btr_pcur_open(index, entry, PAGE_CUR_GE,
s_latch
? BTR_SEARCH_LEAF | BTR_ALREADY_S_LATCHED
: BTR_SEARCH_LEAF,
&pcur, mtr);
allow_duplicates = thr_get_trx(thr)->duplicates;
/* Scan index records and check if there is a duplicate */
do {
const rec_t* rec = btr_pcur_get_rec(&pcur);
const buf_block_t* block = btr_pcur_get_block(&pcur);
const ulint lock_type = LOCK_ORDINARY;
if (page_rec_is_infimum(rec)) {
continue;
}
offsets = rec_get_offsets(rec, index, offsets,
ULINT_UNDEFINED, &offsets_heap);
if (flags & BTR_NO_LOCKING_FLAG) {
/* Set no locks when applying log
in online table rebuild. */
} else if (allow_duplicates) {
/* If the SQL-query will update or replace
duplicate key we will take X-lock for
duplicates ( REPLACE, LOAD DATAFILE REPLACE,
INSERT ON DUPLICATE KEY UPDATE). */
err = row_ins_set_exclusive_rec_lock(
lock_type, block, rec, index, offsets, thr);
} else {
err = row_ins_set_shared_rec_lock(
lock_type, block, rec, index, offsets, thr);
}
switch (err) {
case DB_SUCCESS_LOCKED_REC:
err = DB_SUCCESS;
case DB_SUCCESS:
break;
default:
goto end_scan;
}
if (page_rec_is_supremum(rec)) {
continue;
}
cmp = cmp_dtuple_rec(entry, rec, offsets);
if (cmp == 0) {
if (row_ins_dupl_error_with_rec(rec, entry,
index, offsets)) {
err = DB_DUPLICATE_KEY;
thr_get_trx(thr)->error_info = index;
/* If the duplicate is on hidden FTS_DOC_ID,
state so in the error log */
if (DICT_TF2_FLAG_IS_SET(
index->table,
DICT_TF2_FTS_HAS_DOC_ID)
&& strcmp(index->name,
FTS_DOC_ID_INDEX_NAME) == 0) {
ib_logf(IB_LOG_LEVEL_ERROR,
"Duplicate FTS_DOC_ID value"
" on table %s",
index->table->name);
}
goto end_scan;
}
} else {
ut_a(cmp < 0);
goto end_scan;
}
} while (btr_pcur_move_to_next(&pcur, mtr));
end_scan:
/* Restore old value */
dtuple_set_n_fields_cmp(entry, n_fields_cmp);
return(err);
}
/** Checks for a duplicate when the table is being rebuilt online.
@retval DB_SUCCESS when no duplicate is detected
@retval DB_SUCCESS_LOCKED_REC when rec is an exact match of entry or
a newer version of entry (the entry should not be inserted)
@retval DB_DUPLICATE_KEY when entry is a duplicate of rec */
static __attribute__((nonnull, warn_unused_result))
dberr_t
row_ins_duplicate_online(
/*=====================*/
ulint n_uniq, /*!< in: offset of DB_TRX_ID */
const dtuple_t* entry, /*!< in: entry that is being inserted */
const rec_t* rec, /*!< in: clustered index record */
ulint* offsets)/*!< in/out: rec_get_offsets(rec) */
{
ulint fields = 0;
ulint bytes = 0;
/* During rebuild, there should not be any delete-marked rows
in the new table. */
ut_ad(!rec_get_deleted_flag(rec, rec_offs_comp(offsets)));
ut_ad(dtuple_get_n_fields_cmp(entry) == n_uniq);
/* Compare the PRIMARY KEY fields and the
DB_TRX_ID, DB_ROLL_PTR. */
cmp_dtuple_rec_with_match_low(
entry, rec, offsets, n_uniq + 2, &fields, &bytes);
if (fields < n_uniq) {
/* Not a duplicate. */
return(DB_SUCCESS);
}
if (fields == n_uniq + 2) {
/* rec is an exact match of entry. */
ut_ad(bytes == 0);
return(DB_SUCCESS_LOCKED_REC);
}
return(DB_DUPLICATE_KEY);
}
/** Checks for a duplicate when the table is being rebuilt online.
@retval DB_SUCCESS when no duplicate is detected
@retval DB_SUCCESS_LOCKED_REC when rec is an exact match of entry or
a newer version of entry (the entry should not be inserted)
@retval DB_DUPLICATE_KEY when entry is a duplicate of rec */
static __attribute__((nonnull, warn_unused_result))
dberr_t
row_ins_duplicate_error_in_clust_online(
/*====================================*/
ulint n_uniq, /*!< in: offset of DB_TRX_ID */
const dtuple_t* entry, /*!< in: entry that is being inserted */
const btr_cur_t*cursor, /*!< in: cursor on insert position */
ulint** offsets,/*!< in/out: rec_get_offsets(rec) */
mem_heap_t** heap) /*!< in/out: heap for offsets */
{
dberr_t err = DB_SUCCESS;
const rec_t* rec = btr_cur_get_rec(cursor);
if (cursor->low_match >= n_uniq && !page_rec_is_infimum(rec)) {
*offsets = rec_get_offsets(rec, cursor->index, *offsets,
ULINT_UNDEFINED, heap);
err = row_ins_duplicate_online(n_uniq, entry, rec, *offsets);
if (err != DB_SUCCESS) {
return(err);
}
}
rec = page_rec_get_next_const(btr_cur_get_rec(cursor));
if (cursor->up_match >= n_uniq && !page_rec_is_supremum(rec)) {
*offsets = rec_get_offsets(rec, cursor->index, *offsets,
ULINT_UNDEFINED, heap);
err = row_ins_duplicate_online(n_uniq, entry, rec, *offsets);
}
return(err);
}
/***************************************************************//**
Checks if a unique key violation error would occur at an index entry
insert. Sets shared locks on possible duplicate records. Works only
for a clustered index!
@retval DB_SUCCESS if no error
@retval DB_DUPLICATE_KEY if error,
@retval DB_LOCK_WAIT if we have to wait for a lock on a possible duplicate
record
@retval DB_SUCCESS_LOCKED_REC if an exact match of the record was found
in online table rebuild (flags & (BTR_KEEP_SYS_FLAG | BTR_NO_LOCKING_FLAG)) */
static __attribute__((nonnull, warn_unused_result))
dberr_t
row_ins_duplicate_error_in_clust(
/*=============================*/
ulint flags, /*!< in: undo logging and locking flags */
btr_cur_t* cursor, /*!< in: B-tree cursor */
const dtuple_t* entry, /*!< in: entry to insert */
que_thr_t* thr, /*!< in: query thread */
mtr_t* mtr) /*!< in: mtr */
{
dberr_t err;
rec_t* rec;
ulint n_unique;
trx_t* trx = thr_get_trx(thr);
mem_heap_t*heap = NULL;
ulint offsets_[REC_OFFS_NORMAL_SIZE];
ulint* offsets = offsets_;
rec_offs_init(offsets_);
UT_NOT_USED(mtr);
ut_ad(dict_index_is_clust(cursor->index));
/* NOTE: For unique non-clustered indexes there may be any number
of delete marked records with the same value for the non-clustered
index key (remember multiversioning), and which differ only in
the row refererence part of the index record, containing the
clustered index key fields. For such a secondary index record,
to avoid race condition, we must FIRST do the insertion and after
that check that the uniqueness condition is not breached! */
/* NOTE: A problem is that in the B-tree node pointers on an
upper level may match more to the entry than the actual existing
user records on the leaf level. So, even if low_match would suggest
that a duplicate key violation may occur, this may not be the case. */
n_unique = dict_index_get_n_unique(cursor->index);
if (cursor->low_match >= n_unique) {
rec = btr_cur_get_rec(cursor);
if (!page_rec_is_infimum(rec)) {
offsets = rec_get_offsets(rec, cursor->index, offsets,
ULINT_UNDEFINED, &heap);
/* We set a lock on the possible duplicate: this
is needed in logical logging of MySQL to make
sure that in roll-forward we get the same duplicate
errors as in original execution */
if (trx->duplicates) {
/* If the SQL-query will update or replace
duplicate key we will take X-lock for
duplicates ( REPLACE, LOAD DATAFILE REPLACE,
INSERT ON DUPLICATE KEY UPDATE). */
err = row_ins_set_exclusive_rec_lock(
LOCK_REC_NOT_GAP,
btr_cur_get_block(cursor),
rec, cursor->index, offsets, thr);
} else {
err = row_ins_set_shared_rec_lock(
LOCK_REC_NOT_GAP,
btr_cur_get_block(cursor), rec,
cursor->index, offsets, thr);
}
switch (err) {
case DB_SUCCESS_LOCKED_REC:
case DB_SUCCESS:
break;
default:
goto func_exit;
}
if (row_ins_dupl_error_with_rec(
rec, entry, cursor->index, offsets)) {
duplicate:
trx->error_info = cursor->index;
err = DB_DUPLICATE_KEY;
goto func_exit;
}
}
}
if (cursor->up_match >= n_unique) {
rec = page_rec_get_next(btr_cur_get_rec(cursor));
if (!page_rec_is_supremum(rec)) {
offsets = rec_get_offsets(rec, cursor->index, offsets,
ULINT_UNDEFINED, &heap);
if (trx->duplicates) {
/* If the SQL-query will update or replace
duplicate key we will take X-lock for
duplicates ( REPLACE, LOAD DATAFILE REPLACE,
INSERT ON DUPLICATE KEY UPDATE). */
err = row_ins_set_exclusive_rec_lock(
LOCK_REC_NOT_GAP,
btr_cur_get_block(cursor),
rec, cursor->index, offsets, thr);
} else {
err = row_ins_set_shared_rec_lock(
LOCK_REC_NOT_GAP,
btr_cur_get_block(cursor),
rec, cursor->index, offsets, thr);
}
switch (err) {
case DB_SUCCESS_LOCKED_REC:
case DB_SUCCESS:
break;
default:
goto func_exit;
}
if (row_ins_dupl_error_with_rec(
rec, entry, cursor->index, offsets)) {
goto duplicate;
}
}
/* This should never happen */
ut_error;
}
err = DB_SUCCESS;
func_exit:
if (UNIV_LIKELY_NULL(heap)) {
mem_heap_free(heap);
}
return(err);
}
/***************************************************************//**
Checks if an index entry has long enough common prefix with an
existing record so that the intended insert of the entry must be
changed to a modify of the existing record. In the case of a clustered
index, the prefix must be n_unique fields long. In the case of a
secondary index, all fields must be equal. InnoDB never updates
secondary index records in place, other than clearing or setting the
delete-mark flag. We could be able to update the non-unique fields
of a unique secondary index record by checking the cursor->up_match,
but we do not do so, because it could have some locking implications.
@return TRUE if the existing record should be updated; FALSE if not */
UNIV_INLINE
ibool
row_ins_must_modify_rec(
/*====================*/
const btr_cur_t* cursor) /*!< in: B-tree cursor */
{
/* NOTE: (compare to the note in row_ins_duplicate_error_in_clust)
Because node pointers on upper levels of the B-tree may match more
to entry than to actual user records on the leaf level, we
have to check if the candidate record is actually a user record.
A clustered index node pointer contains index->n_unique first fields,
and a secondary index node pointer contains all index fields. */
return(cursor->low_match
>= dict_index_get_n_unique_in_tree(cursor->index)
&& !page_rec_is_infimum(btr_cur_get_rec(cursor)));
}
/***************************************************************//**
Tries to insert an entry into a clustered index, ignoring foreign key
constraints. If a record with the same unique key is found, the other
record is necessarily marked deleted by a committed transaction, or a
unique key violation error occurs. The delete marked record is then
updated to an existing record, and we must write an undo log record on
the delete marked record.
@retval DB_SUCCESS on success
@retval DB_LOCK_WAIT on lock wait when !(flags & BTR_NO_LOCKING_FLAG)
@retval DB_FAIL if retry with BTR_MODIFY_TREE is needed
@return error code */
UNIV_INTERN
dberr_t
row_ins_clust_index_entry_low(
/*==========================*/
ulint flags, /*!< in: undo logging and locking flags */
ulint mode, /*!< in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
depending on whether we wish optimistic or
pessimistic descent down the index tree */
dict_index_t* index, /*!< in: clustered index */
ulint n_uniq, /*!< in: 0 or index->n_uniq */
dtuple_t* entry, /*!< in/out: index entry to insert */
ulint n_ext, /*!< in: number of externally stored columns */
que_thr_t* thr) /*!< in: query thread */
{
btr_cur_t cursor;
ulint* offsets = NULL;
dberr_t err;
big_rec_t* big_rec = NULL;
mtr_t mtr;
mem_heap_t* offsets_heap = NULL;
ut_ad(dict_index_is_clust(index));
ut_ad(!dict_index_is_unique(index)
|| n_uniq == dict_index_get_n_unique(index));
ut_ad(!n_uniq || n_uniq == dict_index_get_n_unique(index));
mtr_start(&mtr);
if (mode == BTR_MODIFY_LEAF && dict_index_is_online_ddl(index)) {
if (UNIV_UNLIKELY(thr_get_trx(thr)->fake_changes)) {
mode = BTR_SEARCH_LEAF | BTR_ALREADY_S_LATCHED;
} else {
mode = BTR_MODIFY_LEAF | BTR_ALREADY_S_LATCHED;
}
mtr_s_lock(dict_index_get_lock(index), &mtr);
} else if (UNIV_UNLIKELY(thr_get_trx(thr)->fake_changes)) {
mode = (mode & BTR_MODIFY_TREE)
? BTR_SEARCH_TREE : BTR_SEARCH_LEAF;
}
cursor.thr = thr;
/* Note that we use PAGE_CUR_LE as the search mode, because then
the function will return in both low_match and up_match of the
cursor sensible values */
btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_LE, mode,
&cursor, 0, __FILE__, __LINE__, &mtr);
#ifdef UNIV_DEBUG
{
page_t* page = btr_cur_get_page(&cursor);
rec_t* first_rec = page_rec_get_next(
page_get_infimum_rec(page));
ut_ad(page_rec_is_supremum(first_rec)
|| rec_get_n_fields(first_rec, index)
== dtuple_get_n_fields(entry));
}
#endif
if (n_uniq && (cursor.up_match >= n_uniq
|| cursor.low_match >= n_uniq)) {
if (flags
== (BTR_CREATE_FLAG | BTR_NO_LOCKING_FLAG
| BTR_NO_UNDO_LOG_FLAG | BTR_KEEP_SYS_FLAG)) {
/* Set no locks when applying log
in online table rebuild. Only check for duplicates. */
err = row_ins_duplicate_error_in_clust_online(
n_uniq, entry, &cursor,
&offsets, &offsets_heap);
switch (err) {
case DB_SUCCESS:
break;
default:
ut_ad(0);
/* fall through */
case DB_SUCCESS_LOCKED_REC:
case DB_DUPLICATE_KEY:
thr_get_trx(thr)->error_info = cursor.index;
}
} else {
/* Note that the following may return also
DB_LOCK_WAIT */
err = row_ins_duplicate_error_in_clust(
flags, &cursor, entry, thr, &mtr);
}
if (err != DB_SUCCESS) {
err_exit:
mtr_commit(&mtr);
goto func_exit;
}
}
if (row_ins_must_modify_rec(&cursor)) {
/* There is already an index entry with a long enough common
prefix, we must convert the insert into a modify of an
existing record */
mem_heap_t* entry_heap = mem_heap_create(1024);
err = row_ins_clust_index_entry_by_modify(
flags, mode, &cursor, &offsets, &offsets_heap,
entry_heap, &big_rec, entry, thr, &mtr);
rec_t* rec = btr_cur_get_rec(&cursor);
if (big_rec && UNIV_LIKELY(!thr_get_trx(thr)->fake_changes)) {
ut_a(err == DB_SUCCESS);
/* Write out the externally stored
columns while still x-latching
index->lock and block->lock. Allocate
pages for big_rec in the mtr that
modified the B-tree, but be sure to skip
any pages that were freed in mtr. We will
write out the big_rec pages before
committing the B-tree mini-transaction. If
the system crashes so that crash recovery
will not replay the mtr_commit(&mtr), the
big_rec pages will be left orphaned until
the pages are allocated for something else.
TODO: If the allocation extends the
tablespace, it will not be redo
logged, in either mini-transaction.
Tablespace extension should be
redo-logged in the big_rec
mini-transaction, so that recovery
will not fail when the big_rec was
written to the extended portion of the
file, in case the file was somehow
truncated in the crash. */
DEBUG_SYNC_C_IF_THD(
thr_get_trx(thr)->mysql_thd,
"before_row_ins_upd_extern");
err = btr_store_big_rec_extern_fields(
index, btr_cur_get_block(&cursor),
rec, offsets, big_rec, &mtr,
BTR_STORE_INSERT_UPDATE);
DEBUG_SYNC_C_IF_THD(
thr_get_trx(thr)->mysql_thd,
"after_row_ins_upd_extern");
/* If writing big_rec fails (for
example, because of DB_OUT_OF_FILE_SPACE),
the record will be corrupted. Even if
we did not update any externally
stored columns, our update could cause
the record to grow so that a
non-updated column was selected for
external storage. This non-update
would not have been written to the
undo log, and thus the record cannot
be rolled back.
However, because we have not executed
mtr_commit(mtr) yet, the update will
not be replayed in crash recovery, and
the following assertion failure will
effectively "roll back" the operation. */
ut_a(err == DB_SUCCESS);
dtuple_big_rec_free(big_rec);
}
if (err == DB_SUCCESS && dict_index_is_online_ddl(index)) {
row_log_table_insert(rec, index, offsets);
}
mtr_commit(&mtr);
mem_heap_free(entry_heap);
} else {
rec_t* insert_rec;
if (mode != BTR_MODIFY_TREE) {
ut_ad(((mode & ~BTR_ALREADY_S_LATCHED)
== BTR_MODIFY_LEAF)
|| thr_get_trx(thr)->fake_changes);
err = btr_cur_optimistic_insert(
flags, &cursor, &offsets, &offsets_heap,
entry, &insert_rec, &big_rec,
n_ext, thr, &mtr);
} else {
if (buf_LRU_buf_pool_running_out()) {
err = DB_LOCK_TABLE_FULL;
goto err_exit;
}
err = btr_cur_optimistic_insert(
flags, &cursor,
&offsets, &offsets_heap,
entry, &insert_rec, &big_rec,
n_ext, thr, &mtr);
if (err == DB_FAIL) {
err = btr_cur_pessimistic_insert(
flags, &cursor,
&offsets, &offsets_heap,
entry, &insert_rec, &big_rec,
n_ext, thr, &mtr);
}
}
if (UNIV_LIKELY_NULL(big_rec)) {
mtr_commit(&mtr);
if (UNIV_UNLIKELY(thr_get_trx(thr)->fake_changes)) {
/* skip store extern */
mem_heap_free(big_rec->heap);
goto func_exit;
}
/* Online table rebuild could read (and
ignore) the incomplete record at this point.
If online rebuild is in progress, the
row_ins_index_entry_big_rec() will write log. */
DBUG_EXECUTE_IF(
"row_ins_extern_checkpoint",
log_make_checkpoint_at(
LSN_MAX, TRUE););
err = row_ins_index_entry_big_rec(
entry, big_rec, offsets, &offsets_heap, index,
thr_get_trx(thr)->mysql_thd,
__FILE__, __LINE__);
dtuple_convert_back_big_rec(index, entry, big_rec);
} else {
if (err == DB_SUCCESS
&& dict_index_is_online_ddl(index)) {
row_log_table_insert(
insert_rec, index, offsets);
}
mtr_commit(&mtr);
}
}
func_exit:
if (offsets_heap) {
mem_heap_free(offsets_heap);
}
return(err);
}
/***************************************************************//**
Starts a mini-transaction and checks if the index will be dropped.
@return true if the index is to be dropped */
static __attribute__((nonnull, warn_unused_result))
bool
row_ins_sec_mtr_start_and_check_if_aborted(
/*=======================================*/
mtr_t* mtr, /*!< out: mini-transaction */
dict_index_t* index, /*!< in/out: secondary index */
bool check, /*!< in: whether to check */
ulint search_mode)
/*!< in: flags */
{
ut_ad(!dict_index_is_clust(index));
mtr_start(mtr);
if (!check) {
return(false);
}
if (search_mode & BTR_ALREADY_S_LATCHED) {
mtr_s_lock(dict_index_get_lock(index), mtr);
} else {
mtr_x_lock(dict_index_get_lock(index), mtr);
}
switch (index->online_status) {
case ONLINE_INDEX_ABORTED:
case ONLINE_INDEX_ABORTED_DROPPED:
ut_ad(*index->name == TEMP_INDEX_PREFIX);
return(true);
case ONLINE_INDEX_COMPLETE:
return(false);
case ONLINE_INDEX_CREATION:
break;
}
ut_error;
return(true);
}
/***************************************************************//**
Tries to insert an entry into a secondary index. If a record with exactly the
same fields is found, the other record is necessarily marked deleted.
It is then unmarked. Otherwise, the entry is just inserted to the index.
@retval DB_SUCCESS on success
@retval DB_LOCK_WAIT on lock wait when !(flags & BTR_NO_LOCKING_FLAG)
@retval DB_FAIL if retry with BTR_MODIFY_TREE is needed
@return error code */
UNIV_INTERN
dberr_t
row_ins_sec_index_entry_low(
/*========================*/
ulint flags, /*!< in: undo logging and locking flags */
ulint mode, /*!< in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE,
depending on whether we wish optimistic or
pessimistic descent down the index tree */
dict_index_t* index, /*!< in: secondary index */
mem_heap_t* offsets_heap,
/*!< in/out: memory heap that can be emptied */
mem_heap_t* heap, /*!< in/out: memory heap */
dtuple_t* entry, /*!< in/out: index entry to insert */
trx_id_t trx_id, /*!< in: PAGE_MAX_TRX_ID during
row_log_table_apply(), or 0 */
que_thr_t* thr) /*!< in: query thread */
{
btr_cur_t cursor;
ulint search_mode = mode | BTR_INSERT;
dberr_t err = DB_SUCCESS;
ulint n_unique;
mtr_t mtr;
ulint* offsets = NULL;
ut_ad(!dict_index_is_clust(index));
ut_ad(mode == BTR_MODIFY_LEAF || mode == BTR_MODIFY_TREE);
cursor.thr = thr;
ut_ad(thr_get_trx(thr)->id);
mtr_start(&mtr);
/* Ensure that we acquire index->lock when inserting into an
index with index->online_status == ONLINE_INDEX_COMPLETE, but
could still be subject to rollback_inplace_alter_table().
This prevents a concurrent change of index->online_status.
The memory object cannot be freed as long as we have an open
reference to the table, or index->table->n_ref_count > 0. */
const bool check = *index->name == TEMP_INDEX_PREFIX;
if (check) {
DEBUG_SYNC_C("row_ins_sec_index_enter");
if (mode == BTR_MODIFY_LEAF) {
search_mode |= BTR_ALREADY_S_LATCHED;
mtr_s_lock(dict_index_get_lock(index), &mtr);
} else {
mtr_x_lock(dict_index_get_lock(index), &mtr);
}
if (row_log_online_op_try(
index, entry, thr_get_trx(thr)->id)) {
goto func_exit;
}
}
/* Note that we use PAGE_CUR_LE as the search mode, because then
the function will return in both low_match and up_match of the
cursor sensible values */
if (!thr_get_trx(thr)->check_unique_secondary) {
search_mode |= BTR_IGNORE_SEC_UNIQUE;
}
btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_LE,
search_mode,
&cursor, 0, __FILE__, __LINE__, &mtr);
if (cursor.flag == BTR_CUR_INSERT_TO_IBUF) {
/* The insert was buffered during the search: we are done */
goto func_exit;
}
#ifdef UNIV_DEBUG
{
page_t* page = btr_cur_get_page(&cursor);
rec_t* first_rec = page_rec_get_next(
page_get_infimum_rec(page));
ut_ad(page_rec_is_supremum(first_rec)
|| rec_get_n_fields(first_rec, index)
== dtuple_get_n_fields(entry));
}
#endif
n_unique = dict_index_get_n_unique(index);
if (dict_index_is_unique(index)
&& (cursor.low_match >= n_unique || cursor.up_match >= n_unique)) {
mtr_commit(&mtr);
DEBUG_SYNC_C("row_ins_sec_index_unique");
if (row_ins_sec_mtr_start_and_check_if_aborted(
&mtr, index, check, search_mode)) {
goto func_exit;
}
err = row_ins_scan_sec_index_for_duplicate(
flags, index, entry, thr, check, &mtr, offsets_heap);
mtr_commit(&mtr);
switch (err) {
case DB_SUCCESS:
break;
case DB_DUPLICATE_KEY:
if (*index->name == TEMP_INDEX_PREFIX) {
ut_ad(!thr_get_trx(thr)
->dict_operation_lock_mode);
mutex_enter(&dict_sys->mutex);
dict_set_corrupted_index_cache_only(
index, index->table);
mutex_exit(&dict_sys->mutex);
/* Do not return any error to the
caller. The duplicate will be reported
by ALTER TABLE or CREATE UNIQUE INDEX.
Unfortunately we cannot report the
duplicate key value to the DDL thread,
because the altered_table object is
private to its call stack. */
err = DB_SUCCESS;
}
/* fall through */
default:
return(err);
}
if (row_ins_sec_mtr_start_and_check_if_aborted(
&mtr, index, check, search_mode)) {
goto func_exit;
}
/* We did not find a duplicate and we have now
locked with s-locks the necessary records to
prevent any insertion of a duplicate by another
transaction. Let us now reposition the cursor and
continue the insertion. */
btr_cur_search_to_nth_level(
index, 0, entry, PAGE_CUR_LE,
UNIV_UNLIKELY(thr_get_trx(thr)->fake_changes)
? BTR_SEARCH_LEAF
: (btr_latch_mode)
(search_mode & ~(BTR_INSERT | BTR_IGNORE_SEC_UNIQUE)),
&cursor, 0, __FILE__, __LINE__, &mtr);
}
if (row_ins_must_modify_rec(&cursor)) {
/* There is already an index entry with a long enough common
prefix, we must convert the insert into a modify of an
existing record */
offsets = rec_get_offsets(
btr_cur_get_rec(&cursor), index, offsets,
ULINT_UNDEFINED, &offsets_heap);
err = row_ins_sec_index_entry_by_modify(
flags, mode, &cursor, &offsets,
offsets_heap, heap, entry, thr, &mtr);
} else {
rec_t* insert_rec;
big_rec_t* big_rec;
if (mode == BTR_MODIFY_LEAF) {
err = btr_cur_optimistic_insert(
flags, &cursor, &offsets, &offsets_heap,
entry, &insert_rec,
&big_rec, 0, thr, &mtr);
} else {
ut_ad(mode == BTR_MODIFY_TREE);
if (buf_LRU_buf_pool_running_out()) {
err = DB_LOCK_TABLE_FULL;
goto func_exit;
}
err = btr_cur_optimistic_insert(
flags, &cursor,
&offsets, &offsets_heap,
entry, &insert_rec,
&big_rec, 0, thr, &mtr);
if (err == DB_FAIL) {
err = btr_cur_pessimistic_insert(
flags, &cursor,
&offsets, &offsets_heap,
entry, &insert_rec,
&big_rec, 0, thr, &mtr);
}
}
if (err == DB_SUCCESS && trx_id) {
page_update_max_trx_id(
btr_cur_get_block(&cursor),
btr_cur_get_page_zip(&cursor),
trx_id, &mtr);
}
ut_ad(!big_rec);
}
func_exit:
mtr_commit(&mtr);
return(err);
}
/***************************************************************//**
Tries to insert the externally stored fields (off-page columns)
of a clustered index entry.
@return DB_SUCCESS or DB_OUT_OF_FILE_SPACE */
UNIV_INTERN
dberr_t
row_ins_index_entry_big_rec_func(
/*=============================*/
const dtuple_t* entry, /*!< in/out: index entry to insert */
const big_rec_t* big_rec,/*!< in: externally stored fields */
ulint* offsets,/*!< in/out: rec offsets */
mem_heap_t** heap, /*!< in/out: memory heap */
dict_index_t* index, /*!< in: index */
const char* file, /*!< in: file name of caller */
#ifndef DBUG_OFF
const void* thd, /*!< in: connection, or NULL */
#endif /* DBUG_OFF */
ulint line) /*!< in: line number of caller */
{
mtr_t mtr;
btr_cur_t cursor;
rec_t* rec;
dberr_t error;
ut_ad(dict_index_is_clust(index));
DEBUG_SYNC_C_IF_THD(thd, "before_row_ins_extern_latch");
mtr_start(&mtr);
btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_LE,
BTR_MODIFY_TREE, &cursor, 0,
file, line, &mtr);
rec = btr_cur_get_rec(&cursor);
offsets = rec_get_offsets(rec, index, offsets,
ULINT_UNDEFINED, heap);
DEBUG_SYNC_C_IF_THD(thd, "before_row_ins_extern");
error = btr_store_big_rec_extern_fields(
index, btr_cur_get_block(&cursor),
rec, offsets, big_rec, &mtr, BTR_STORE_INSERT);
DEBUG_SYNC_C_IF_THD(thd, "after_row_ins_extern");
if (error == DB_SUCCESS
&& dict_index_is_online_ddl(index)) {
row_log_table_insert(rec, index, offsets);
}
mtr_commit(&mtr);
return(error);
}
/***************************************************************//**
Inserts an entry into a clustered index. Tries first optimistic,
then pessimistic descent down the tree. If the entry matches enough
to a delete marked record, performs the insert by updating or delete
unmarking the delete marked record.
@return DB_SUCCESS, DB_LOCK_WAIT, DB_DUPLICATE_KEY, or some other error code */
UNIV_INTERN
dberr_t
row_ins_clust_index_entry(
/*======================*/
dict_index_t* index, /*!< in: clustered index */
dtuple_t* entry, /*!< in/out: index entry to insert */
que_thr_t* thr, /*!< in: query thread */
ulint n_ext) /*!< in: number of externally stored columns */
{
dberr_t err;
ulint n_uniq;
if (!index->table->foreign_set.empty()) {
err = row_ins_check_foreign_constraints(
index->table, index, entry, thr);
if (err != DB_SUCCESS) {
return(err);
}
}
n_uniq = dict_index_is_unique(index) ? index->n_uniq : 0;
/* Try first optimistic descent to the B-tree */
log_free_check();
err = row_ins_clust_index_entry_low(
0, BTR_MODIFY_LEAF, index, n_uniq, entry, n_ext, thr);
#ifdef UNIV_DEBUG
/* Work around Bug#14626800 ASSERTION FAILURE IN DEBUG_SYNC().
Once it is fixed, remove the 'ifdef', 'if' and this comment. */
if (!thr_get_trx(thr)->ddl) {
DEBUG_SYNC_C_IF_THD(thr_get_trx(thr)->mysql_thd,
"after_row_ins_clust_index_entry_leaf");
}
#endif /* UNIV_DEBUG */
if (err != DB_FAIL) {
DEBUG_SYNC_C("row_ins_clust_index_entry_leaf_after");
return(err);
}
/* Try then pessimistic descent to the B-tree */
log_free_check();
return(row_ins_clust_index_entry_low(
0, BTR_MODIFY_TREE, index, n_uniq, entry, n_ext, thr));
}
/***************************************************************//**
Inserts an entry into a secondary index. Tries first optimistic,
then pessimistic descent down the tree. If the entry matches enough
to a delete marked record, performs the insert by updating or delete
unmarking the delete marked record.
@return DB_SUCCESS, DB_LOCK_WAIT, DB_DUPLICATE_KEY, or some other error code */
UNIV_INTERN
dberr_t
row_ins_sec_index_entry(
/*====================*/
dict_index_t* index, /*!< in: secondary index */
dtuple_t* entry, /*!< in/out: index entry to insert */
que_thr_t* thr) /*!< in: query thread */
{
dberr_t err;
mem_heap_t* offsets_heap;
mem_heap_t* heap;
if (!index->table->foreign_set.empty()) {
err = row_ins_check_foreign_constraints(index->table, index,
entry, thr);
if (err != DB_SUCCESS) {
return(err);
}
}
ut_ad(thr_get_trx(thr)->id);
offsets_heap = mem_heap_create(1024);
heap = mem_heap_create(1024);
/* Try first optimistic descent to the B-tree */
log_free_check();
err = row_ins_sec_index_entry_low(
0, BTR_MODIFY_LEAF, index, offsets_heap, heap, entry, 0, thr);
if (err == DB_FAIL) {
mem_heap_empty(heap);
/* Try then pessimistic descent to the B-tree */
log_free_check();
err = row_ins_sec_index_entry_low(
0, BTR_MODIFY_TREE, index,
offsets_heap, heap, entry, 0, thr);
}
mem_heap_free(heap);
mem_heap_free(offsets_heap);
return(err);
}
/***************************************************************//**
Inserts an index entry to index. Tries first optimistic, then pessimistic
descent down the tree. If the entry matches enough to a delete marked record,
performs the insert by updating or delete unmarking the delete marked
record.
@return DB_SUCCESS, DB_LOCK_WAIT, DB_DUPLICATE_KEY, or some other error code */
static
dberr_t
row_ins_index_entry(
/*================*/
dict_index_t* index, /*!< in: index */
dtuple_t* entry, /*!< in/out: index entry to insert */
que_thr_t* thr) /*!< in: query thread */
{
DBUG_EXECUTE_IF("row_ins_index_entry_timeout", {
DBUG_SET("-d,row_ins_index_entry_timeout");
return(DB_LOCK_WAIT);});
if (dict_index_is_clust(index)) {
return(row_ins_clust_index_entry(index, entry, thr, 0));
} else {
return(row_ins_sec_index_entry(index, entry, thr));
}
}
/***********************************************************//**
Sets the values of the dtuple fields in entry from the values of appropriate
columns in row. */
static __attribute__((nonnull))
void
row_ins_index_entry_set_vals(
/*=========================*/
dict_index_t* index, /*!< in: index */
dtuple_t* entry, /*!< in: index entry to make */
const dtuple_t* row) /*!< in: row */
{
ulint n_fields;
ulint i;
n_fields = dtuple_get_n_fields(entry);
for (i = 0; i < n_fields; i++) {
dict_field_t* ind_field;
dfield_t* field;
const dfield_t* row_field;
ulint len;
field = dtuple_get_nth_field(entry, i);
ind_field = dict_index_get_nth_field(index, i);
row_field = dtuple_get_nth_field(row, ind_field->col->ind);
len = dfield_get_len(row_field);
/* Check column prefix indexes */
if (ind_field->prefix_len > 0
&& dfield_get_len(row_field) != UNIV_SQL_NULL) {
const dict_col_t* col
= dict_field_get_col(ind_field);
len = dtype_get_at_most_n_mbchars(
col->prtype, col->mbminmaxlen,
ind_field->prefix_len,
len,
static_cast<const char*>(
dfield_get_data(row_field)));
ut_ad(!dfield_is_ext(row_field));
}
dfield_set_data(field, dfield_get_data(row_field), len);
if (dfield_is_ext(row_field)) {
ut_ad(dict_index_is_clust(index));
dfield_set_ext(field);
}
}
}
/***********************************************************//**
Inserts a single index entry to the table.
@return DB_SUCCESS if operation successfully completed, else error
code or DB_LOCK_WAIT */
static __attribute__((nonnull, warn_unused_result))
dberr_t
row_ins_index_entry_step(
/*=====================*/
ins_node_t* node, /*!< in: row insert node */
que_thr_t* thr) /*!< in: query thread */
{
dberr_t err;
ut_ad(dtuple_check_typed(node->row));
row_ins_index_entry_set_vals(node->index, node->entry, node->row);
ut_ad(dtuple_check_typed(node->entry));
err = row_ins_index_entry(node->index, node->entry, thr);
#ifdef UNIV_DEBUG
/* Work around Bug#14626800 ASSERTION FAILURE IN DEBUG_SYNC().
Once it is fixed, remove the 'ifdef', 'if' and this comment. */
if (!thr_get_trx(thr)->ddl) {
DEBUG_SYNC_C_IF_THD(thr_get_trx(thr)->mysql_thd,
"after_row_ins_index_entry_step");
}
#endif /* UNIV_DEBUG */
return(err);
}
/***********************************************************//**
Allocates a row id for row and inits the node->index field. */
UNIV_INLINE
void
row_ins_alloc_row_id_step(
/*======================*/
ins_node_t* node) /*!< in: row insert node */
{
row_id_t row_id;
ut_ad(node->state == INS_NODE_ALLOC_ROW_ID);
if (dict_index_is_unique(dict_table_get_first_index(node->table))) {
/* No row id is stored if the clustered index is unique */
return;
}
/* Fill in row id value to row */
row_id = dict_sys_get_new_row_id();
dict_sys_write_row_id(node->row_id_buf, row_id);
}
/***********************************************************//**
Gets a row to insert from the values list. */
UNIV_INLINE
void
row_ins_get_row_from_values(
/*========================*/
ins_node_t* node) /*!< in: row insert node */
{
que_node_t* list_node;
dfield_t* dfield;
dtuple_t* row;
ulint i;
/* The field values are copied in the buffers of the select node and
it is safe to use them until we fetch from select again: therefore
we can just copy the pointers */
row = node->row;
i = 0;
list_node = node->values_list;
while (list_node) {
eval_exp(list_node);
dfield = dtuple_get_nth_field(row, i);
dfield_copy_data(dfield, que_node_get_val(list_node));
i++;
list_node = que_node_get_next(list_node);
}
}
/***********************************************************//**
Gets a row to insert from the select list. */
UNIV_INLINE
void
row_ins_get_row_from_select(
/*========================*/
ins_node_t* node) /*!< in: row insert node */
{
que_node_t* list_node;
dfield_t* dfield;
dtuple_t* row;
ulint i;
/* The field values are copied in the buffers of the select node and
it is safe to use them until we fetch from select again: therefore
we can just copy the pointers */
row = node->row;
i = 0;
list_node = node->select->select_list;
while (list_node) {
dfield = dtuple_get_nth_field(row, i);
dfield_copy_data(dfield, que_node_get_val(list_node));
i++;
list_node = que_node_get_next(list_node);
}
}
/***********************************************************//**
Inserts a row to a table.
@return DB_SUCCESS if operation successfully completed, else error
code or DB_LOCK_WAIT */
static __attribute__((nonnull, warn_unused_result))
dberr_t
row_ins(
/*====*/
ins_node_t* node, /*!< in: row insert node */
que_thr_t* thr) /*!< in: query thread */
{
dberr_t err;
if (node->state == INS_NODE_ALLOC_ROW_ID) {
row_ins_alloc_row_id_step(node);
node->index = dict_table_get_first_index(node->table);
node->entry = UT_LIST_GET_FIRST(node->entry_list);
if (node->ins_type == INS_SEARCHED) {
row_ins_get_row_from_select(node);
} else if (node->ins_type == INS_VALUES) {
row_ins_get_row_from_values(node);
}
node->state = INS_NODE_INSERT_ENTRIES;
}
ut_ad(node->state == INS_NODE_INSERT_ENTRIES);
while (node->index != NULL) {
if (node->index->type != DICT_FTS) {
err = row_ins_index_entry_step(node, thr);
if (err != DB_SUCCESS) {
return(err);
}
}
node->index = dict_table_get_next_index(node->index);
node->entry = UT_LIST_GET_NEXT(tuple_list, node->entry);
DBUG_EXECUTE_IF(
"row_ins_skip_sec",
node->index = NULL; node->entry = NULL; break;);
/* Skip corrupted secondary index and its entry */
while (node->index && dict_index_is_corrupted(node->index)) {
node->index = dict_table_get_next_index(node->index);
node->entry = UT_LIST_GET_NEXT(tuple_list, node->entry);
}
}
ut_ad(node->entry == NULL);
node->state = INS_NODE_ALLOC_ROW_ID;
return(DB_SUCCESS);
}
/***********************************************************//**
Inserts a row to a table. This is a high-level function used in SQL execution
graphs.
@return query thread to run next or NULL */
UNIV_INTERN
que_thr_t*
row_ins_step(
/*=========*/
que_thr_t* thr) /*!< in: query thread */
{
ins_node_t* node;
que_node_t* parent;
sel_node_t* sel_node;
trx_t* trx;
dberr_t err;
ut_ad(thr);
trx = thr_get_trx(thr);
trx_start_if_not_started_xa(trx);
node = static_cast<ins_node_t*>(thr->run_node);
ut_ad(que_node_get_type(node) == QUE_NODE_INSERT);
parent = que_node_get_parent(node);
sel_node = node->select;
if (thr->prev_node == parent) {
node->state = INS_NODE_SET_IX_LOCK;
}
/* If this is the first time this node is executed (or when
execution resumes after wait for the table IX lock), set an
IX lock on the table and reset the possible select node. MySQL's
partitioned table code may also call an insert within the same
SQL statement AFTER it has used this table handle to do a search.
This happens, for example, when a row update moves it to another
partition. In that case, we have already set the IX lock on the
table during the search operation, and there is no need to set
it again here. But we must write trx->id to node->trx_id_buf. */
trx_write_trx_id(node->trx_id_buf, trx->id);
if (node->state == INS_NODE_SET_IX_LOCK) {
node->state = INS_NODE_ALLOC_ROW_ID;
/* It may be that the current session has not yet started
its transaction, or it has been committed: */
if (trx->id == node->trx_id) {
/* No need to do IX-locking */
goto same_trx;
}
err = lock_table(0, node->table, LOCK_IX, thr);
DBUG_EXECUTE_IF("ib_row_ins_ix_lock_wait",
err = DB_LOCK_WAIT;);
if (err != DB_SUCCESS) {
goto error_handling;
}
node->trx_id = trx->id;
same_trx:
if (node->ins_type == INS_SEARCHED) {
/* Reset the cursor */
sel_node->state = SEL_NODE_OPEN;
/* Fetch a row to insert */
thr->run_node = sel_node;
return(thr);
}
}
if ((node->ins_type == INS_SEARCHED)
&& (sel_node->state != SEL_NODE_FETCH)) {
ut_ad(sel_node->state == SEL_NODE_NO_MORE_ROWS);
/* No more rows to insert */
thr->run_node = parent;
return(thr);
}
/* DO THE CHECKS OF THE CONSISTENCY CONSTRAINTS HERE */
err = row_ins(node, thr);
error_handling:
trx->error_state = err;
if (err != DB_SUCCESS) {
/* err == DB_LOCK_WAIT or SQL error detected */
return(NULL);
}
/* DO THE TRIGGER ACTIONS HERE */
if (node->ins_type == INS_SEARCHED) {
/* Fetch a row to insert */
thr->run_node = sel_node;
} else {
thr->run_node = que_node_get_parent(node);
}
return(thr);
}
| 27.433462 | 79 | 0.672639 | [
"object",
"vector"
] |
a1e0ffc1b0de98d52524f5825919fe83ba67d080 | 11,759 | cpp | C++ | firmware/src/foc/foc.cpp | zenglongGH/px4esc | b12adc96a180503c75856220cfe8539cb24204cc | [
"BSD-3-Clause"
] | 1 | 2021-08-07T22:27:54.000Z | 2021-08-07T22:27:54.000Z | firmware/src/foc/foc.cpp | zenglongGH/px4esc | b12adc96a180503c75856220cfe8539cb24204cc | [
"BSD-3-Clause"
] | null | null | null | firmware/src/foc/foc.cpp | zenglongGH/px4esc | b12adc96a180503c75856220cfe8539cb24204cc | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2016 Zubax Robotics OU <info@zubax.com>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "foc.hpp"
#include "transforms.hpp"
#include "voltage_modulator.hpp"
#include "irq_debug.hpp"
// Tasks:
#include "idle_task.hpp"
#include "fault_task.hpp"
#include "beeping_task.hpp"
#include "running_task.hpp"
#include "hw_test/task.hpp"
#include "motor_id/task.hpp"
#include <unistd.h>
/*
* Documents:
* - http://cache.nxp.com/files/microcontrollers/doc/ref_manual/DRM148.pdf
*/
namespace foc
{
namespace
{
chibios_rt::Mutex g_mutex;
TaskContext g_context;
board::motor::PWMHandle g_pwm_handle;
IRQDebugPlotter g_debug_plotter;
using motor_id::MotorIdentificationTask;
using hw_test::HardwareTestingTask;
typedef TaskHandler
< IdleTask
, FaultTask
, BeepingTask
, RunningTask
, HardwareTestingTask
, MotorIdentificationTask
> TaskHandlerInstance;
TaskHandlerInstance g_task_handler([]() { return g_context; });
inline Scalar convertElectricalAngularVelocityToMechanicalRPM(Const eangvel)
{
return convertRotationRateElectricalToMechanical(convertAngularVelocityToRPM(eangvel),
g_context.params.motor.num_poles);
}
class Thread : public chibios_rt::BaseStaticThread<2048>
{
static constexpr float WatchdogTimeout = 2.0F;
mutable os::watchdog::Timer watchdog_;
volatile bool plotting_enabled_ = false;
static os::Logger& getLogger()
{
static os::Logger logger("FOC");
return logger;
}
void main() override
{
watchdog_.startMSec(unsigned(WatchdogTimeout * 1e3F));
setName("foc_logger");
IRQDebugOutputBuffer::addOutputCallback([](const char* s) { getLogger().println("IRQ: %s", s); });
getLogger().puts("Started");
while (!os::isRebootRequested())
{
watchdog_.reset();
{
os::MutexLocker ml(g_mutex);
IRQDebugOutputBuffer::poll();
if (plotting_enabled_)
{
g_debug_plotter.print();
}
else
{
::usleep(10000);
}
}
}
getLogger().puts("Goodbye");
}
public:
virtual ~Thread() { }
void setPlottingEnabled(bool x)
{
plotting_enabled_ = x;
}
} g_thread;
} // namespace
void init(const Parameters& params)
{
os::MutexLocker ml(g_mutex);
board::motor::beginCalibration();
g_context.params = params;
g_context.board.pwm = board::motor::getPWMParameters();
g_context.board.limits = board::motor::getLimits();
{
AbsoluteCriticalSectionLocker locker;
g_task_handler.select<IdleTask>();
}
g_thread.start(LOWPRIO);
DEBUG_LOG("FOC sizeof: %u %u %u %u\n",
sizeof(g_task_handler), sizeof(MotorIdentificationTask), sizeof(g_context), sizeof(g_context.params));
}
void setParameters(const Parameters& params)
{
AbsoluteCriticalSectionLocker locker;
g_context.params = params;
g_task_handler.from<IdleTask>().to<IdleTask>(); // Cycling to reload new configuration and check it
}
Parameters getParameters()
{
AbsoluteCriticalSectionLocker locker;
return g_context.params;
}
MotorParameters getMotorParameters()
{
AbsoluteCriticalSectionLocker locker;
return g_context.params.motor;
}
hw_test::Report getHardwareTestReport()
{
AbsoluteCriticalSectionLocker locker;
return g_context.hw_test_report;
}
void beginMotorIdentification(motor_id::Mode mode)
{
g_task_handler.from<IdleTask, BeepingTask, FaultTask>().to<MotorIdentificationTask>(mode);
}
void beginHardwareTest()
{
g_task_handler.from<IdleTask, BeepingTask, FaultTask>().to<HardwareTestingTask>();
}
bool isMotorIdentificationInProgress(MotorIdentificationStateInfo* out_info)
{
if (out_info != nullptr)
{
AbsoluteCriticalSectionLocker locker;
if (auto task = g_task_handler.as<MotorIdentificationTask>())
{
out_info->progress = task->getProgress();
out_info->inverter_power_filtered = 0;
out_info->mechanical_rpm = 0;
return true;
}
return false;
}
else
{
return g_task_handler.is<MotorIdentificationTask>();
}
}
bool isHardwareTestInProgress()
{
return g_task_handler.is<HardwareTestingTask>();
}
bool isRunning(RunningStateInfo* out_info,
bool* out_spinup_in_progress)
{
AbsoluteCriticalSectionLocker locker;
if (auto task = g_task_handler.as<RunningTask>())
{
if (out_info != nullptr)
{
out_info->stall_count = task->getNumSuccessiveStalls();
const auto filt = task->getLowPassFilteredValues();
out_info->inverter_power_filtered = filt.inverter_power;
out_info->demand_factor_filtered = filt.demand_factor;
out_info->mechanical_rpm =
convertElectricalAngularVelocityToMechanicalRPM(task->getElectricalAngularVelocity());
}
if (out_spinup_in_progress != nullptr)
{
*out_spinup_in_progress = task->isSpinupInProgress();
}
return true;
}
return false;
}
bool isInactive(InactiveStateInfo* out_info)
{
AbsoluteCriticalSectionLocker locker;
if (g_task_handler.either<IdleTask, BeepingTask, FaultTask>())
{
if (out_info != nullptr)
{
if (auto task = g_task_handler.as<FaultTask>())
{
out_info->fault_code = task->getFaultCode();
}
else
{
out_info->fault_code = 0;
}
}
return true;
}
return false;
}
ExtendedStatus getExtendedStatus()
{
AbsoluteCriticalSectionLocker locker;
return {
g_task_handler.get().getName(),
g_task_handler.getTaskSwitchCounter()
};
}
void setSetpoint(ControlMode control_mode,
Const value,
Const request_ttl)
{
AbsoluteCriticalSectionLocker locker;
if (auto task = g_task_handler.as<RunningTask>())
{
task->setSetpoint(control_mode, value, request_ttl);
}
else
{
if (os::float_eq::closeToZero(value))
{
g_pwm_handle.release(); // This helps to avoid holding long critical sections with activated power stage
g_task_handler.from<FaultTask, MotorIdentificationTask>().to<IdleTask>();
}
else
{
g_task_handler.from<IdleTask, BeepingTask>().to<RunningTask>(control_mode, value, request_ttl);
}
}
}
void beep(Const frequency, Const duration)
{
g_task_handler.from<IdleTask>().to<BeepingTask>(frequency, duration);
}
void addLogSink(const std::function<void (const char*)>& sink)
{
os::MutexLocker ml(g_mutex);
IRQDebugOutputBuffer::addOutputCallback(sink);
}
void setPlottingEnabled(bool en)
{
g_thread.setPlottingEnabled(en);
}
std::array<DebugKeyValueType, NumDebugKeyValuePairs> getDebugKeyValuePairs()
{
bool match = false;
{
Vector<2> Idq;
Vector<2> Udq;
{
AbsoluteCriticalSectionLocker locker;
if (auto task = g_task_handler.as<RunningTask>())
{
match = true;
Idq = task->getIdq();
Udq = task->getUdq();
}
}
if (match)
{
return {
DebugKeyValueType("Id", Idq[0]),
DebugKeyValueType("Iq", Idq[1]),
DebugKeyValueType("Ud", Udq[0]),
DebugKeyValueType("Uq", Udq[1])
};
}
}
// Getters for other tasks may be added later
return {};
}
}
namespace board
{
namespace motor
{
using namespace foc;
void handleMainIRQ(Const period)
{
const auto hw_status = board::motor::getStatus();
static TaskHandlerInstance::SwitchCounter last_task_switch_counter;
const auto new_task_switch_counter = g_task_handler.getTaskSwitchCounter();
if (new_task_switch_counter != last_task_switch_counter)
{
AbsoluteCriticalSectionLocker locker;
last_task_switch_counter = new_task_switch_counter;
// OK we just switched task, cool.
if (g_task_handler.get().isPreCalibrationRequired())
{
g_pwm_handle.release();
board::motor::beginCalibration();
}
}
if (!board::motor::isCalibrationInProgress())
{
auto& task = g_task_handler.get();
const auto result = task.onMainIRQ(period, hw_status);
if (result.finished)
{
AbsoluteCriticalSectionLocker locker;
g_pwm_handle.release();
task.applyResultToGlobalContext(g_context);
if (result.exit_code == result.ExitCodeOK)
{
assert(!g_task_handler.is<IdleTask>()); // Idle task shouldn't finish
g_task_handler.select<IdleTask>();
}
else
{
assert(!g_task_handler.is<FaultTask>()); // Fault task shouldn't fail
// Fault code consists of the task ID (takes the upper 4 bits) and its failure code (lower bits)
const auto fault_code =
std::uint16_t((g_task_handler.getTaskID() << 12) | (result.exit_code & 0x0FFFU));
g_task_handler.select<FaultTask>(fault_code);
}
}
else
{
std::array<Scalar, ITask::NumDebugVariables> vars;
{
AbsoluteCriticalSectionLocker locker;
vars = task.getDebugVariables();
}
g_debug_plotter.set(vars);
}
}
}
void handleFastIRQ(const Vector<2>& phase_currents_ab,
Const inverter_voltage)
{
if (board::motor::isCalibrationInProgress())
{
g_pwm_handle.release();
}
else
{
const auto out = g_task_handler.get().onNextPWMPeriod(phase_currents_ab, inverter_voltage);
if (out.second)
{
g_pwm_handle.setPWM(out.first);
}
else
{
g_pwm_handle.release();
}
}
}
}
}
| 26.544018 | 118 | 0.636874 | [
"vector"
] |
a1e90446116f481a4066ac77a24372a843af257e | 10,254 | cpp | C++ | mutator.cpp | richinseattle/haze | b307b6ffca326f1211f4355668ab31eeedc77f67 | [
"Apache-2.0"
] | 47 | 2020-09-27T01:46:05.000Z | 2021-07-27T04:48:11.000Z | mutator.cpp | richinseattle/haze-tinyinst | b307b6ffca326f1211f4355668ab31eeedc77f67 | [
"Apache-2.0"
] | 2 | 2020-10-31T20:05:33.000Z | 2020-12-26T03:49:46.000Z | mutator.cpp | richinseattle/haze | b307b6ffca326f1211f4355668ab31eeedc77f67 | [
"Apache-2.0"
] | 7 | 2020-09-27T11:17:29.000Z | 2021-05-01T21:17:33.000Z | /*
Copyright 2020 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "common.h"
#include "mutator.h"
int Mutator::GetRandBlock(size_t samplesize, size_t minblocksize, size_t maxblocksize, size_t *blockstart, size_t *blocksize, PRNG *prng) {
if (samplesize == 0) return 0;
if (samplesize < minblocksize) return 0;
if (samplesize < maxblocksize) maxblocksize = samplesize;
*blocksize = prng->Rand((int)minblocksize, (int)maxblocksize);
*blockstart = prng->Rand(0, (int)(samplesize - (*blocksize)));
return 1;
}
bool ByteFlipMutator::Mutate(Sample *inout_sample, PRNG *prng, std::vector<Sample *> &all_samples) {
// printf("In ByteFlipMutator::Mutate\n");
if (inout_sample->size == 0) return true;
int charpos = prng->Rand(0, (int)(inout_sample->size - 1));
char c = (char)prng->Rand(0, 255);
inout_sample->bytes[charpos] = c;
return true;
}
bool BlockFlipMutator::Mutate(Sample *inout_sample, PRNG *prng, std::vector<Sample *> &all_samples) {
// printf("In BlockFlipMutator::Mutate\n");
size_t blocksize, blockpos;
if (!GetRandBlock(inout_sample->size, min_block_size, max_block_size, &blockpos, &blocksize, prng)) return true;
if (uniform) {
char c = (char)prng->Rand(0, 255);
for (size_t i = 0; i<blocksize; i++) {
inout_sample->bytes[blockpos + i] = c;
}
} else {
for (size_t i = 0; i<blocksize; i++) {
inout_sample->bytes[blockpos + i] = (char)prng->Rand(0, 255);
}
}
return true;
}
bool AppendMutator::Mutate(Sample *inout_sample, PRNG *prng, std::vector<Sample *> &all_samples) {
// printf("In AppendMutator::Mutate\n");
size_t old_size = inout_sample->size;
if (old_size >= MAX_SAMPLE_SIZE) return true;
size_t append = prng->Rand(min_append, max_append);
if ((old_size + append) > MAX_SAMPLE_SIZE) {
append = MAX_SAMPLE_SIZE - old_size;
}
if (append <= 0) return true;
size_t new_size = old_size + append;
inout_sample->bytes =
(char *)realloc(inout_sample->bytes, new_size);
inout_sample->size = new_size;
for (size_t i = old_size; i < new_size; i++) {
inout_sample->bytes[i] = (char)prng->Rand(0, 255);
}
return true;
}
bool BlockInsertMutator::Mutate(Sample *inout_sample, PRNG *prng, std::vector<Sample *> &all_samples) {
// printf("In BlockInsertMutator::Mutate\n");
size_t old_size = inout_sample->size;
if (old_size >= MAX_SAMPLE_SIZE) return true;
size_t to_insert = prng->Rand(min_insert, max_insert);
if ((old_size + to_insert) > MAX_SAMPLE_SIZE) {
to_insert = MAX_SAMPLE_SIZE - old_size;
}
size_t where = prng->Rand(0, (int)old_size);
size_t new_size = old_size + to_insert;
if (to_insert <= 0) return true;
char *old_bytes = inout_sample->bytes;
char *new_bytes = (char *)malloc(new_size);
memcpy(new_bytes, old_bytes, where);
for (size_t i = 0; i < to_insert; i++) {
new_bytes[where + i] = (char)prng->Rand(0, 255);
}
memcpy(new_bytes + where + to_insert, old_bytes + where, old_size - where);
if (old_bytes) free(old_bytes);
inout_sample->bytes = new_bytes;
inout_sample->size = new_size;
return true;
}
bool BlockDuplicateMutator::Mutate(Sample *inout_sample, PRNG *prng, std::vector<Sample *> &all_samples) {
// printf("In BlockDuplicateMutator::Mutate\n");
if (inout_sample->size >= MAX_SAMPLE_SIZE) return true;
size_t blockpos, blocksize;
if (!GetRandBlock(inout_sample->size, min_block_size, max_block_size, &blockpos, &blocksize, prng)) return true;
int64_t blockcount = prng->Rand(min_duplicate_cnt, max_duplicate_cnt);
if ((inout_sample->size + blockcount * blocksize) > MAX_SAMPLE_SIZE)
blockcount = (MAX_SAMPLE_SIZE - (int64_t)inout_sample->size) / blocksize;
if (blockcount <= 0) return true;
char *newbytes;
newbytes = (char *)malloc(inout_sample->size + blockcount * blocksize);
memcpy(newbytes, inout_sample->bytes, blockpos + blocksize);
for (size_t i = 0; i<blockcount; i++) {
memcpy(newbytes + blockpos + (i + 1)*blocksize, inout_sample->bytes + blockpos, blocksize);
}
memcpy(newbytes + blockpos + (blockcount + 1)*blocksize,
inout_sample->bytes + blockpos + blocksize,
inout_sample->size - blockpos - blocksize);
if (inout_sample->bytes) free(inout_sample->bytes);
inout_sample->bytes = newbytes;
inout_sample->size = inout_sample->size + blockcount * blocksize;
return true;
}
void InterstingValueMutator::AddInterestingValue(char *data, size_t size) {
Sample interesting_sample;
interesting_sample.Init(data, size);
interesting_values.push_back(interesting_sample);
}
bool InterstingValueMutator::Mutate(Sample *inout_sample, PRNG *prng, std::vector<Sample *> &all_samples) {
// printf("In InterstingValueMutator::Mutate\n");
if (interesting_values.empty()) return true;
Sample *interesting_sample = &interesting_values[prng->Rand(0, (int)interesting_values.size() - 1)];
size_t blockstart, blocksize;
if (!GetRandBlock(inout_sample->size, interesting_sample->size, interesting_sample->size, &blockstart, &blocksize, prng)) return true;
memcpy(inout_sample->bytes + blockstart, interesting_sample->bytes, interesting_sample->size);
return true;
}
InterstingValueMutator::InterstingValueMutator(bool use_default_values) {
if (!use_default_values) return;
uint16_t i_word;
i_word = 0; AddInterestingValue((char *)(&i_word), sizeof(i_word));
i_word = 0xFFFF; AddInterestingValue((char *)(&i_word), sizeof(i_word));
i_word = 1;
for (int i = 0; i < 16; i++) {
AddInterestingValue((char *)(&i_word), sizeof(i_word));
i_word = (i_word << 1);
}
uint32_t i_dword;
i_dword = 0; AddInterestingValue((char *)(&i_dword), sizeof(i_dword));
i_dword = 0xFFFFFFFF; AddInterestingValue((char *)(&i_dword), sizeof(i_dword));
i_dword = 1;
for (int i = 0; i < 16; i++) {
AddInterestingValue((char *)(&i_dword), sizeof(i_dword));
i_dword = (i_dword << 1);
}
uint64_t i_qword;
i_qword = 0; AddInterestingValue((char *)(&i_qword), sizeof(i_qword));
i_qword = 0xFFFFFFFFFFFFFFFF; AddInterestingValue((char *)(&i_qword), sizeof(i_qword));
i_qword = 1;
for (int i = 0; i < 16; i++) {
AddInterestingValue((char *)(&i_qword), sizeof(i_qword));
i_qword = (i_qword << 1);
}
}
bool SpliceMutator::Mutate(Sample *inout_sample, PRNG *prng, std::vector<Sample *> &all_samples) {
if(all_samples.empty()) return true;
bool displace = false;
if(prng->RandReal() < displacement_p) {
displace = true;
}
Sample *other_sample = all_samples[prng->Rand(0, (int)all_samples.size() - 1)];
if(inout_sample->size == 0) return false;
if(other_sample->size == 0) return false;
if(points == 1) {
size_t point1, point2;
char *new_bytes;
size_t new_sample_size;
if(displace) {
point1 = prng->Rand(0, (int)(inout_sample->size - 1));
point2 = prng->Rand(0, (int)(other_sample->size - 1));
} else {
size_t minsize = inout_sample->size;
if(other_sample->size < minsize) minsize = other_sample->size;
point1 = prng->Rand(0, (int)(minsize - 1));
point2 = point1;
}
new_sample_size = point1 + (other_sample->size - point2);
if(new_sample_size == inout_sample->size) {
memcpy(inout_sample->bytes + point1, other_sample->bytes + point2, other_sample->size - point2);
return true;
} else {
new_bytes = (char *)malloc(new_sample_size);
memcpy(new_bytes, inout_sample->bytes, point1);
memcpy(new_bytes + point1, other_sample->bytes + point2, other_sample->size - point2);
free(inout_sample->bytes);
inout_sample->bytes = new_bytes;
inout_sample->size = new_sample_size;
if (inout_sample->size > MAX_SAMPLE_SIZE) inout_sample->Trim(MAX_SAMPLE_SIZE);
return true;
}
} else if(points != 2) {
FATAL("Splice mutator can only work with 1 or 2 splice points");
}
if(displace) {
size_t blockstart1, blocksize1;
size_t blockstart2, blocksize2;
size_t blockstart3, blocksize3;
if(!GetRandBlock(inout_sample->size, 1, inout_sample->size, &blockstart1, &blocksize1, prng)) return true;
if(!GetRandBlock(other_sample->size, 1, other_sample->size, &blockstart2, &blocksize2, prng)) return true;
blockstart3 = blockstart1 + blocksize1;
blocksize3 = inout_sample->size - blockstart3;
size_t new_sample_size = blockstart1 + blocksize2 + blocksize3;
char *new_bytes = (char *)malloc(new_sample_size);
memcpy(new_bytes, inout_sample->bytes, blockstart1);
memcpy(new_bytes + blockstart1, other_sample->bytes + blockstart2, blocksize2);
memcpy(new_bytes + blockstart1 + blocksize2, inout_sample->bytes + blockstart3, blocksize3);
if(new_sample_size > MAX_SAMPLE_SIZE) {
new_sample_size = MAX_SAMPLE_SIZE;
new_bytes = (char *)realloc(new_bytes, MAX_SAMPLE_SIZE);
}
free(inout_sample->bytes);
inout_sample->bytes = new_bytes;
inout_sample->size = new_sample_size;
return true;
} else {
size_t blockstart, blocksize;
if(!GetRandBlock(other_sample->size, 2, other_sample->size, &blockstart, &blocksize, prng)) return true;
if(blockstart > inout_sample->size) {
blocksize += (blockstart - inout_sample->size);
blockstart = inout_sample->size;
}
if((blockstart + blocksize) <= inout_sample->size) {
memcpy(inout_sample->bytes + blockstart, other_sample->bytes + blockstart, blocksize);
return true;
}
size_t new_sample_size = blockstart + blocksize;
char *new_bytes = (char *)malloc(new_sample_size);
memcpy(new_bytes, inout_sample->bytes, blockstart);
memcpy(new_bytes + blockstart, other_sample->bytes + blockstart, blocksize);
free(inout_sample->bytes);
inout_sample->bytes = new_bytes;
inout_sample->size = new_sample_size;
return true;
}
}
| 40.054688 | 139 | 0.696216 | [
"vector"
] |
a1ebc620aa23b7a98cae19371fefd2377c036931 | 4,675 | cpp | C++ | src/served/net/server.cpp | csfilehub/served | 7b0f68902a9044cf45701c34bea0dcc1d52e3730 | [
"MIT"
] | 434 | 2015-01-14T09:25:57.000Z | 2018-06-28T14:15:26.000Z | src/served/net/server.cpp | csfilehub/served | 7b0f68902a9044cf45701c34bea0dcc1d52e3730 | [
"MIT"
] | 34 | 2018-07-02T22:32:28.000Z | 2021-01-17T01:42:44.000Z | src/served/net/server.cpp | csfilehub/served | 7b0f68902a9044cf45701c34bea0dcc1d52e3730 | [
"MIT"
] | 113 | 2018-07-23T19:18:45.000Z | 2022-03-03T14:55:36.000Z | /*
* Copyright (C) 2014 MediaSift Ltd.
*
* 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 <signal.h>
#include <utility>
#include <thread>
#include <served/net/server.hpp>
using namespace served;
using namespace served::net;
server::server( const std::string & address
, const std::string & port
, multiplexer & mux
, bool register_signals /* = true */
)
: _io_service()
, _signals(_io_service)
, _acceptor(_io_service)
, _connection_manager()
, _socket(_io_service)
, _request_handler(mux)
, _read_timeout(0)
, _write_timeout(0)
, _req_max_bytes(0)
{
/*
* Register to handle the signals that indicate when the server should exit.
* It is safe to register for the same signal multiple times in a program,
* provided all registration for the specified signal is made through Asio.
*/
if ( register_signals ) {
_signals.add(SIGINT);
_signals.add(SIGTERM);
#if defined(SIGQUIT)
_signals.add(SIGQUIT);
#endif // defined(SIGQUIT)
}
do_await_stop();
// Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR).
boost::asio::ip::tcp::resolver resolver(_io_service);
boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve({address, port});
_acceptor.open(endpoint.protocol());
_acceptor.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
_acceptor.bind(endpoint);
_acceptor.listen();
do_accept();
}
void
server::run(int n_threads /* = 1 */, bool block /* = true */)
{
/*
* The io_service::run() call will block until all asynchronous operations
* have finished. While the server is running, there is always at least one
* asynchronous operation outstanding: the asynchronous accept call waiting
* for new incoming connections.
*/
if ( n_threads > 1 )
{
std::vector<std::thread> v_threads;
for ( int i = 0; i < n_threads; i++ )
{
v_threads.push_back(std::thread([this](){
_io_service.run();
}));
}
for ( auto & thread : v_threads )
{
if ( block )
{
if ( thread.joinable() )
{
thread.join();
}
}
else
{
thread.detach();
}
}
}
else
{
_io_service.run();
}
}
void
server::set_read_timeout(int time_milliseconds)
{
_read_timeout = time_milliseconds;
}
void
server::set_write_timeout(int time_milliseconds)
{
_write_timeout = time_milliseconds;
}
void
server::set_max_request_bytes(size_t num_bytes)
{
_req_max_bytes = num_bytes;
}
void
server::stop()
{
if ( ! _io_service.stopped() )
{
_io_service.stop();
}
}
void
server::do_accept()
{
_acceptor.async_accept(_socket,
[this](boost::system::error_code ec) {
// Check whether the server was stopped by a signal before this
// completion handler had a chance to run.
if (!_acceptor.is_open())
{
return;
}
if (!ec)
{
_connection_manager.start(
std::make_shared<connection>( _io_service
, std::move(_socket)
, _connection_manager
, _request_handler
, _req_max_bytes
, _read_timeout
, _write_timeout
));
}
do_accept();
}
);
}
void
server::do_await_stop()
{
_signals.async_wait(
[this](boost::system::error_code /*ec*/, int /*signo*/) {
/* The server is stopped by cancelling all outstanding asynchronous
* operations. Once all operations have finished the io_service::run()
* call will exit.
*/
_acceptor.close();
_connection_manager.stop_all();
});
}
| 25.828729 | 81 | 0.658182 | [
"vector"
] |
a1ef06b4d3dd399a8d4dc176ed5bb3303bc63cfb | 11,716 | cc | C++ | tensorflow/compiler/plugin/poplar/driver/passes/serialize_gradient_accumulation.cc | DebeshJha/tensorflow-1 | 2b5a225c49d25273532d11c424d37ce394d7579a | [
"Apache-2.0"
] | 2 | 2021-03-08T23:32:06.000Z | 2022-01-13T03:43:49.000Z | tensorflow/compiler/plugin/poplar/driver/passes/serialize_gradient_accumulation.cc | DebeshJha/tensorflow-1 | 2b5a225c49d25273532d11c424d37ce394d7579a | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/plugin/poplar/driver/passes/serialize_gradient_accumulation.cc | DebeshJha/tensorflow-1 | 2b5a225c49d25273532d11c424d37ce394d7579a | [
"Apache-2.0"
] | null | null | null | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/plugin/poplar/driver/passes/serialize_gradient_accumulation.h"
#include <memory>
#include <queue>
#include <vector>
#include "tensorflow/compiler/plugin/poplar/driver/passes/slice_optimizer.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/custom_ops/stateful_gradient_accumulate.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/inplace_util.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/matcher_predicates.h"
#include "tensorflow/compiler/plugin/poplar/driver/tools/util.h"
#include "tensorflow/compiler/xla/service/call_graph.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_creation_utils.h"
#include "tensorflow/compiler/xla/service/hlo_reachability.h"
#include "tensorflow/compiler/xla/service/pattern_matcher.h"
namespace xla {
namespace m = match;
namespace poplarplugin {
namespace {
constexpr char kFusionName[] = "_pop_op_serialized_gradient_accumulation";
Status ConvertGradientAccumulatorAdd(HloInstruction* inst) {
HloComputation* comp = inst->parent();
// Convert the GradientAccumulatorAdd into a normal add.
HloInstruction* accumulator = inst->mutable_operand(0);
HloInstruction* to_serialize = inst->mutable_operand(1);
TF_ASSIGN_OR_RETURN(
HloInstruction * add,
MakeBinaryHlo(HloOpcode::kAdd, accumulator, to_serialize));
inst->SetupDerivedInstruction(add);
TF_RETURN_IF_ERROR(comp->ReplaceInstruction(inst, add));
if (add->user_count() != 1) {
return FailedPrecondition(
"Expected the gradient accumulation buffer to have a single user.");
}
HloInstruction* accumulator_user = add->users()[0];
// Try and serialize the gradient accumulation application.
HloInstruction* output = add;
while (output != accumulator) {
// When trying to serialize the gradients, handle the following
// patterns:
// ( 1) Add(a, MultiUpdateAdd(b, c, idx)) =>
// MultiUpdateAdd(Add(a, b), c, idx)
// ( 2) Add(a, Concat(b, c, ...)) =>
// SliceApply(SliceApply(a, b), c) ...
// ( 3) Add(a, Multiply(Concat(b, c, ...), Broadcast(d)) =>
// SliceApplyabY(SliceApplyabY(a, b, d), c, d) ...
// ( 4) Add(a, Add(b, c)) =>
// Add(Add(a, b), c)
// ( 5) Add(a, 0) =>
// a
// Following patterns also handle the RHS being a transpose.
// ( 6) Add(a, Transpose(Concat(b, c, ...))) =>
// Add(a, Concat(Transpose(b), Transpose(c), ...)
// ( 7) Add(a, Transpose(Multiply(Concat(b, c, ...), Broadcast(d))) =>
// Add(a, Multiply(Concat(Transpose(b), Transpose(c), ...),
// Broadcast(d))
// ( 8) Add(a, Transpose(Add(b, c))) =>
// Add(a, Add(Transpose(b), Transpose(c)))
// These patterns try and move the transpose so that patterns 1-5 can be
// applied.
// Note that all these patterns keep the accumulator ('a') on the LHS.
// TODO(T20227) support `Add(a, Transpose(MultiUpdateAdd(b, c, idx)))`.
HloInstruction* lhs = output->mutable_operand(0);
HloInstruction* rhs = output->mutable_operand(1);
// Skip if rhs has more than a single user.
if (rhs->user_count() > 1) {
output = lhs;
continue;
}
if (IsPoplarInstruction(PoplarOp::MultiUpdateAdd)(rhs)) {
// Case 1:
// Add(lhs, MultiUpdateAdd(b, ...)) =>
// MultiUpdateAdd(Add(lhs, b), ...)
HloInstruction* b = rhs->mutable_operand(0);
TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, b));
TF_RETURN_IF_ERROR(rhs->ReplaceOperandWith(0, output));
TF_RETURN_IF_ERROR(output->ReplaceAllUsesWith(rhs));
} else if (rhs->opcode() == HloOpcode::kConcatenate) {
// Case 2:
// Add(lhs, Concat(b, c, ...)) =>
// SliceApply(SliceApply(lhs, b), c) ...
TF_ASSIGN_OR_RETURN(
HloInstruction * new_output,
SliceOptimizer::ConvertToSliceApply(HloOpcode::kAdd, lhs, rhs));
TF_RETURN_IF_ERROR(comp->ReplaceInstruction(output, new_output));
output = lhs;
} else if (Match(rhs, m::Multiply(m::Concatenate(),
m::Broadcast(m::ConstantScalar())))) {
// Case 3:
// Add(a, Multiply(Concat(b, c, ...), Broadcast(d)) =>
// SliceApplyabY(SliceApplyabY(a, b, d), c, d)
HloInstruction* mul = rhs;
HloInstruction* concat = mul->mutable_operand(0);
HloInstruction* scalar = mul->mutable_operand(1)->mutable_operand(0);
TF_ASSIGN_OR_RETURN(HloInstruction * new_output,
SliceOptimizer::ConvertToSliceApplyabY(
HloOpcode::kAdd, lhs, concat, scalar));
TF_RETURN_IF_ERROR(comp->ReplaceInstruction(output, new_output));
output = lhs;
} else if (rhs->opcode() == HloOpcode::kAdd) {
// Case 4:
// Add(lhs, Add(a, b)) =>
// Add(Add(lhs, a), b)
HloInstruction* a = rhs->mutable_operand(0);
HloInstruction* b = rhs->mutable_operand(1);
TF_RETURN_IF_ERROR(rhs->ReplaceOperandWith(0, lhs));
TF_RETURN_IF_ERROR(rhs->ReplaceOperandWith(1, a));
TF_RETURN_IF_ERROR(output->ReplaceOperandWith(0, rhs));
TF_RETURN_IF_ERROR(output->ReplaceOperandWith(1, b));
} else if (IsWideConstantZero(rhs)) {
// Case 5:
// Add(lhs, zeros) =>
// lhs
TF_RETURN_IF_ERROR(comp->ReplaceInstruction(output, lhs));
output = lhs;
} else if (Match(rhs, m::Transpose(m::Concatenate())) ||
Match(rhs, m::Transpose(m::Multiply(
m::Concatenate(),
m::Broadcast(m::ConstantScalar()))))) {
// Case 6:
// Add(a, Transpose(Concat(b, c, ...))) =>
// Add(a, Concat(Transpose(b), Transpose(c), ...)
// Case 7:
// Add(a, Transpose(Multiply(Concat(b, c, ...), Broadcast(d))) =>
// Add(a, Multiply(Concat(Transpose(b), Transpose(c), ...),
// Broadcast(d))
HloInstruction* transpose = rhs;
HloInstruction* concat = transpose->mutable_operand(0);
// Get the scalar for case 7.
HloInstruction* scalar = nullptr;
if (concat->opcode() == HloOpcode::kMultiply) {
scalar = concat->mutable_operand(1)->mutable_operand(0);
CHECK_EQ(scalar->opcode(), HloOpcode::kConstant);
concat = concat->mutable_operand(0);
}
CHECK_EQ(concat->opcode(), HloOpcode::kConcatenate);
// We can push a transpose through a concatenate if only a single
// dimension is being transposed.
const std::vector<int64> permutation = transpose->dimensions();
int64 num_differences = 0;
for (int64 i = 0; i != permutation.size(); ++i) {
num_differences += permutation[i] == i ? 0 : 1;
}
if (num_differences != 2) {
// We cannot move this transpose.
output = lhs;
continue;
}
// Transpose the individual operands of the concat operation.
auto operands = concat->operands();
std::vector<HloInstruction*> new_operands(concat->operand_count());
for (int64 i = 0; i != operands.size(); ++i) {
TF_ASSIGN_OR_RETURN(new_operands[i],
MakeTransposeHlo(operands[i], permutation));
}
// Create a concat on the transposed operands, on the permuted
// concat dimension.
const int64 concat_dimension = concat->concatenate_dimension();
const int64 new_concat_dimension = permutation[concat_dimension];
TF_ASSIGN_OR_RETURN(HloInstruction * new_output,
MakeConcatHlo(new_operands, new_concat_dimension));
// Add a multiply if there was one.
if (scalar) {
// Create a new broadcast.
HloInstruction* bcast =
MakeBroadcastHlo(scalar, {}, new_output->shape().dimensions());
// Apply the scalar.
TF_ASSIGN_OR_RETURN(
new_output, MakeBinaryHlo(HloOpcode::kMultiply, new_output, bcast));
}
TF_RETURN_IF_ERROR(comp->ReplaceInstruction(rhs, new_output));
} else if (Match(rhs, m::Transpose(m::Add()))) {
// Case 8:
// Add(a, Transpose(Add(b, c))) =>
// Add(a, Add(Transpose(b), Transpose(c)))
HloInstruction* add = rhs->mutable_operand(0);
HloInstruction* b = add->mutable_operand(0);
HloInstruction* c = add->mutable_operand(1);
// Tranpose b and c.
TF_ASSIGN_OR_RETURN(HloInstruction * b_t,
MakeTransposeHlo(b, rhs->dimensions()));
TF_ASSIGN_OR_RETURN(HloInstruction * c_t,
MakeTransposeHlo(c, rhs->dimensions()));
// Create a new add.
TF_ASSIGN_OR_RETURN(HloInstruction * new_add,
MakeBinaryHlo(HloOpcode::kAdd, b_t, c_t));
TF_RETURN_IF_ERROR(comp->ReplaceInstruction(rhs, new_add));
} else {
output = lhs;
}
}
// To avoid any other passes modifying the serialized chain of instruction,
// temporarily put it inside of a fusion computation. The
// PostSerializeGradientAccumulation pass will inline this back after all the
// optimizations are performed.
std::vector<HloInstruction*> to_outline;
CHECK_EQ(accumulator->user_count(), 1);
HloInstruction* next_inst = accumulator->users()[0];
while (next_inst != accumulator_user) {
to_outline.push_back(next_inst);
if (next_inst->user_count() != 1) {
return InternalErrorStrCat("Expected instruction ", next_inst->ToString(),
" to have a single user, but has ",
next_inst->user_count(), ".");
}
next_inst = next_inst->users()[0];
}
if (to_outline.size()) {
OutlineExpressionFromComputationWithFusion(to_outline, kFusionName, comp);
}
return Status::OK();
}
StatusOr<bool> ConvertGradientAccumulatorAdds(HloModule* module) {
bool changed = false;
for (HloComputation* comp : module->MakeComputationPostOrder()) {
if (IsPopOpsFusion(comp)) {
continue;
}
// Get all the accumulators.
std::vector<HloInstruction*> accumulator_adds;
for (HloInstruction* inst : comp->MakeInstructionPostOrder()) {
if (IsPoplarInstruction(PoplarOp::GradientAccumulatorAdd)(inst)) {
accumulator_adds.push_back(inst);
}
}
// Serialize them.
for (HloInstruction* accumulator_add : accumulator_adds) {
changed = true;
TF_RETURN_IF_ERROR(ConvertGradientAccumulatorAdd(accumulator_add));
}
}
return changed;
}
} // namespace
StatusOr<bool> SerializeGradientAccumulation::Run(HloModule* module) {
VLOG(2) << "Before SerializeGradientAccumulation:";
XLA_VLOG_LINES(2, module->ToString());
TF_ASSIGN_OR_RETURN(const bool changed,
ConvertGradientAccumulatorAdds(module));
if (changed) {
VLOG(2) << "After SerializeGradientAccumulation:";
XLA_VLOG_LINES(2, module->ToString());
} else {
VLOG(2) << "No changes were made to the module.";
}
return changed;
}
} // namespace poplarplugin
} // namespace xla
| 39.315436 | 99 | 0.638614 | [
"shape",
"vector"
] |
b802e24f2fb14d87713055121cdc2e5624e3ac6d | 11,437 | cpp | C++ | simd_sys_eu/src/simd_sys_eu_add_sub_2.cpp | timurkelin/simsimd | 79431b70cca50a995f2a1f12b3f5abe26e574096 | [
"MIT"
] | 14 | 2019-07-16T22:14:21.000Z | 2021-09-26T10:20:48.000Z | simd_sys_eu/src/simd_sys_eu_add_sub_2.cpp | timurkelin/simsimd | 79431b70cca50a995f2a1f12b3f5abe26e574096 | [
"MIT"
] | null | null | null | simd_sys_eu/src/simd_sys_eu_add_sub_2.cpp | timurkelin/simsimd | 79431b70cca50a995f2a1f12b3f5abe26e574096 | [
"MIT"
] | 3 | 2020-03-20T02:34:39.000Z | 2020-06-28T19:55:28.000Z | /*
* simd_sys_eu_add_sub_2.cpp
*
* Description:
* Methods for the 2-input add/subtract execution unit
* This is an example of the multiple IN ports feeding data into a single OUT port
*/
#include "simd_sys_eu_add_sub_2.h"
#include "simd_assert.h"
#include "simd_report.h"
namespace simd {
void simd_sys_eu_add_sub_2_c::init(
boost::optional<const boost_pt::ptree&> _pref_p ) {
const boost_pt::ptree& pref = _pref_p.get();
pref_p = _pref_p;
// Set port sizes
data_vi.init( n_data_i );
data_vo.init( n_data_o );
// Set size of the internal signals
ready_v.init( n_ready );
// Set the vector sizes for the config and status slots
try {
std::size_t conf_size = pref.get<std::size_t>( "config_slots" );
std::size_t stat_size = pref.get<std::size_t>( "status_slots" );
std::size_t fifo_size = pref.get<std::size_t>( "fifo_depth" );
if( conf_size > 0 ) {
config.resize( conf_size );
}
else {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " Incorrect config size";
}
if( stat_size >= 0 ) {
status.resize( stat_size );
}
else {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " Incorrect status size";
}
if( fifo_size > 0 ) {
active_config_p = boost::optional<sc_core::sc_fifo<std::size_t>&>(
*( new sc_core::sc_fifo<std::size_t>( std::string( name()).append( "_idx_fifo" ).c_str(), fifo_size )));
}
active_config = conf_size - 1;
active_status = stat_size ? stat_size - 1 : 0;
}
catch( const boost_pt::ptree_error& err ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " " << err.what();
}
catch( const std::exception& err ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " " << err.what();
}
catch( ... ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " Unexpected";
}
}
void simd_sys_eu_add_sub_2_c::add_trace(
sc_core::sc_trace_file* tf,
const std::string& top_name ) {
//std::string mod_name = top_name + "." + std::string( name());
add_trace_ports(
tf,
top_name );
}
void simd_sys_eu_add_sub_2_c::req_run( // Execution request
void ) {
bool flg_neg_re0 = false;
bool flg_neg_im0 = false;
bool flg_neg_re1 = false;
bool flg_neg_im1 = false;
// Sign manipulation of the operands
try {
flg_neg_re0 = config.at( active_config ).get<bool>( "neg_re0" );
flg_neg_im0 = config.at( active_config ).get<bool>( "neg_im0" );
flg_neg_re1 = config.at( active_config ).get<bool>( "neg_re1" );
flg_neg_im1 = config.at( active_config ).get<bool>( "neg_im1" );
}
catch( const boost_pt::ptree_error& err ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " " << err.what();
}
catch( const std::exception& err ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " " << err.what();
}
catch( ... ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " Unexpected";
}
// Parse the sign strings
sign_re0 = flg_neg_re0 ? -1.0 : +1.0;
sign_im0 = flg_neg_im0 ? -1.0 : +1.0;
sign_re1 = flg_neg_re1 ? -1.0 : +1.0;
sign_im1 = flg_neg_im1 ? -1.0 : +1.0;
// Operation when the sample in the frame is not available
try {
smp_nena_op = config.at( active_config ).get<std::string>( "smp_nena_op" );
}
catch( const boost_pt::ptree_error& err ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " " << err.what();
}
catch( const std::exception& err ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " " << err.what();
}
catch( ... ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " Unexpected";
}
if( smp_nena_op != "zero" &&
smp_nena_op != "nena" &&
smp_nena_op != "error" ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " Incorrect specification";
}
}
void simd_sys_eu_add_sub_2_c::proc_thrd(
void ) {
simd_dmeu_valid_t dst_valid = SIMD_IDLE;
simd_dmeu_data_c dst_data;
simd_dmeu_ready_t dst_ready = false;
bool dst_avail;
std::vector<simd_dmeu_valid_t> src_valid( n_data_i, SIMD_IDLE );
std::vector<simd_dmeu_data_c> src_data( n_data_i );
std::vector<simd_dmeu_ready_t> src_ready( n_data_i );
bool vec_tail = false;
simd_sig_dmeu_state_c sig_state;
std::vector<simd_dump_buf_c<simd_dmeu_data_c>> dump_buf_data_vi{
std::string( name()) + ".data_i0",
std::string( name()) + ".data_i1"
};
simd_dump_buf_c<simd_dmeu_data_c> dump_buf_data_o0(
std::string( name()) + ".data_o0" );
sc_core::wait();
for(;;) {
sc_core::wait();
bool all_inp_avail = true;
// Read ports
simd_dmeu_state_t state = state_o->read().get(); // current state been sent to xbar
bool proc_en = proc_i->read(); // proc_en from xbar
dst_ready = data_vo.at( 0 )->is_ready();
if(( state == DMEU_ST_IDLE || state == DMEU_ST_PROC ) && proc_en ) {
// Read data and valid from the input ports if their "ready" is set
for( size_t data_i = 0; data_i < n_data_i; data_i ++ ) {
if( src_ready.at( data_i ) ) { // SRC Ready was set in the previous clock cycle
data_vi.at( data_i )->nb_read( // Read the input port if its "ready" signal is set
src_data.at( data_i ),
src_valid.at( data_i ));
}
}
// Read ports
dst_avail = data_vo.at( 0 )->is_avail();
if( !vec_tail && dst_ready ) {
for( size_t data_i = 0; data_i < n_data_i; data_i ++ ) {
if( src_valid.at( data_i ) == SIMD_IDLE ) {
all_inp_avail = false;
break;
}
else if(( data_i != 0 ) && ( src_valid.at( data_i ) != src_valid.at( 0 ))) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " Size mismatch for the input vectors";
}
}
// Try reading and transmit a sample on this clock cycle
if( all_inp_avail ) {
if( src_valid.at( 0 ) == SIMD_TAIL ) { // This condition should go first according to VRI
dst_valid = SIMD_TAIL;
vec_tail = true;
}
else if( src_valid.at( 0 ) == SIMD_HEAD ) {
state_o->write( sig_state.set( DMEU_ST_PROC ));
dst_valid = SIMD_HEAD;
event( "vec_head" ); // Generate "head" event for the output vector
}
else if( src_valid.at( 0 ) == SIMD_BODY ) {
dst_valid = SIMD_BODY;
}
else {
dst_valid = SIMD_IDLE;
}
// EU processing core
for( size_t slot = 0; slot < simd_dmeu_data_c::dim; slot ++ ) {
if( src_data.at( 0 )[slot].ena & src_data.at( 1 )[slot].ena ) { // both samples are available
dst_data[slot].smp = simd_dmeu_smp_t(
src_data.at( 0 )[slot].smp.real() * sign_re0 + src_data.at( 1 )[slot].smp.real() * sign_re1,
src_data.at( 0 )[slot].smp.imag() * sign_im0 + src_data.at( 1 )[slot].smp.imag() * sign_im1 );
dst_data[slot].ena = true;
}
else if( src_data.at( 0 )[slot].ena ^ src_data.at( 1 )[slot].ena ) { // One sample is unavailable
if( smp_nena_op == "zero" ) {
if( src_data.at( 0 )[slot].ena ) {
dst_data[slot].smp = simd_dmeu_smp_t(
src_data.at( 0 )[slot].smp.real() * sign_re0,
src_data.at( 0 )[slot].smp.imag() * sign_im0 );
}
else {
dst_data[slot].smp = simd_dmeu_smp_t(
src_data.at( 1 )[slot].smp.real() * sign_re1,
src_data.at( 1 )[slot].smp.imag() * sign_im1 );
}
dst_data[slot].ena = true;
}
else if( smp_nena_op == "nena" ) {
dst_data[slot].smp = simd_dmeu_smp_t( 0.0, 0.0 );
dst_data[slot].ena = false;
}
else if( smp_nena_op == "error" ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " Incorrect sample";
}
}
else {
dst_data[slot].smp = simd_dmeu_smp_t( 0.0, 0.0 );
dst_data[slot].ena = false;
}
}
// Write data to channel
data_vo.at( 0 )->nb_write( dst_data, dst_valid );
// Write to the dump buffers
for( size_t data_i = 0; data_i < n_data_i; data_i ++ ) {
dump_buf_data_vi.at( data_i ).write(
src_data.at( data_i ),
src_valid.at( 0 ) != SIMD_TAIL ? BUF_WRITE_CONT : BUF_WRITE_LAST );
}
dump_buf_data_o0.write(
dst_data,
dst_valid != SIMD_TAIL ? BUF_WRITE_CONT : BUF_WRITE_LAST );
} // if( all_inp_avail )
else {
data_vo.at( 0 )->nb_valid( SIMD_IDLE );
} // if( all_inp_avail ) ... else ...
} // if( !vec_tail && dst_ready )
else if( vec_tail && dst_avail ) {
// Acknowledged TAIL
if( dst_valid != SIMD_TAIL ) {
SIMD_REPORT_ERROR( "simd::sys_eu" ) << name() << " Unexpected state";
}
event( "vec_tail" ); // Generate event on the acknowledged tail marker of the output vector
state_o->write( sig_state.set( DMEU_ST_DONE ));
dst_valid = SIMD_IDLE;
data_vo.at( 0 )->nb_valid( dst_valid );
vec_tail = false;
}
}
// Propagate dst_ready to the source ports
for( size_t data_i = 0; data_i < n_data_i; data_i ++ ) {
if( all_inp_avail || src_valid.at( data_i ) == SIMD_IDLE ) {
src_ready.at( data_i ) = dst_ready;
}
else {
src_ready.at( data_i ) = false;
}
data_vi.at( data_i )->nb_ready( src_ready.at( data_i ));
}
if( state == DMEU_ST_DONE && !proc_en ) {
bool run_here = next_conf_run( active_config );
if( !run_here && active_config_p && active_config_p.get().num_available()) {
std::size_t conf_idx = active_config_p.get().read();
active_config = conf_idx; // Specify active config index
active_status = curr_stat_idx( conf_idx );
req_run(); // Function-specific configuration
}
state_o->write( sig_state.set( DMEU_ST_IDLE ));
}
// Parse request on busw (1 per clock cycle)
if( busw_i->num_available()) {
simd_sig_ptree_c req = busw_i->read();
parse_busw_req( req );
}
}
}
void simd_sys_eu_add_sub_2_c::ready_thrd(
void ) {
for(;;) {
sc_core::wait(); // We process "ready" in the synchronous process
}
}
} // namespace simd
| 34.975535 | 121 | 0.524613 | [
"vector"
] |
b8039307beb57239f7808567af3734d6a3cc2866 | 29,192 | cpp | C++ | DarkGDK/Dark Basic Pro SDK/Shared/Basic2D/CBasic2DC.cpp | dgavedissian/DBPro-CMake | 83e5b9505a8a068eec62bb8b5fc9dddbad08c3dd | [
"MIT"
] | null | null | null | DarkGDK/Dark Basic Pro SDK/Shared/Basic2D/CBasic2DC.cpp | dgavedissian/DBPro-CMake | 83e5b9505a8a068eec62bb8b5fc9dddbad08c3dd | [
"MIT"
] | null | null | null | DarkGDK/Dark Basic Pro SDK/Shared/Basic2D/CBasic2DC.cpp | dgavedissian/DBPro-CMake | 83e5b9505a8a068eec62bb8b5fc9dddbad08c3dd | [
"MIT"
] | null | null | null |
//////////////////////////////////////////////////////////////////////////////////
// INCLUDES / LIBS ///////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
#include <time.h>
#include "cbasic2Dc.h"
#include ".\..\error\cerror.h"
#include ".\..\core\globstruct.h"
// WickedX - 290414 r114 - Added for paint function
//////////////////////////////////////////////////////////////////////////////////
#include <stack>
using namespace std;
//////////////////////////////////////////////////////////////////////////////////
#ifdef DARKSDK_COMPILE
#include ".\..\..\..\DarkGDK\Code\Include\DarkSDKDisplay.h"
#endif
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// GLOBALS ///////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
typedef IDirect3DDevice9* ( *GFX_GetDirect3DDevicePFN ) ( void );
DBPRO_GLOBAL GlobStruct* g_pGlob = NULL;
DBPRO_GLOBAL HINSTANCE g_GFX;
DBPRO_GLOBAL GFX_GetDirect3DDevicePFN g_GFX_GetDirect3DDevice;
DBPRO_GLOBAL LPDIRECT3DDEVICE9 m_pD3D;
DBPRO_GLOBAL bool m_bIsLocked;
DBPRO_GLOBAL D3DLOCKED_RECT m_LockedRect;
DBPRO_GLOBAL LPDIRECT3DSURFACE9 m_pSurface;
DBPRO_GLOBAL DWORD* m_pData;
DBPRO_GLOBAL int m_SurfaceWidth;
DBPRO_GLOBAL int m_SurfaceHeight;
DBPRO_GLOBAL LPDIRECT3DVERTEXBUFFER9 m_pLineVB;
DBPRO_GLOBAL DWORD m_dwBPP;
DBPRO_GLOBAL int m_iBRed;
DBPRO_GLOBAL int m_iBGreen;
DBPRO_GLOBAL int m_iBBlue;
DBPRO_GLOBAL int m_iFRed;
DBPRO_GLOBAL int m_iFGreen;
DBPRO_GLOBAL int m_iFBlue;
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// INTERNAL FUNCTIONS ////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
DARKSDK int GetBitDepthFromFormat(D3DFORMAT Format)
{
switch(Format)
{
case D3DFMT_R8G8B8 : return 24; break;
case D3DFMT_A8R8G8B8 : return 32; break;
case D3DFMT_X8R8G8B8 : return 32; break;
case D3DFMT_R5G6B5 : return 16; break;
case D3DFMT_X1R5G5B5 : return 16; break;
case D3DFMT_A1R5G5B5 : return 16; break;
case D3DFMT_A4R4G4B4 : return 16; break;
case D3DFMT_A8 : return 8; break;
case D3DFMT_R3G3B2 : return 8; break;
case D3DFMT_A8R3G3B2 : return 16; break;
case D3DFMT_X4R4G4B4 : return 16; break;
case D3DFMT_A2B10G10R10 : return 32; break;
case D3DFMT_G16R16 : return 32; break;
case D3DFMT_A8P8 : return 8; break;
case D3DFMT_P8 : return 8; break;
case D3DFMT_L8 : return 8; break;
case D3DFMT_A8L8 : return 16; break;
case D3DFMT_A4L4 : return 8; break;
}
return 0;
}
DARKSDK void UpdateBPP(void)
{
// Update BPP based on draw depth
D3DSURFACE_DESC ddsd;
g_pGlob->pCurrentBitmapSurface->GetDesc(&ddsd);
m_dwBPP=GetBitDepthFromFormat(ddsd.Format)/8;
}
DARKSDK void Constructor ( HINSTANCE hSetup )
{
// if we dont have any valid handles,
if ( !hSetup )
{
// attempt to load the DLLs manually
#ifndef DARKSDK_COMPILE
hSetup = LoadLibrary ( "DBProSetupDebug.dll" );
// create glob data locally
g_pGlob = new GlobStruct;
// u74b7 - Fixed the overwriting of stack data.
//ZeroMemory(&g_pGlob, sizeof(GlobStruct));
ZeroMemory(g_pGlob, sizeof(GlobStruct));
#endif
}
#ifndef DARKSDK_COMPILE
// Assign Setup DLL Handle
g_GFX = hSetup;
// check library was loaded
if ( !g_GFX )
Error ( "Cannot load setup library" );
#endif
// now setup function pointer and get interface to D3D
//g_GFX_GetDirect3DDevice = ( GFX_GetDirect3DDevicePFN ) GetProcAddress ( g_GFX, "?GetDirect3DDevice@@YAPAUIDirect3DDevice9@@XZ" );
#ifndef DARKSDK_COMPILE
{
g_GFX_GetDirect3DDevice = ( GFX_GetDirect3DDevicePFN ) GetProcAddress ( g_GFX, "?GetDirect3DDevice@@YAPAUIDirect3DDevice9@@XZ" );
}
#else
{
g_GFX_GetDirect3DDevice = dbGetDirect3DDevice;
}
#endif
m_pD3D = g_GFX_GetDirect3DDevice ( );
m_bIsLocked = false;
m_pSurface = NULL;
m_pData = NULL;
// 20091128 v75 - IRM - Expand the LineVB so that it can also be used for the BOX command
m_pLineVB = NULL;
m_pD3D->CreateVertexBuffer( 6*sizeof(tagLinesVertexDesc), D3DUSAGE_WRITEONLY, D3DFVF_LINES, D3DPOOL_DEFAULT, &m_pLineVB, NULL);
memset ( &m_LockedRect, 0, sizeof ( m_LockedRect ) );
}
DARKSDK void Destructor ( void )
{
SAFE_RELEASE(m_pLineVB);
}
DARKSDK void SetErrorHandler ( LPVOID pErrorHandlerPtr )
{
// Update error handler pointer
g_pErrorHandler = (CRuntimeErrorHandler*)pErrorHandlerPtr;
}
DARKSDK void PassCoreData( LPVOID pGlobPtr )
{
// Held in Core, used here..
g_pGlob = (GlobStruct*)pGlobPtr;
// Get BPP
UpdateBPP();
}
DARKSDK void RefreshD3D ( int iMode )
{
if(iMode==0)
{
// Remove all traces of old D3D usage
Destructor();
}
if(iMode==1)
{
// Get new D3D and recreate everything D3D related
Constructor ( g_pGlob->g_GFX );
PassCoreData ( g_pGlob );
}
}
DARKSDK void Clear ( int iRed, int iGreen, int iBlue )
{
// Assign Colours
m_iBRed=iRed;
m_iBGreen=iGreen;
m_iBBlue=iBlue;
m_pD3D->Clear ( 1, NULL, D3DCLEAR_TARGET, D3DCOLOR_ARGB( 255, m_iBRed, m_iBGreen, m_iBBlue ), 0.0f, 0 );
}
DARKSDK void Ink ( int iRedF, int iGreenF, int iBlueF, int iRedB, int iGreenB, int iBlueB )
{
// Assign Colours
m_iBRed=iRedB;
m_iBGreen=iGreenB;
m_iBBlue=iBlueB;
m_iFRed=iRedF;
m_iFGreen=iGreenF;
m_iFBlue=iBlueF;
// Assign COLORREF
g_pGlob->dwForeColor = D3DCOLOR_ARGB( 255, m_iFRed, m_iFGreen, m_iFBlue );
g_pGlob->dwBackColor = D3DCOLOR_ARGB( 255, m_iBRed, m_iBGreen, m_iBBlue );
}
#define _RGB16BIT565(r,g,b) ((b & 31) + ((g & 63) << 5) + ((r & 31) << 11))
DARKSDK USHORT RGB16Bit565(int r, int g, int b)
{
r>>=3; g>>=2; b>>=3;
return(_RGB16BIT565((r),(g),(b)));
}
DARKSDK void PlotCore( int iX, int iY, DWORD Color )
{
// mike - 230604 - modified core so that 16 bit colours are supported
DWORD dwAlpha = Color >> 24;
DWORD dwRed = ((( Color ) >> 16 ) & 0xff );
DWORD dwGreen = ((( Color ) >> 8 ) & 0xff );
DWORD dwBlue = ((( Color ) ) & 0xff );
// mike - 280305 - allow to write over screen boundaries
if(iX<0) return;
if(iY<0) return;
// leefix - 310305 - return code with additional bitmap specific check
if ( g_pGlob->iCurrentBitmapNumber==0 )
{
if ( iX >= g_pGlob->iScreenWidth ) return;
if ( iY >= g_pGlob->iScreenHeight ) return;
}
// mike - 021005 - ensure we're not plotting outside of surce
if ( iX >= m_SurfaceWidth )
return;
if ( iY >= m_SurfaceHeight )
return;
switch(m_dwBPP)
{
// mike - 250604
case 2 : *((WORD*)m_pData + iX + iY * m_LockedRect.Pitch / 2 ) = RGB16Bit565 ( dwRed, dwGreen, dwBlue ); break;
//case 2 : *((WORD*)m_pData + iX + iY * m_LockedRect.Pitch / 2 ) =WORD(Color); break;
case 4 : m_pData [ iX + iY * m_LockedRect.Pitch / 4 ] = Color; break;
}
}
DARKSDK DWORD GetPlotCore( int iX, int iY )
{
// lee - 170206 - u60 - performance hit sure, but safest method
if(iX<0) return 0;
if(iY<0) return 0;
if ( g_pGlob->iCurrentBitmapNumber==0 )
{
if ( iX >= g_pGlob->iScreenWidth ) return 0;
if ( iY >= g_pGlob->iScreenHeight ) return 0;
}
if ( iX >= m_SurfaceWidth ) return 0;
if ( iY >= m_SurfaceHeight ) return 0;
switch(m_dwBPP)
{
case 2: return *((WORD*)m_pData + iX + iY * m_LockedRect.Pitch / 2 );
case 4: return m_pData [ iX + iY*m_LockedRect.Pitch / 4 ];
}
return 0;
}
// WickedX - 290414 r114 - Added core for Paint Function
// Fast scanline floodfill algorithm using the Standard Templete Library - stack
DARKSDK void PaintCore ( int iX, int iY )
{
int y1;
DWORD OldColor, NewColor;
bool spanLeft, spanRight;
POINT coords;
stack<POINT> Stack;
if (iX<0 || iX>=m_SurfaceWidth)
return;
if (iY<0 || iY>=m_SurfaceHeight)
return;
NewColor = g_pGlob->dwForeColor;
OldColor = GetPlotCore ( iX, iY );
if (OldColor==NewColor)
return;
coords.x = iX;
coords.y = iY;
Stack.push(coords);
while (!Stack.empty())
{
coords = Stack.top();
Stack.pop();
iX = coords.x;
y1 = coords.y;
while (y1 >= 0 && GetPlotCore ( iX, y1 )==OldColor)
y1--;
y1++;
spanLeft = spanRight = 0;
while (y1<m_SurfaceHeight && GetPlotCore ( iX, y1 )==OldColor)
{
PlotCore ( iX, y1, NewColor );
if (!spanLeft && iX>0 && GetPlotCore ( iX-1, y1 )==OldColor)
{
coords.x = iX-1;
coords.y = y1;
Stack.push(coords);
spanLeft = 1;
}
else if (spanLeft && iX>0 && GetPlotCore ( iX-1, y1 )!=OldColor)
{
spanLeft = 0;
}
if (!spanRight && iX<m_SurfaceWidth-1 && GetPlotCore ( iX+1, y1 )==OldColor)
{
coords.x = iX+1;
coords.y = y1;
Stack.push(coords);
spanRight = 1;
}
else if (spanRight && iX<m_SurfaceWidth-1 && GetPlotCore ( iX+1, y1 )!=OldColor)
{
spanRight = 0;
}
y1++;
}
}
}
DARKSDK void Write ( int iX, int iY, DWORD Color )
{
if(iX>=0 && iY>=0 && iX<=m_SurfaceWidth && iY<=m_SurfaceHeight)
PlotCore(iX,iY,Color);
}
DARKSDK void WriteCirclePoints ( int iCX, int iCY, int x, int y, DWORD Color )
{
Write ( iCX+x, iCY+y, Color );
Write ( iCX+y, iCY+x, Color );
Write ( iCX+y, iCY-x, Color );
Write ( iCX+x, iCY-y, Color );
Write ( iCX-x, iCY-y, Color );
Write ( iCX-y, iCY-x, Color );
Write ( iCX-y, iCY+x, Color );
Write ( iCX-x, iCY+y, Color );
}
// WickedX - 290414 r114 - Removed from Circle function and added here
// To allow for batch operations when used between dbLockPixels() and dbUnlockPixels()
DARKSDK void CircleCore ( int iX, int iY, int iRadius )
{
int x = 0;
int y = iRadius;
int d = 1 - iRadius;
WriteCirclePoints ( iX, iY, x, y, g_pGlob->dwForeColor );
while ( y > x )
{
if ( d < 0 )
d += 2 * x;// + 3;
else
{
d += 2 * ( x - y );// + 5;
y--;
}
x++;
WriteCirclePoints ( iX, iY, x, y, g_pGlob->dwForeColor );
}
}
DARKSDK void WriteEllipsePoints ( int iCX, int iCY, int x, int y, DWORD Color )
{
Write ( iCX+x, iCY+y, Color );
Write ( iCX+x, iCY-y, Color );
Write ( iCX-x, iCY-y, Color );
Write ( iCX-x, iCY+y, Color );
}
// WickedX - 290414 r114 - Removed from Elipse function and added here
// To allow for batch operations when used between dbLockPixels() and dbUnlockPixels()
DARKSDK void ElipseCore ( int iX, int iY, int iXRadius, int iYRadius )
{
int x = 0;
int y = iYRadius;
double a = 0;
while(a<2.0)
{
double ix = sin(a)*iXRadius;
double iy = cos(a)*iYRadius;
int newx=(int)ix;
int newy=(int)iy;
while(newx!=x || newy!=y)
{
if(newx<x) x--;
if(newx>x) x++;
if(newy<y) y--;
if(newy>y) y++;
WriteEllipsePoints ( iX, iY, x, y, g_pGlob->dwForeColor );
}
//a+=0.01;
// mike - 230604 - stop missing pixels
a+=0.001;
}
}
DARKSDK void Clear ( DWORD RGBColor )
{
m_pD3D->Clear ( 1, NULL, D3DCLEAR_TARGET, RGBColor, 0.0f, 0 );
}
DARKSDK bool GetLockable ( void )
{
return false;
}
DARKSDK void CopyArea(int iDestX, int iDestY, int iWidth, int iHeight, int iSourceX, int iSourceY)
{
// get surface desc
D3DSURFACE_DESC surfacedesc;
IDirect3DSurface9* pSurface = g_pGlob->pCurrentBitmapSurface;
pSurface->GetDesc ( &surfacedesc );
// Define areas to copy
RECT rcSource = { iSourceX, iSourceY, iSourceX+iWidth, iSourceY+iHeight };
// Clip to actual surface source size
int iScrWidth=surfacedesc.Width;
int iScrHeight=surfacedesc.Height;
if(rcSource.right>iScrWidth) rcSource.right=iScrWidth;
if(rcSource.bottom>iScrHeight) rcSource.bottom=iScrHeight;
// Define destination rect
RECT rcDestRect;
rcDestRect.left=iDestX;
rcDestRect.top=iDestY;
rcDestRect.right=iDestX+(rcSource.right-rcSource.left);
rcDestRect.bottom=iDestX+(rcSource.bottom-rcSource.top);
// Perform copy
if(m_pD3D)
{
// source and dest surface
if ( pSurface )
{
// create temp surface
IDirect3DSurface9* pTempSurface = NULL;
m_pD3D->CreateRenderTarget ( surfacedesc.Width, surfacedesc.Height, surfacedesc.Format, D3DMULTISAMPLE_NONE, 0, TRUE, &pTempSurface, NULL );
if ( pTempSurface )
{
// copy over
m_pD3D->StretchRect(pSurface, NULL, pTempSurface, NULL, D3DTEXF_NONE);
m_pD3D->StretchRect(pTempSurface, &rcSource, pSurface, &rcDestRect, D3DTEXF_NONE);
// free surface
SAFE_RELEASE ( pTempSurface );
}
}
}
}
DARKSDK void Clear ( void )
{
m_pD3D->Clear ( 0, NULL, D3DCLEAR_TARGET, g_pGlob->dwBackColor, 0.0f, 0 );
}
DARKSDK void ClearRgb ( DWORD RGBBackColor )
{
g_pGlob->iCursorX=0;
g_pGlob->iCursorY=0;
m_pD3D->Clear ( 0, NULL, D3DCLEAR_TARGET, RGBBackColor, 0.0f, 0 );
}
DARKSDK void Ink ( DWORD RGBForeColor, DWORD RGBBackColor )
{
g_pGlob->dwForeColor = RGBForeColor;
g_pGlob->dwBackColor = RGBBackColor;
}
DARKSDK DWORD CorrectDotColor ( DWORD dwCol )
{
// mike - 260604 - return original colour
return dwCol;
if(m_dwBPP==2)
{
int red = (int)(((dwCol & (255<<16)) >> 16) / 8.3);
int green = (int)(((dwCol & (255<<8)) >> 8) / 4.1);
int blue = (int)((dwCol & 255) / 8.3);
if(red>31) red=31;
if(green>63) green=63;
if(blue>31) blue=31;
dwCol = (red<<11)+(green<<5)+(blue);
}
return dwCol;
}
DARKSDK void Dot ( int iX, int iY )
{
DWORD dwCol = CorrectDotColor ( g_pGlob->dwForeColor );
// mike - 280305 - allow to write over screen boundaries
if(iX<0) return;
if(iY<0) return;
// leefix - 310305 - return code with additional bitmap specific check
if ( g_pGlob->iCurrentBitmapNumber==0 )
{
if(iX>g_pGlob->iScreenWidth) return;
if(iY>g_pGlob->iScreenHeight) return;
}
if ( m_bIsLocked )
{
PlotCore(iX,iY,dwCol);
}
else
{
Lock ( );
PlotCore(iX,iY,dwCol);
Unlock ( );
}
}
DARKSDK void Box ( int iLeft, int iTop, int iRight, int iBottom )
{
/* This does not work for all NVidia systems, so replace with a render.
D3DRECT rect = { iLeft, iTop, iRight, iBottom };
m_pD3D->Clear ( 1, &rect, D3DCLEAR_TARGET, g_pGlob->dwForeColor, 0.0f, 0 );
*/
tagLinesVertexDesc * v = 0;
if (m_pLineVB)
m_pLineVB->Lock( 0, 0, (void**)&v, 0 );
if (v)
{
v[0].x = (float)iLeft;
v[0].y = (float)iBottom;
v[0].z = 10.0f;
v[0].rhw = 1.0f;
v[0].dwColour = g_pGlob->dwForeColor;
v[1].x = (float)iLeft;
v[1].y = (float)iTop;
v[1].z = 10.0f;
v[1].rhw = 1.0f;
v[1].dwColour = g_pGlob->dwForeColor;
v[2].x = (float)iRight;
v[2].y = (float)iTop;
v[2].z = 10.0f;
v[2].rhw = 1.0f;
v[2].dwColour = g_pGlob->dwForeColor;
v[3].x = (float)iRight;
v[3].y = (float)iBottom;
v[3].z = 10.0f;
v[3].rhw = 1.0f;
v[3].dwColour = g_pGlob->dwForeColor;
m_pLineVB->Unlock();
m_pD3D->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
m_pD3D->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );
m_pD3D->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
m_pD3D->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
m_pD3D->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
m_pD3D->SetRenderState( D3DRS_ZENABLE, FALSE );
m_pD3D->SetRenderState( D3DRS_DITHERENABLE, FALSE );
m_pD3D->SetRenderState( D3DRS_LIGHTING, FALSE );
m_pD3D->SetRenderState( D3DRS_COLORVERTEX, TRUE );
m_pD3D->SetRenderState( D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1 );
m_pD3D->SetRenderState( D3DRS_SPECULARENABLE, FALSE );
m_pD3D->SetRenderState( D3DRS_FOGENABLE, FALSE );
m_pD3D->SetRenderState( D3DRS_ZWRITEENABLE, FALSE );
DWORD AAEnabled = FALSE;
m_pD3D->GetRenderState ( D3DRS_MULTISAMPLEANTIALIAS, &AAEnabled );
if (AAEnabled)
m_pD3D->SetRenderState( D3DRS_MULTISAMPLEANTIALIAS, FALSE );
m_pD3D->SetVertexShader( NULL );
m_pD3D->SetFVF( D3DFVF_LINES );
m_pD3D->SetStreamSource( 0, m_pLineVB, 0, sizeof(tagLinesVertexDesc) );
m_pD3D->SetTexture( 0, NULL );
m_pD3D->SetTextureStageState ( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
m_pD3D->SetTextureStageState ( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE );
m_pD3D->SetTextureStageState ( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
m_pD3D->SetTextureStageState ( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
m_pD3D->SetTextureStageState ( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE );
m_pD3D->SetTextureStageState ( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
m_pD3D->DrawPrimitive( D3DPT_TRIANGLEFAN, 0 ,2 );
if (AAEnabled)
m_pD3D->SetRenderState ( D3DRS_MULTISAMPLEANTIALIAS, TRUE );
}
}
DARKSDK void Line ( int iXa, int iYa, int iXb, int iYb )
{
if(m_pLineVB)
{
// fill data for line
tagLinesVertexDesc * lines;
m_pLineVB->Lock( 0, 0, (void**)&lines, 0 );
lines [ 0 ].x = (float)iXa; // start x point
lines [ 0 ].y = (float)iYa; // start y point
lines [ 0 ].z = 0; // keep this as 0 because we want 2D only
lines [ 0 ].rhw = 1.0f;
lines [ 0 ].dwColour = g_pGlob->dwForeColor;
lines [ 1 ].x = (float)iXb; // end x point
lines [ 1 ].y = (float)iYb; // end y point
lines [ 1 ].z = 0; // keep this as 0 because we want 2D only
lines [ 1 ].rhw = 1.0f;
lines [ 1 ].dwColour = g_pGlob->dwForeColor;
m_pLineVB->Unlock();
// draw the line
m_pD3D->SetTexture( 0, NULL );
m_pD3D->SetTexture( 1, NULL );
// DX8->DX9
m_pD3D->SetVertexShader( NULL );
m_pD3D->SetFVF( D3DFVF_LINES );
m_pD3D->SetStreamSource( 0, m_pLineVB, 0, sizeof(tagLinesVertexDesc) );
m_pD3D->SetRenderState( D3DRS_FOGENABLE, FALSE );
m_pD3D->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
m_pD3D->SetRenderState( D3DRS_ALPHATESTENABLE, FALSE );
m_pD3D->DrawPrimitive( D3DPT_LINELIST, 0 , 1);
}
}
// WickedX - 290414 r114 - Transferred circle code to CircleCore function
// Allowing for batch operations between dbLockPixels() and dbUnlockPixels()
DARKSDK void Circle ( int iX, int iY, int iRadius )
{
if ( m_bIsLocked )
{
CircleCore( iX, iY, iRadius );
}
else
{
Lock ( );
CircleCore ( iX, iY, iRadius );
Unlock ( );
}
}
// WickedX - 290414 r114 - Transferred ellipse code to ElipseCore function
// Allowing for batch operations between dbLockPixels() and dbUnlockPixels()
DARKSDK void Elipse ( int iX, int iY, int iXRadius, int iYRadius )
{
if ( m_bIsLocked )
{
ElipseCore ( iX, iY, iXRadius, iYRadius );
}
else
{
Lock ( );
ElipseCore ( iX, iY, iXRadius, iYRadius );
Unlock ( );
}
}
// WickedX - 290414 r114 - Added Paint Function
DARKSDK void Paint(int iX, int iY)
{
if ( m_bIsLocked )
{
PaintCore ( iX, iY );
}
else
{
Lock ( );
PaintCore ( iX, iY );
Unlock ( );
}
}
DARKSDK DWORD Rgb ( int iRed, int iGreen, int iBlue )
{
return D3DCOLOR_XRGB(iRed, iGreen, iBlue);
}
DARKSDK int RgbR ( DWORD iRGB )
{
return (int)((iRGB & 0x00FF0000) >> 16);
}
DARKSDK int RgbG ( DWORD iRGB )
{
return (int)((iRGB & 0x0000FF00) >> 8);
}
DARKSDK int RgbB ( DWORD iRGB )
{
return (int)((iRGB & 0x000000FF) );
}
DARKSDK DWORD GetPoint ( int iX, int iY )
{
DWORD dwColor=0;
if ( m_bIsLocked )
{
// LEEFIX - 141102 - 16 bit has no such alpha bites so this is very wrong
// dwColor=GetPlotCore(iX,iY) & 0x000000FF;
dwColor=GetPlotCore(iX,iY);
}
else
{
// LEEFIX - 141102 - 16 bit has no such alpha bites so this is very wrong
// dwColor=GetPlotCore(iX,iY) & 0x000000FF;
Lock ( );
dwColor=GetPlotCore(iX,iY);
Unlock ( );
}
int red, green, blue;
switch(m_dwBPP)
{
case 2 : // Split 16bit(5-6-5) components
red = (int)(( ((dwColor>>11) & 31) ) * 8.3);
green = (int)(( ((dwColor>>5) & 63) ) * 4.1);
blue = (int)(( ((dwColor) & 31) ) * 8.3);
if(red>255) red=255;
if(green>255) green=255;
if(blue>255) blue=255;
dwColor = D3DCOLOR_XRGB( red, green, blue );
break;
}
// Combine to create final colour value
return dwColor;
}
DARKSDK void BoxGradient( int iLeft, int iTop, int iRight, int iBottom, DWORD dw1, DWORD dw2, DWORD dw3, DWORD dw4 )
{
// Create a box with a gradient fade from one colour to another
// using the per vertex colour rendering technique :)
/*
20091128 v75 - IRM - http://forum.thegamecreators.com/?m=forum_view&t=161543&b=15
Using 2 polys for rendering the box does not give correctly shaded output,
ie the central points colour should be an average of all 4 corners.
Have switched to using 4 polys with each poly sharing a centre with a calculated colour.
This can be done as a fan, with 6 vertices and no index buffer.
Also, lots of code removed from this function, as I have expanded the vertex buffer
used by the LINE command so that it can also be used for this command, rather than
building a new vertex buffer each time.
Because of this, it should be a little faster than it was before.
*/
// 20091128 v75 - IRM - Calculate the centre vertex position and colour
float CentreX = (iLeft + iRight) / 2.0f;
float CentreY = (iTop + iBottom) / 2.0f;
#define BG_GetAlpha(c) (((c) >> 24) & 0xff)
#define BG_GetRed(c) (((c) >> 16) & 0xff)
#define BG_GetGreen(c) (((c) >> 8) & 0xff)
#define BG_GetBlue(c) ( (c) & 0xff)
// Note: The +2 allows colour to be rounded to the nearest match.
// If not used, the central colour would tend to be a little too dark.
DWORD CentreA = (BG_GetAlpha(dw1) + BG_GetAlpha(dw2) + BG_GetAlpha(dw3) + BG_GetAlpha(dw4) + 2) / 4;
DWORD CentreR = (BG_GetRed(dw1) + BG_GetRed(dw2) + BG_GetRed(dw3) + BG_GetRed(dw4) + 2) / 4;
DWORD CentreG = (BG_GetGreen(dw1) + BG_GetGreen(dw2) + BG_GetGreen(dw3) + BG_GetGreen(dw4) + 2) / 4;
DWORD CentreB = (BG_GetBlue(dw1) + BG_GetBlue(dw2) + BG_GetBlue(dw3) + BG_GetBlue(dw4) + 2) / 4;
DWORD CentreCol = D3DCOLOR_ARGB(CentreA, CentreR, CentreG, CentreB);
tagLinesVertexDesc * v = 0;
if (m_pLineVB)
m_pLineVB->Lock( 0, 0, (void**)&v, 0 );
if (v)
{
// 20091128 v75 - IRM - Fill out the 6 vertices
v[0].x = CentreX;
v[0].y = CentreY;
v[0].z = 10.0f;
v[0].rhw = 1.0f;
v[0].dwColour = CentreCol;
v[1].x = (float)iLeft;
v[1].y = (float)iBottom;
v[1].z = 10.0f;
v[1].rhw = 1.0f;
v[1].dwColour = dw1;
v[2].x = (float)iLeft;
v[2].y = (float)iTop;
v[2].z = 10.0f;
v[2].rhw = 1.0f;
v[2].dwColour = dw2;
v[3].x = (float)iRight;
v[3].y = (float)iTop;
v[3].z = 10.0f;
v[3].rhw = 1.0f;
v[3].dwColour = dw4;
v[4].x = (float)iRight;
v[4].y = (float)iBottom;
v[4].z = 10.0f;
v[4].rhw = 1.0f;
v[4].dwColour = dw3;
v[5].x = (float)iLeft;
v[5].y = (float)iBottom;
v[5].z = 10.0f;
v[5].rhw = 1.0f;
v[5].dwColour = dw1;
m_pLineVB->Unlock();
m_pD3D->SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
m_pD3D->SetRenderState( D3DRS_FILLMODE, D3DFILL_SOLID );
m_pD3D->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
m_pD3D->SetRenderState( D3DRS_SRCBLEND, D3DBLEND_SRCALPHA );
m_pD3D->SetRenderState( D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA );
m_pD3D->SetRenderState( D3DRS_ZENABLE, FALSE );
m_pD3D->SetRenderState( D3DRS_DITHERENABLE, FALSE );
m_pD3D->SetRenderState( D3DRS_LIGHTING, FALSE );
m_pD3D->SetRenderState( D3DRS_COLORVERTEX, TRUE );
m_pD3D->SetRenderState( D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_COLOR1 );
m_pD3D->SetRenderState( D3DRS_SPECULARENABLE, FALSE );
m_pD3D->SetRenderState( D3DRS_FOGENABLE, FALSE );
m_pD3D->SetRenderState( D3DRS_ZWRITEENABLE, FALSE );
// Save AA setting, and disable if active
DWORD AAEnabled = FALSE;
m_pD3D->GetRenderState ( D3DRS_MULTISAMPLEANTIALIAS, &AAEnabled );
if (AAEnabled)
m_pD3D->SetRenderState( D3DRS_MULTISAMPLEANTIALIAS, FALSE );
m_pD3D->SetVertexShader( NULL );
m_pD3D->SetFVF( D3DFVF_LINES );
m_pD3D->SetStreamSource( 0, m_pLineVB, 0, sizeof(tagLinesVertexDesc) );
m_pD3D->SetTexture( 0, NULL );
m_pD3D->SetTextureStageState ( 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1 );
m_pD3D->SetTextureStageState ( 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE );
m_pD3D->SetTextureStageState ( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
m_pD3D->SetTextureStageState ( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
m_pD3D->SetTextureStageState ( 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE );
m_pD3D->SetTextureStageState ( 0, D3DTSS_ALPHAARG2, D3DTA_DIFFUSE );
// 20091128 v75 - IRM - Render as a fan with 4 polys, not a strip with 2 polys
m_pD3D->DrawPrimitive( D3DPT_TRIANGLEFAN, 0 ,4);
// Re-enable AA if it was previously enabled
if (AAEnabled)
m_pD3D->SetRenderState ( D3DRS_MULTISAMPLEANTIALIAS, TRUE );
}
}
DARKSDK void Dot ( int iX, int iY, DWORD dwColor )
{
// LEEFIX - 141102 - Added this conevrter function from above DOT function
dwColor = CorrectDotColor ( dwColor );
if ( m_bIsLocked )
{
PlotCore(iX,iY,dwColor);
}
else
{
Lock ( );
PlotCore(iX,iY,dwColor);
Unlock ( );
}
}
DARKSDK DWORD GetPixelPtr ( void )
{
return (DWORD)m_pData;
}
DARKSDK DWORD GetPixelPitch ( void )
{
return (DWORD)m_LockedRect.Pitch;
}
DARKSDK void Lock ( void )
{
if ( m_bIsLocked==false )
{
// Get current render target surface
m_pSurface = g_pGlob->pCurrentBitmapSurface;
if(m_pSurface==NULL)
return;
if ( FAILED ( m_pSurface->LockRect ( &m_LockedRect, NULL, 0 ) ) )
return;
m_pData = ( DWORD* ) ( m_LockedRect.pBits );
D3DSURFACE_DESC ddsd;
m_pSurface->GetDesc(&ddsd);
m_SurfaceWidth=(int)ddsd.Width;
m_SurfaceHeight=(int)ddsd.Height;
m_bIsLocked = true;
}
}
DARKSDK void Unlock ( void )
{
if ( m_bIsLocked==true )
{
m_pSurface->UnlockRect ( );
m_bIsLocked = false;
}
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// DARK SDK SECTION //////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
#ifdef DARKSDK_COMPILE
void ConstructorBasic2D ( HINSTANCE hInstance )
{
Constructor( hInstance );
}
void DestructorBasic2D ( void )
{
Destructor ( );
}
void SetErrorHandlerBasic2D ( LPVOID pErrorHandlerPtr )
{
SetErrorHandler ( pErrorHandlerPtr );
}
void PassCoreDataBasic2D ( LPVOID pGlobPtr )
{
PassCoreData ( pGlobPtr );
}
void RefreshD3DBasic2D ( int iMode )
{
RefreshD3D ( iMode );
}
void UpdateBPPBasic2D (void)
{
UpdateBPP ( );
}
void dbCLS ( DWORD RGBBackColor )
{
ClearRgb ( RGBBackColor );
}
void dbInk ( DWORD RGBForeColor, DWORD RGBBackColor )
{
Ink ( RGBForeColor, RGBBackColor );
}
void dbDot ( int iX, int iY )
{
Dot ( iX, iY );
}
void dbBox ( int iLeft, int iTop, int iRight, int iBottom )
{
Box ( iLeft, iTop, iRight, iBottom );
}
void dbLine ( int iXa, int iYa, int iXb, int iYb )
{
Line ( iXa, iYa, iXb, iYb );
}
void dbCircle ( int iX, int iY, int iRadius )
{
Circle ( iX, iY, iRadius );
}
void dbElipse ( int iX, int iY, int iXRadius, int iYRadius )
{
Elipse ( iX, iY, iXRadius, iYRadius );
}
// WickedX - 290414 r114 - Added dbPaint Function
void dbPaint(int iX, int iY)
{
Paint ( iX, iY );
}
DWORD dbRgb ( int iRed, int iGreen, int iBlue )
{
return Rgb ( iRed, iGreen, iBlue );
}
int dbRgbR ( DWORD iRGB )
{
return RgbR ( iRGB );
}
int dbRgbG ( DWORD iRGB )
{
return RgbG ( iRGB );
}
int dbRgbB ( DWORD iRGB )
{
return RgbB ( iRGB );
}
DWORD dbPoint ( int iX, int iY )
{
return GetPoint ( iX, iY );
}
void dbDot ( int iX, int iY, DWORD dwColor )
{
Dot ( iX, iY, dwColor );
}
void dbBox ( int iLeft, int iTop, int iRight, int iBottom, DWORD dw1, DWORD dw2, DWORD dw3, DWORD dw4 )
{
BoxGradient ( iLeft, iTop, iRight, iBottom, dw1, dw2, dw3, dw4 );
}
void dbLockPixels ( void )
{
Lock ( );
}
void dbUnLockPixels ( void )
{
Unlock ( );
}
DWORD dbGetPixelsPointer ( void )
{
return GetPixelPtr ( );
}
DWORD dbGetPixelsPitch ( void )
{
return GetPixelPitch ( );
}
void dbCopyArea ( int iDestX, int iDestY, int iWidth, int iHeight, int iSourceX, int iSourceY )
{
CopyArea ( iDestX, iDestY, iWidth, iHeight, iSourceX, iSourceY );
}
// lee - 300706 - GDK fixes
DWORD dbRGB ( int iRed, int iGreen, int iBlue ) { return dbRgb ( iRed, iGreen, iBlue ); }
int dbRGBR ( DWORD iRGB ) { return dbRgbR ( iRGB ); }
int dbRGBG ( DWORD iRGB ) { return dbRgbG ( iRGB ); }
int dbRGBB ( DWORD iRGB ) { return dbRgbB ( iRGB ); }
void dbEllipse ( int iX, int iY, int iXRadius, int iYRadius ) { dbElipse ( iX, iY, iXRadius, iYRadius ); }
void dbUnlockPixels ( void ) { dbUnLockPixels(); }
#endif
//////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////// | 26.562329 | 143 | 0.616642 | [
"render"
] |
b804ddc9c1e390626d6864f94610e965519b23d3 | 3,019 | hpp | C++ | Simple++/IO/IOManagerLoadable.hpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null | Simple++/IO/IOManagerLoadable.hpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null | Simple++/IO/IOManagerLoadable.hpp | Oriode/Simpleplusplus | 2ba44eeab5078d6dab66bdefdf73617696b8cb2e | [
"Apache-2.0"
] | null | null | null |
template<typename DataType>
IOManagerLoadable<DataType>::IOManagerLoadable( const IOManager<DataType> & manager ) {
setLoaded( true );
for ( auto it( manager.dataMap.getBegin() ); it != manager.dataMap.getEnd(); manager.dataMap.iterate( &it ) ) {
ObjectContainer newContainer;
newContainer.object = new DataType( *( manager.dataMap.getValueIt( it ).object ) );
newContainer.nbUses = manager.dataMap.getValueIt( it ).nbUses;
_addObjectContainer( manager.dataMap.getIndexIt( it ), newContainer );
}
}
template<typename DataType>
typename IOManagerLoadable<DataType>::ObjectId IOManagerLoadable<DataType>::addObject( const String & filePath ) {
ObjectContainer * objectFounded( this -> dataMap[filePath] );
if ( objectFounded ) {
( objectFounded -> nbUses )++;
return objectFounded;
} else {
// Object doesn't exists, we have to add it
if ( isLoaded() ) {
DataType * newData( new DataType() );
if ( IO::read( filePath, newData ) ) {
ObjectContainer newContainer;
newContainer.nbUses = 1;
newContainer.object = newData;
return _addObjectContainer( filePath, newContainer );
} else {
delete newData;
// Loading has failed
return NULL;
}
} else {
ObjectContainer newContainer;
newContainer.nbUses = 1;
newContainer.object = NULL;
return _addObjectContainer( filePath, newContainer );
}
}
}
template<typename DataType>
bool IOManagerLoadable<DataType>::onUnload() {
for ( auto it( this -> dataVector.getBegin() ); it != this -> dataVector.getEnd(); this -> dataVector.iterate( &it ) ) {
ObjectContainer * objectContainer( _getObjectContainer( this -> dataVector.getValueIt( it ) ) );
delete objectContainer -> object;
objectContainer -> object = NULL;
}
return true;
}
template<typename DataType>
bool IOManagerLoadable<DataType>::onLoad() {
for ( auto it( this -> dataVector.getBegin() ); it != this -> dataVector.getEnd(); this -> dataVector.iterate( &it ) ) {
ObjectContainer * objectContainer( _getObjectContainer( this -> dataVector.getValueIt( it ) ) );
objectContainer -> object = new DataType();
if ( !IO::read( *( objectContainer -> filePath ), objectContainer -> object ) ) {
for ( auto it2( this -> dataVector.getBegin() ); it2 != this -> dataVector.getEnd(); this -> dataVector.iterate( &it2 ) ) {
ObjectContainer * objectContainer2( _getObjectContainer( this -> dataVector.getValueIt( it ) ) );
delete objectContainer2 -> object;
objectContainer2 -> object = NULL;
}
return false;
}
}
return true;
}
template<typename DataType>
IOManagerLoadable<DataType>::IOManagerLoadable() {
}
template<typename DataType>
IOManagerLoadable<DataType>::~IOManagerLoadable() {
}
template<typename DataType>
bool IOManagerLoadable<DataType>::onRead( std::fstream * fileStream ) {
return IOManager<DataType>::read( fileStream );
}
template<typename DataType>
bool IOManagerLoadable<DataType>::onWrite( std::fstream * fileStream ) const {
return IOManager<DataType>::write( fileStream );
}
| 30.806122 | 126 | 0.707519 | [
"object"
] |
b805ccb9ca80d8e3ec22bb505bda0fdc3e734eed | 14,821 | cpp | C++ | ext/s2/internal/parse_s2.cpp | davidsiaw/s2 | 2881fe51136e2afbfbe5a94329a9fd0d1490fec0 | [
"MIT"
] | null | null | null | ext/s2/internal/parse_s2.cpp | davidsiaw/s2 | 2881fe51136e2afbfbe5a94329a9fd0d1490fec0 | [
"MIT"
] | 2 | 2019-12-19T04:46:31.000Z | 2020-06-25T02:33:52.000Z | ext/s2/internal/parse_s2.cpp | davidsiaw/s2 | 2881fe51136e2afbfbe5a94329a9fd0d1490fec0 | [
"MIT"
] | null | null | null |
#include "parse_s2.hpp"
/*
WARNING: This file is generated using ruco. Please modify the .ruco file if you wish to change anything
https://github.com/davidsiaw/ruco
*/
namespace S2
{
S2Ptr Parse(std::string sourceFile)
{
std::shared_ptr<FILE> fp (fopen(sourceFile.c_str(), "r"), fclose);
if (!fp)
{
throw FileNotFoundException();
}
std::shared_ptr<Scanner> scanner (new Scanner(fp.get()));
std::shared_ptr<Parser> parser (new Parser(scanner.get()));
parser->Parse();
return parser->s2;
}
picojson::object CompileS2(S2Ptr pointer);
picojson::object CompileTypeVariable(TypeVariablePtr pointer);
picojson::object CompileStructName(StructNamePtr pointer);
picojson::object CompileMemberName(MemberNamePtr pointer);
picojson::object CompileNumberLiteral(NumberLiteralPtr pointer);
picojson::object CompileStringLiteral(StringLiteralPtr pointer);
picojson::object CompileTypeIdentifier(TypeIdentifierPtr pointer);
picojson::object CompileTypeExpression(TypeExpressionPtr pointer);
picojson::object CompileTypeParameterArguments(TypeParameterArgumentsPtr pointer);
picojson::object CompileTypeDeclaration(TypeDeclarationPtr pointer);
picojson::object CompileTypeParameters(TypeParametersPtr pointer);
picojson::object CompileNumberLit(NumberLitPtr pointer);
picojson::object CompileExpression(ExpressionPtr pointer);
picojson::object CompileAttributeParam(AttributeParamPtr pointer);
picojson::object CompileAttributeParamList(AttributeParamListPtr pointer);
picojson::object CompileAttribute(AttributePtr pointer);
picojson::object CompileMember(MemberPtr pointer);
picojson::object CompileFormat(FormatPtr pointer);
picojson::object CompileImport(ImportPtr pointer);
picojson::object CompileStatement(StatementPtr pointer);
picojson::object CompileS2(S2Ptr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"S2");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>3, :type=>:id}
picojson::array statements;
for(unsigned i=0; i<pointer->statements.size(); i++)
{
statements.push_back(picojson::value(CompileStatement(pointer->statements[i])));
}
object[L"statements"] = picojson::value(statements);
return object;
}
picojson::object CompileTypeVariable(TypeVariablePtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"TypeVariable");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:token}
object[L"_token"] = picojson::value(pointer->content);
return object;
}
picojson::object CompileStructName(StructNamePtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"StructName");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:token}
object[L"_token"] = picojson::value(pointer->content);
return object;
}
picojson::object CompileMemberName(MemberNamePtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"MemberName");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:token}
object[L"_token"] = picojson::value(pointer->content);
return object;
}
picojson::object CompileNumberLiteral(NumberLiteralPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"NumberLiteral");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:token}
object[L"_token"] = picojson::value(pointer->content);
return object;
}
picojson::object CompileStringLiteral(StringLiteralPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"StringLiteral");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:token}
object[L"_token"] = picojson::value(pointer->content);
return object;
}
picojson::object CompileTypeIdentifier(TypeIdentifierPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"TypeIdentifier");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:id}
if (pointer->structname)
{
picojson::object structname;
structname = CompileStructName(pointer->structname);
object[L"structname"] = picojson::value(structname);
}
// {:count=>1, :type=>:id}
if (pointer->typevariable)
{
picojson::object typevariable;
typevariable = CompileTypeVariable(pointer->typevariable);
object[L"typevariable"] = picojson::value(typevariable);
}
// {:count=>3, :type=>:id}
picojson::array typeparameterarguments;
for(unsigned i=0; i<pointer->typeparameterarguments.size(); i++)
{
typeparameterarguments.push_back(picojson::value(CompileTypeParameterArguments(pointer->typeparameterarguments[i])));
}
object[L"typeparameterarguments"] = picojson::value(typeparameterarguments);
return object;
}
picojson::object CompileTypeExpression(TypeExpressionPtr pointer)
{
picojson::object object;
// variation
object[L"_type"] = picojson::value(L"TypeExpression");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
picojson::object content;
switch(pointer->get_typeexpression_type())
{
case TYPEIDENTIFIER_TYPEEXPRESSION:
{
content = CompileTypeIdentifier(std::dynamic_pointer_cast<TypeIdentifier>(pointer));
break;
}
}
object[L"_content"] = picojson::value(content);
return object;
}
picojson::object CompileTypeParameterArguments(TypeParameterArgumentsPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"TypeParameterArguments");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>3, :type=>:id}
picojson::array typeexpressions;
for(unsigned i=0; i<pointer->typeexpressions.size(); i++)
{
typeexpressions.push_back(picojson::value(CompileTypeExpression(pointer->typeexpressions[i])));
}
object[L"typeexpressions"] = picojson::value(typeexpressions);
return object;
}
picojson::object CompileTypeDeclaration(TypeDeclarationPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"TypeDeclaration");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:id}
if (pointer->structname)
{
picojson::object structname;
structname = CompileStructName(pointer->structname);
object[L"structname"] = picojson::value(structname);
}
// {:count=>3, :type=>:id}
picojson::array typeparameters;
for(unsigned i=0; i<pointer->typeparameters.size(); i++)
{
typeparameters.push_back(picojson::value(CompileTypeParameters(pointer->typeparameters[i])));
}
object[L"typeparameters"] = picojson::value(typeparameters);
return object;
}
picojson::object CompileTypeParameters(TypeParametersPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"TypeParameters");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>3, :type=>:id}
picojson::array typevariables;
for(unsigned i=0; i<pointer->typevariables.size(); i++)
{
typevariables.push_back(picojson::value(CompileTypeVariable(pointer->typevariables[i])));
}
object[L"typevariables"] = picojson::value(typevariables);
return object;
}
picojson::object CompileNumberLit(NumberLitPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"NumberLit");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:id}
if (pointer->numberliteral)
{
picojson::object numberliteral;
numberliteral = CompileNumberLiteral(pointer->numberliteral);
object[L"numberliteral"] = picojson::value(numberliteral);
}
return object;
}
picojson::object CompileExpression(ExpressionPtr pointer)
{
picojson::object object;
// variation
object[L"_type"] = picojson::value(L"Expression");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
picojson::object content;
switch(pointer->get_expression_type())
{
case NUMBERLIT_EXPRESSION:
{
content = CompileNumberLit(std::dynamic_pointer_cast<NumberLit>(pointer));
break;
}
}
object[L"_content"] = picojson::value(content);
return object;
}
picojson::object CompileAttributeParam(AttributeParamPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"AttributeParam");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:id}
if (pointer->membername)
{
picojson::object membername;
membername = CompileMemberName(pointer->membername);
object[L"membername"] = picojson::value(membername);
}
// {:count=>1, :type=>:id}
if (pointer->expression)
{
picojson::object expression;
expression = CompileExpression(pointer->expression);
object[L"expression"] = picojson::value(expression);
}
return object;
}
picojson::object CompileAttributeParamList(AttributeParamListPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"AttributeParamList");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>3, :type=>:id}
picojson::array attributeparams;
for(unsigned i=0; i<pointer->attributeparams.size(); i++)
{
attributeparams.push_back(picojson::value(CompileAttributeParam(pointer->attributeparams[i])));
}
object[L"attributeparams"] = picojson::value(attributeparams);
return object;
}
picojson::object CompileAttribute(AttributePtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"Attribute");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:id}
if (pointer->typeexpression)
{
picojson::object typeexpression;
typeexpression = CompileTypeExpression(pointer->typeexpression);
object[L"typeexpression"] = picojson::value(typeexpression);
}
// {:count=>3, :type=>:id}
picojson::array attributeparamlists;
for(unsigned i=0; i<pointer->attributeparamlists.size(); i++)
{
attributeparamlists.push_back(picojson::value(CompileAttributeParamList(pointer->attributeparamlists[i])));
}
object[L"attributeparamlists"] = picojson::value(attributeparamlists);
return object;
}
picojson::object CompileMember(MemberPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"Member");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>3, :type=>:id}
picojson::array attributes;
for(unsigned i=0; i<pointer->attributes.size(); i++)
{
attributes.push_back(picojson::value(CompileAttribute(pointer->attributes[i])));
}
object[L"attributes"] = picojson::value(attributes);
// {:count=>1, :type=>:id}
if (pointer->typeidentifier)
{
picojson::object typeidentifier;
typeidentifier = CompileTypeIdentifier(pointer->typeidentifier);
object[L"typeidentifier"] = picojson::value(typeidentifier);
}
// {:count=>3, :type=>:id}
picojson::array membernames;
for(unsigned i=0; i<pointer->membernames.size(); i++)
{
membernames.push_back(picojson::value(CompileMemberName(pointer->membernames[i])));
}
object[L"membernames"] = picojson::value(membernames);
return object;
}
picojson::object CompileFormat(FormatPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"Format");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>3, :type=>:id}
picojson::array attributes;
for(unsigned i=0; i<pointer->attributes.size(); i++)
{
attributes.push_back(picojson::value(CompileAttribute(pointer->attributes[i])));
}
object[L"attributes"] = picojson::value(attributes);
// {:count=>1, :type=>:id}
if (pointer->typedeclaration)
{
picojson::object typedeclaration;
typedeclaration = CompileTypeDeclaration(pointer->typedeclaration);
object[L"typedeclaration"] = picojson::value(typedeclaration);
}
// {:count=>4, :type=>:id}
picojson::array members;
for(unsigned i=0; i<pointer->members.size(); i++)
{
members.push_back(picojson::value(CompileMember(pointer->members[i])));
}
object[L"members"] = picojson::value(members);
return object;
}
picojson::object CompileImport(ImportPtr pointer)
{
picojson::object object;
// normal
object[L"_type"] = picojson::value(L"Import");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
// {:count=>1, :type=>:id}
if (pointer->stringliteral)
{
picojson::object stringliteral;
stringliteral = CompileStringLiteral(pointer->stringliteral);
object[L"stringliteral"] = picojson::value(stringliteral);
}
return object;
}
picojson::object CompileStatement(StatementPtr pointer)
{
picojson::object object;
// variation
object[L"_type"] = picojson::value(L"Statement");
object[L"_col"] = picojson::value((double)pointer->_col);
object[L"_line"] = picojson::value((double)pointer->_line);
picojson::object content;
switch(pointer->get_statement_type())
{
case FORMAT_STATEMENT:
{
content = CompileFormat(std::dynamic_pointer_cast<Format>(pointer));
break;
}
case IMPORT_STATEMENT:
{
content = CompileImport(std::dynamic_pointer_cast<Import>(pointer));
break;
}
}
object[L"_content"] = picojson::value(content);
return object;
}
picojson::value Jsonify(S2Ptr parseResult)
{
return picojson::value(CompileS2(parseResult));
}
}
| 23.488114 | 120 | 0.702517 | [
"object"
] |
b811c56e218a60ec6872fcf5d92a2e38202e8373 | 16,494 | cpp | C++ | testing/sg_tst_context.cpp | beanhuo/sg3_utils | be90b8fe4666ee15a516941fe155c421e40b12d6 | [
"BSD-2-Clause"
] | null | null | null | testing/sg_tst_context.cpp | beanhuo/sg3_utils | be90b8fe4666ee15a516941fe155c421e40b12d6 | [
"BSD-2-Clause"
] | null | null | null | testing/sg_tst_context.cpp | beanhuo/sg3_utils | be90b8fe4666ee15a516941fe155c421e40b12d6 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2013-2018 Douglas Gilbert.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. 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 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 AUTHOR 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 <iostream>
#include <vector>
#include <system_error>
#include <thread>
#include <mutex>
#include <chrono>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "sg_lib.h"
#include "sg_pt.h"
static const char * version_str = "1.03 20180712";
static const char * util_name = "sg_tst_context";
/* This is a test program for checking that file handles keep their
* context properly when sent (synchronous) SCSI pass-through commands.
* A disk device is assumed and even-numbered threads send TEST UNIT
* READY commands while odd-numbered threads send alternating START STOP
* UNIT commands (i.e. start then stop then start, etc). The point is to
* check the results to make sure that they don't get the other command's
* response. For example a START STOP UNIT command should not see a "not
* ready" sense key.
*
* This is C++ code with some things from C++11 (e.g. threads) and was
* only just able to compile (when some things were reverted) with gcc/g++
* version 4.7.3 found in Ubuntu 13.04 . C++11 "feature complete" support
* was not available until g++ version 4.8.1 and that is found in Fedora
* 19 and Ubuntu 13.10 .
*
* The build uses various object files from the <sg3_utils>/lib directory
* which is assumed to be a sibling of this examples directory. Those
* object files in the lib directory can be built with:
* cd <sg3_utils> ; ./configure ; cd lib; make
* Then to build sg_tst_context concatenate the next 3 lines:
* g++ -Wall -std=c++11 -pthread -I ../include ../lib/sg_lib.o
* ../lib/sg_lib_data.o ../lib/sg_pt_linux.o -o sg_tst_context
* sg_tst_context.cpp
* Alternatively use 'make -f Makefile.cplus sg_tst_context'
*
*/
using namespace std;
using namespace std::chrono;
#define DEF_NUM_PER_THREAD 200
#define DEF_NUM_THREADS 2
#define EBUFF_SZ 256
static mutex count_mutex;
static mutex console_mutex;
static unsigned int even_notreadys;
static unsigned int odd_notreadys;
static unsigned int ebusy_count;
static int verbose;
static void
usage(void)
{
printf("Usage: %s [-e] [-h] [-n <n_per_thr>] [-N] [-R] [-s]\n"
" [-t <num_thrs>] [-v] [-V] <disk_device>\n",
util_name);
printf(" where\n");
printf(" -e use O_EXCL on open (def: don't)\n");
printf(" -h print this usage message then exit\n");
printf(" -n <n_per_thr> number of loops per thread "
"(def: %d)\n", DEF_NUM_PER_THREAD);
printf(" -N use O_NONBLOCK on open (def: don't)\n");
printf(" -R make sure device in ready (started) "
"state after\n"
" test (do extra iteration if "
"necessary)\n");
printf(" -s share an open file handle (def: one "
"per thread)\n");
printf(" -t <num_thrs> number of threads (def: %d)\n",
DEF_NUM_THREADS);
printf(" -v increase verbosity\n");
printf(" -V print version number then exit\n\n");
printf("Test if file handles keep context through to their responses. "
"Sends\nTEST UNIT READY commands on even threads (origin 0) and "
"START STOP\nUNIT commands on odd threads. Expect NOT READY "
"sense keys only\nfrom the even threads (i.e from TUR)\n");
}
static int
pt_err(int res)
{
if (res < 0)
fprintf(stderr, " pass through OS error: %s\n", safe_strerror(-res));
else if (SCSI_PT_DO_BAD_PARAMS == res)
fprintf(stderr, " bad pass through setup\n");
else if (SCSI_PT_DO_TIMEOUT == res)
fprintf(stderr, " pass through timeout\n");
else
fprintf(stderr, " do_scsi_pt error=%d\n", res);
return (res < 0) ? res : -EPERM /* -1 */;
}
static int
pt_cat_no_good(int cat, struct sg_pt_base * ptp, const unsigned char * sbp)
{
int slen;
char b[256];
const int bl = (int)sizeof(b);
const char * cp = NULL;
b[0] = '\0';
switch (cat) {
case SCSI_PT_RESULT_STATUS: /* other than GOOD and CHECK CONDITION */
sg_get_scsi_status_str(get_scsi_pt_status_response(ptp), bl, b);
cp = " scsi status: %s\n";
break;
case SCSI_PT_RESULT_SENSE:
slen = get_scsi_pt_sense_len(ptp);
sg_get_sense_str("", sbp, slen, 1, bl, b);
cp = "%s\n";
break;
case SCSI_PT_RESULT_TRANSPORT_ERR:
get_scsi_pt_transport_err_str(ptp, bl, b);
cp = " transport: %s\n";
break;
case SCSI_PT_RESULT_OS_ERR:
get_scsi_pt_os_err_str(ptp, bl, b);
cp = " os: %s\n";
break;
default:
cp = " unknown pt result category (%d)\n";
break;
}
if (cp) {
lock_guard<mutex> lg(console_mutex);
fprintf(stderr, cp, b);
}
return -EIO /* -5 */;
}
#define TUR_CMD_LEN 6
#define SSU_CMD_LEN 6
#define NOT_READY SG_LIB_CAT_NOT_READY
/* Returns 0 for good, 1024 for a sense key of NOT_READY, or a negative
* errno */
static int
do_tur(struct sg_pt_base * ptp, int id)
{
int slen, res, cat;
unsigned char turCmdBlk [TUR_CMD_LEN] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0};
unsigned char sense_buffer[64];
clear_scsi_pt_obj(ptp);
set_scsi_pt_cdb(ptp, turCmdBlk, sizeof(turCmdBlk));
set_scsi_pt_sense(ptp, sense_buffer, sizeof(sense_buffer));
res = do_scsi_pt(ptp, -1, 20 /* secs timeout */, verbose);
if (res) {
{
lock_guard<mutex> lg(console_mutex);
fprintf(stderr, "TEST UNIT READY do_scsi_pt() submission error, "
"id=%d\n", id);
}
res = pt_err(res);
goto err;
}
cat = get_scsi_pt_result_category(ptp);
if (SCSI_PT_RESULT_GOOD != cat) {
slen = get_scsi_pt_sense_len(ptp);
if ((SCSI_PT_RESULT_SENSE == cat) &&
(NOT_READY == sg_err_category_sense(sense_buffer, slen))) {
res = 1024;
goto err;
}
{
lock_guard<mutex> lg(console_mutex);
fprintf(stderr, "TEST UNIT READY do_scsi_pt() category problem, "
"id=%d\n", id);
}
res = pt_cat_no_good(cat, ptp, sense_buffer);
goto err;
}
res = 0;
err:
return res;
}
/* Returns 0 for good, 1024 for a sense key of NOT_READY, or a negative
* errno */
static int
do_ssu(struct sg_pt_base * ptp, int id, bool start)
{
int slen, res, cat;
unsigned char ssuCmdBlk [SSU_CMD_LEN] = {0x1b, 0x0, 0x0, 0x0, 0x0, 0x0};
unsigned char sense_buffer[64];
if (start)
ssuCmdBlk[4] |= 0x1;
clear_scsi_pt_obj(ptp);
set_scsi_pt_cdb(ptp, ssuCmdBlk, sizeof(ssuCmdBlk));
set_scsi_pt_sense(ptp, sense_buffer, sizeof(sense_buffer));
res = do_scsi_pt(ptp, -1, 40 /* secs timeout */, verbose);
if (res) {
{
lock_guard<mutex> lg(console_mutex);
fprintf(stderr, "START STOP UNIT do_scsi_pt() submission error, "
"id=%d\n", id);
}
res = pt_err(res);
goto err;
}
cat = get_scsi_pt_result_category(ptp);
if (SCSI_PT_RESULT_GOOD != cat) {
slen = get_scsi_pt_sense_len(ptp);
if ((SCSI_PT_RESULT_SENSE == cat) &&
(NOT_READY == sg_err_category_sense(sense_buffer, slen))) {
res = 1024;
goto err;
}
{
lock_guard<mutex> lg(console_mutex);
fprintf(stderr, "START STOP UNIT do_scsi_pt() category problem, "
"id=%d\n", id);
}
res = pt_cat_no_good(cat, ptp, sense_buffer);
goto err;
}
res = 0;
err:
return res;
}
static void
work_thread(const char * dev_name, int id, int num, bool share,
int pt_fd, int nonblock, int oexcl, bool ready_after)
{
bool started = true;
int k;
int res = 0;
unsigned int thr_even_notreadys = 0;
unsigned int thr_odd_notreadys = 0;
unsigned int thr_ebusy_count = 0;
struct sg_pt_base * ptp = NULL;
char ebuff[EBUFF_SZ];
{
lock_guard<mutex> lg(console_mutex);
cerr << "Enter work_thread id=" << id << " num=" << num << " share="
<< share << endl;
}
if (! share) { /* ignore passed ptp, make this thread's own */
int oflags = O_RDWR;
if (nonblock)
oflags |= O_NONBLOCK;
if (oexcl)
oflags |= O_EXCL;
while (((pt_fd = scsi_pt_open_flags(dev_name, oflags, verbose)) < 0)
&& (-EBUSY == pt_fd)) {
++thr_ebusy_count;
this_thread::yield(); // give other threads a chance
}
if (pt_fd < 0) {
snprintf(ebuff, EBUFF_SZ, "work_thread id=%d: error opening: %s",
id, dev_name);
perror(ebuff);
return;
}
if (thr_ebusy_count) {
lock_guard<mutex> lg(count_mutex);
ebusy_count += thr_ebusy_count;
}
}
/* The instance of 'struct sg_pt_base' is local to this thread but the
* pt_fd it contains may be shared, depending on the 'share' boolean. */
ptp = construct_scsi_pt_obj_with_fd(pt_fd, verbose);
if (NULL == ptp) {
fprintf(stderr, "work_thread id=%d: "
"construct_scsi_pt_obj_with_fd() failed, memory?\n", id);
return;
}
for (k = 0; k < num; ++k) {
if (0 == (id % 2)) {
/* Even thread ids do TEST UNIT READYs */
res = do_tur(ptp, id);
if (1024 == res) {
++thr_even_notreadys;
res = 0;
}
} else {
/* Odd thread ids do START STOP UNITs, alternating between
* starts and stops */
started = (0 == (k % 2));
res = do_ssu(ptp, id, started);
if (1024 == res) {
++thr_odd_notreadys;
res = 0;
}
}
if (res)
break;
if (ready_after && (! started))
do_ssu(ptp, id, true);
}
if (ptp)
destruct_scsi_pt_obj(ptp);
if ((! share) && (pt_fd >= 0))
close(pt_fd);
{
lock_guard<mutex> lg(count_mutex);
even_notreadys += thr_even_notreadys;
odd_notreadys += thr_odd_notreadys;
}
{
lock_guard<mutex> lg(console_mutex);
if (k < num)
cerr << "thread id=" << id << " FAILed at iteration: " << k
<< " [negated errno: " << res << " <"
<< safe_strerror(-res) << ">]" << endl;
else
cerr << "thread id=" << id << " normal exit" << '\n';
}
}
int
main(int argc, char * argv[])
{
int k;
int pt_fd = -1;
int oexcl = 0;
int nonblock = 0;
int num_per_thread = DEF_NUM_PER_THREAD;
bool ready_after = false;
bool share = false;
int num_threads = DEF_NUM_THREADS;
char * dev_name = NULL;
char ebuff[EBUFF_SZ];
for (k = 1; k < argc; ++k) {
if (0 == memcmp("-e", argv[k], 2))
++oexcl;
else if (0 == memcmp("-h", argv[k], 2)) {
usage();
return 0;
} else if (0 == memcmp("-n", argv[k], 2)) {
++k;
if ((k < argc) && isdigit(*argv[k])) {
num_per_thread = sg_get_num(argv[k]);
if (num_per_thread<= 0) {
fprintf(stderr, "want positive integer for number "
"per thread\n");
return 1;
}
} else
break;
} else if (0 == memcmp("-N", argv[k], 2))
++nonblock;
else if (0 == memcmp("-R", argv[k], 2))
ready_after = true;
else if (0 == memcmp("-s", argv[k], 2))
share = true;
else if (0 == memcmp("-t", argv[k], 2)) {
++k;
if ((k < argc) && isdigit(*argv[k]))
num_threads = atoi(argv[k]);
else
break;
} else if (0 == memcmp("-v", argv[k], 2))
++verbose;
else if (0 == memcmp("-V", argv[k], 2)) {
printf("%s version: %s\n", util_name, version_str);
return 0;
} else if (*argv[k] == '-') {
printf("Unrecognized switch: %s\n", argv[k]);
dev_name = NULL;
break;
}
else if (! dev_name)
dev_name = argv[k];
else {
printf("too many arguments\n");
dev_name = 0;
break;
}
}
if (0 == dev_name) {
usage();
return 1;
}
try {
if (share) {
int oflags = O_RDWR;
if (nonblock)
oflags |= O_NONBLOCK;
if (oexcl)
oflags |= O_EXCL;
while (((pt_fd = scsi_pt_open_flags(dev_name, oflags, verbose))
< 0) && (-EBUSY == pt_fd)) {
++ebusy_count;
sleep(0); // process yield ??
}
if (pt_fd < 0) {
snprintf(ebuff, EBUFF_SZ, "main: error opening: %s",
dev_name);
perror(ebuff);
return 1;
}
/* Tried calling construct_scsi_pt_obj_with_fd() here but that
* doesn't work since 'struct sg_pt_base' objects aren't
* thread-safe without user space intervention (e.g. mutexes). */
}
vector<thread *> vt;
for (k = 0; k < num_threads; ++k) {
thread * tp = new thread {work_thread, dev_name, k,
num_per_thread, share, pt_fd, nonblock,
oexcl, ready_after};
vt.push_back(tp);
}
for (k = 0; k < (int)vt.size(); ++k)
vt[k]->join();
for (k = 0; k < (int)vt.size(); ++k)
delete vt[k];
if (share)
scsi_pt_close_device(pt_fd);
cout << "Expected not_readys on TEST UNIT READY: " << even_notreadys
<< endl;
cout << "UNEXPECTED not_readys on START STOP UNIT: "
<< odd_notreadys << endl;
if (ebusy_count)
cout << "Number of EBUSYs (on open): " << ebusy_count << endl;
}
catch(system_error& e) {
cerr << "got a system_error exception: " << e.what() << '\n';
auto ec = e.code();
cerr << "category: " << ec.category().name() << '\n';
cerr << "value: " << ec.value() << '\n';
cerr << "message: " << ec.message() << '\n';
cerr << "\nNote: if g++ may need '-pthread' or similar in "
"compile/link line" << '\n';
}
catch(...) {
cerr << "got another exception: " << '\n';
}
if (pt_fd >= 0)
close(pt_fd);
return 0;
}
| 32.791252 | 78 | 0.554565 | [
"object",
"vector"
] |
b8135445af043e590807760683ff0c8ae36a8c1f | 2,909 | hpp | C++ | external/bsd/atf/dist/tools/expand.hpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | external/bsd/atf/dist/tools/expand.hpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | external/bsd/atf/dist/tools/expand.hpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | //
// Automated Testing Framework (atf)
//
// Copyright (c) 2007 The NetBSD Foundation, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
//
#if !defined(TOOLS_EXPAND_HPP)
#define TOOLS_EXPAND_HPP
#include <string>
#include <vector>
namespace tools {
namespace expand {
// ------------------------------------------------------------------------
// Free functions.
// ------------------------------------------------------------------------
//!
//! \brief Checks if the given string is a glob pattern.
//!
//! Returns true if the given string is a glob pattern; i.e. if it contains
//! any character that will be expanded by expand_glob.
//!
bool is_glob(const std::string&);
//!
//! \brief Checks if a given string matches a glob pattern.
//!
//! Given a glob pattern and a string, checks whether the former matches
//! the latter. Returns a boolean indicating this condition.
//!
bool matches_glob(const std::string&, const std::string&);
//!
//! \brief Expands a glob pattern among multiple candidates.
//!
//! Given a glob pattern and a set of candidate strings, checks which of
//! those strings match the glob pattern and returns them.
//!
template< class T >
std::vector< std::string > expand_glob(const std::string& glob,
const T& candidates)
{
std::vector< std::string > exps;
for (typename T::const_iterator iter = candidates.begin();
iter != candidates.end(); iter++)
if (matches_glob(glob, *iter))
exps.push_back(*iter);
return exps;
}
} // namespace expand
} // namespace tools
#endif // !defined(TOOLS_EXPAND_HPP)
| 35.048193 | 75 | 0.680303 | [
"vector"
] |
b814a2489e74751ed73528ac81198009ddd771d0 | 2,445 | hpp | C++ | contrib/libboost/boost_1_62_0/boost/range/algorithm/partition.hpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | contrib/libboost/boost_1_62_0/boost/range/algorithm/partition.hpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | contrib/libboost/boost_1_62_0/boost/range/algorithm/partition.hpp | 189569400/ClickHouse | 0b8683c8c9f0e17446bef5498403c39e9cb483b8 | [
"Apache-2.0"
] | 1,343 | 2017-12-08T19:47:19.000Z | 2022-03-26T11:31:36.000Z | // Copyright Neil Groves 2009. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ALGORITHM_PARTITION__HPP_INCLUDED
#define BOOST_RANGE_ALGORITHM_PARTITION__HPP_INCLUDED
#include <boost/concept_check.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <boost/range/detail/range_return.hpp>
#include <algorithm>
namespace boost
{
namespace range
{
/// \brief template function partition
///
/// range-based version of the partition std algorithm
///
/// \pre ForwardRange is a model of the ForwardRangeConcept
template<class ForwardRange, class UnaryPredicate>
inline BOOST_DEDUCED_TYPENAME range_iterator<ForwardRange>::type
partition(ForwardRange& rng, UnaryPredicate pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<ForwardRange> ));
return std::partition(boost::begin(rng),boost::end(rng),pred);
}
/// \overload
template<class ForwardRange, class UnaryPredicate>
inline BOOST_DEDUCED_TYPENAME range_iterator<ForwardRange>::type
partition(const ForwardRange& rng, UnaryPredicate pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
return std::partition(boost::begin(rng),boost::end(rng),pred);
}
// range_return overloads
/// \overload
template< range_return_value re, class ForwardRange,
class UnaryPredicate >
inline BOOST_DEDUCED_TYPENAME range_return<ForwardRange,re>::type
partition(ForwardRange& rng, UnaryPredicate pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<ForwardRange> ));
return boost::range_return<ForwardRange,re>::
pack(std::partition(boost::begin(rng), boost::end(rng), pred), rng);
}
/// \overload
template< range_return_value re, class ForwardRange,
class UnaryPredicate >
inline BOOST_DEDUCED_TYPENAME range_return<const ForwardRange,re>::type
partition(const ForwardRange& rng, UnaryPredicate pred)
{
BOOST_RANGE_CONCEPT_ASSERT(( ForwardRangeConcept<const ForwardRange> ));
return boost::range_return<const ForwardRange,re>::
pack(std::partition(boost::begin(rng), boost::end(rng), pred), rng);
}
} // namespace range
using range::partition;
} // namespace boost
#endif // include guard
| 32.6 | 76 | 0.761554 | [
"model"
] |
b815473c60cbeab0806f94cf36532dc517f445eb | 5,092 | hpp | C++ | src/helper.hpp | gtraines/g13-schneller | 87ba1855cada0e0ceebb0e0188f76cc84e00620a | [
"MIT"
] | null | null | null | src/helper.hpp | gtraines/g13-schneller | 87ba1855cada0e0ceebb0e0188f76cc84e00620a | [
"MIT"
] | null | null | null | src/helper.hpp | gtraines/g13-schneller | 87ba1855cada0e0ceebb0e0188f76cc84e00620a | [
"MIT"
] | null | null | null | /*
* helper.hpp
*
* Miscellaneous helpful little tidbits...
*/
/*
* Copyright (c) 2015, James Fowler
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the
* following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#ifndef __HELPER_HPP__
#define __HELPER_HPP__
#include <boost/lexical_cast.hpp>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/preprocessor/seq.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <iomanip>
#include <exception>
#include <string>
#include <vector>
#include <map>
// *************************************************************************
namespace Helper {
struct string_repr_out {
string_repr_out( const std::string &str ) : s(str) {}
void write_on( std::ostream & ) const;
std::string s;
};
inline std::ostream &operator <<( std::ostream & o, const string_repr_out & sro ) {
sro.write_on( o );
return o;
}
template <class T>
inline const T &repr( const T &v ) { return v; }
inline string_repr_out repr( const char *s ) { return string_repr_out(s); }
inline string_repr_out repr( const std::string & s ) { return string_repr_out(s); }
// *************************************************************************
class NotFoundException : public std::exception {
public:
const char *what() throw ();
};
template <class KEY_T, class VAL_T>
inline const VAL_T &find_or_throw( const std::map<KEY_T,VAL_T> &m, const KEY_T &target ) {
auto i = m.find( target );
if( i == m.end() ) {
throw NotFoundException();
}
return i->second;
};
template <class KEY_T, class VAL_T>
inline VAL_T &find_or_throw( std::map<KEY_T,VAL_T> &m, const KEY_T &target ) {
auto i = m.find( target );
if( i == m.end() ) {
throw NotFoundException();
}
return i->second;
};
// *************************************************************************
template <class T>
class Coord {
public:
Coord() : x(), y() {}
Coord( T _x, T _y ) : x(_x), y(_y) {}
T x;
T y;
};
template <class T>
std::ostream &operator<<( std::ostream &o, const Coord<T> &c ) {
o << "{ " << c.x << " x " << c.y << " }";
return o;
};
template <class T>
class Bounds {
public:
typedef Coord<T> CT;
Bounds( const CT &_tl, const CT &_br) : tl(_tl), br(_br) {}
Bounds( T x1, T y1, T x2, T y2 ) : tl(x1,y1), br(x2,y2) {}
bool contains( const CT &pos ) const {
return tl.x <= pos.x && tl.y <= pos.y && pos.x <= br.x && pos.y <= br.y;
}
void expand( const CT &pos ) {
if( pos.x < tl.x ) tl.x = pos.x;
if( pos.y < tl.y ) tl.y = pos.y;
if( pos.x > br.x ) br.x = pos.x;
if( pos.y > br.y ) br.y = pos.y;
}
CT tl;
CT br;
};
template <class T>
std::ostream &operator<<( std::ostream &o, const Bounds<T> &b ) {
o << "{ " << b.tl.x << " x " << b.tl.y << " / " << b.br.x << " x " << b.br.y << " }";
return o;
};
// *************************************************************************
typedef const char * CCP;
inline const char *advance_ws(CCP &source, std::string &dest) {
const char *space = source ? strchr(source, ' ') : 0;
if (space) {
dest = std::string(source, space - source);
source = space + 1;
} else {
dest = source;
source = 0;
}
return source;
};
// *************************************************************************
template <class MAP_T>
struct _map_keys_out {
_map_keys_out( const MAP_T&c, const std::string &s ) : container(c), sep(s) {}
const MAP_T&container;
std::string sep;
};
template <class STREAM_T, class MAP_T>
STREAM_T &operator <<( STREAM_T &o, const _map_keys_out<MAP_T> &_mko ) {
bool first = true;
for( auto i = _mko.container.begin(); i != _mko.container.end(); i++ ) {
if( first ) {
first = false;
o << i->first;
} else {
o << _mko.sep << i->first;
}
}
};
template <class MAP_T>
_map_keys_out<MAP_T> map_keys_out( const MAP_T &c, const std::string &sep = " " ) {
return _map_keys_out<MAP_T>( c, sep );
};
// *************************************************************************
}; // namespace Helper
// *************************************************************************
#endif // __HELPER_HPP__
| 25.847716 | 90 | 0.585625 | [
"vector"
] |
b8216a6d58da0ce6e4f3cbc7e3f2eeb5fd9ab453 | 7,920 | cpp | C++ | caffe/src/caffe/layers/lifted_struct_similarity_softmax_layer.cpp | BlancRay/SeqFace | 72bdeb1d5f463df9c8c164466f3a7125421b975c | [
"MIT"
] | 136 | 2018-03-20T01:26:36.000Z | 2022-02-07T12:05:43.000Z | caffe/src/caffe/layers/lifted_struct_similarity_softmax_layer.cpp | BlancRay/SeqFace | 72bdeb1d5f463df9c8c164466f3a7125421b975c | [
"MIT"
] | 18 | 2018-03-20T08:06:53.000Z | 2021-02-22T11:59:47.000Z | caffe/src/caffe/layers/lifted_struct_similarity_softmax_layer.cpp | BlancRay/SeqFace | 72bdeb1d5f463df9c8c164466f3a7125421b975c | [
"MIT"
] | 33 | 2018-03-20T02:13:33.000Z | 2022-02-07T12:05:44.000Z | #include <algorithm>
#include <vector>
#include "caffe/layers/lifted_struct_similarity_softmax_layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void LiftedStructSimilaritySoftmaxLossLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
LossLayer<Dtype>::LayerSetUp(bottom, top);
CHECK_EQ(bottom[0]->height(), 1);
CHECK_EQ(bottom[0]->width(), 1);
CHECK_EQ(bottom[1]->channels(), 1);
CHECK_EQ(bottom[1]->height(), 1);
CHECK_EQ(bottom[1]->width(), 1);
// List of member variables defined in /include/caffe/loss_layers.hpp;
// diff_, dist_sq_, summer_vec_, loss_aug_inference_;
dist_sq_.Reshape(bottom[0]->num(), 1, 1, 1);
dot_.Reshape(bottom[0]->num(), bottom[0]->num(), 1, 1);
ones_.Reshape(bottom[0]->num(), 1, 1, 1); // n by 1 vector of ones.
for (int i=0; i < bottom[0]->num(); ++i){
ones_.mutable_cpu_data()[i] = Dtype(1);
}
blob_pos_diff_.Reshape(bottom[0]->channels(), 1, 1, 1);
blob_neg_diff_.Reshape(bottom[0]->channels(), 1, 1, 1);
}
template <typename Dtype>
void LiftedStructSimilaritySoftmaxLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) {
const int channels = bottom[0]->channels();
for (int i = 0; i < bottom[0]->num(); i++){
dist_sq_.mutable_cpu_data()[i] = caffe_cpu_dot(channels, bottom[0]->cpu_data() + (i*channels), bottom[0]->cpu_data() + (i*channels));
}
int M_ = bottom[0]->num();
int N_ = bottom[0]->num();
int K_ = bottom[0]->channels();
const Dtype* bottom_data1 = bottom[0]->cpu_data();
const Dtype* bottom_data2 = bottom[0]->cpu_data();
Dtype dot_scaler(-2.0);
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, M_, N_, K_, dot_scaler, bottom_data1, bottom_data2, (Dtype)0., dot_.mutable_cpu_data());
// add ||x_i||^2 to all elements in row i
for (int i=0; i<N_; i++){
caffe_axpy(N_, dist_sq_.cpu_data()[i], ones_.cpu_data(), dot_.mutable_cpu_data() + i*N_);
}
// add the norm vector to row i
for (int i=0; i<N_; i++){
caffe_axpy(N_, Dtype(1.0), dist_sq_.cpu_data(), dot_.mutable_cpu_data() + i*N_);
}
// construct pairwise label matrix
vector<vector<bool> > label_mat(N_, vector<bool>(N_, false));
for (int i=0; i<N_; i++){
for (int j=0; j<N_; j++){
label_mat[i][j] = (bottom[1]->cpu_data()[i] == bottom[1]->cpu_data()[j]);
}
}
Dtype margin = this->layer_param_.lifted_struct_sim_softmax_loss_param().margin();
Dtype loss(0.0);
num_constraints = Dtype(0.0);
const Dtype* bin = bottom[0]->cpu_data();
Dtype* bout = bottom[0]->mutable_cpu_diff();
// zero initialize bottom[0]->mutable_cpu_diff();
for (int i=0; i<N_; i++){
caffe_set(K_, Dtype(0.0), bout + i*K_);
}
// loop upper triangular matrix and look for positive anchors
for (int i=0; i<N_; i++){
for (int j=i+1; j<N_; j++){
// found a positive pair @ anchor (i, j)
if (label_mat[i][j]){
Dtype dist_pos = sqrt(dot_.cpu_data()[i*N_ + j]);
caffe_sub(K_, bin + i*K_, bin + j*K_, blob_pos_diff_.mutable_cpu_data());
// 1.count the number of negatives for this positive
int num_negatives = 0;
for (int k=0; k<N_; k++){
if (!label_mat[i][k]){
num_negatives += 1;
}
}
for (int k=0; k<N_; k++){
if (!label_mat[j][k]){
num_negatives += 1;
}
}
loss_aug_inference_.Reshape(num_negatives, 1, 1, 1);
// vector of ones used to sum along channels
summer_vec_.Reshape(num_negatives, 1, 1, 1);
for (int ss = 0; ss < num_negatives; ++ss){
summer_vec_.mutable_cpu_data()[ss] = Dtype(1);
}
// 2. compute loss augmented inference
int neg_idx = 0;
// mine negative (anchor i, neg k)
for (int k=0; k<N_; k++){
if (!label_mat[i][k]){
loss_aug_inference_.mutable_cpu_data()[neg_idx] = margin - sqrt(dot_.cpu_data()[i*N_ + k]);
neg_idx++;
}
}
// mine negative (anchor j, neg k)
for (int k=0; k<N_; k++){
if (!label_mat[j][k]){
loss_aug_inference_.mutable_cpu_data()[neg_idx] = margin - sqrt(dot_.cpu_data()[j*N_ + k]);
neg_idx++;
}
}
// compute softmax of loss aug inference vector;
Dtype max_elem = *std::max_element(loss_aug_inference_.cpu_data(), loss_aug_inference_.cpu_data() + num_negatives);
caffe_add_scalar(loss_aug_inference_.count(), Dtype(-1.0)*max_elem, loss_aug_inference_.mutable_cpu_data());
caffe_exp(loss_aug_inference_.count(), loss_aug_inference_.mutable_cpu_data(), loss_aug_inference_.mutable_cpu_data());
Dtype soft_maximum = log(caffe_cpu_dot(num_negatives, summer_vec_.cpu_data(), loss_aug_inference_.mutable_cpu_data())) + max_elem;
// hinge the soft_maximum - S_ij (positive pair similarity)
Dtype this_loss = std::max(soft_maximum + dist_pos, Dtype(0.0));
// squared hinge
loss += this_loss * this_loss;
num_constraints += Dtype(1.0);
// 3. compute gradients
Dtype sum_exp = caffe_cpu_dot(num_negatives, summer_vec_.cpu_data(), loss_aug_inference_.mutable_cpu_data());
// update from positive distance dJ_dD_{ij}; update x_i, x_j
Dtype scaler(0.0);
scaler = Dtype(2.0)*this_loss / dist_pos;
// update x_i
caffe_axpy(K_, scaler * Dtype(1.0), blob_pos_diff_.cpu_data(), bout + i*K_);
// update x_j
caffe_axpy(K_, scaler * Dtype(-1.0), blob_pos_diff_.cpu_data(), bout + j*K_);
// update from negative distance dJ_dD_{ik}; update x_i, x_k
neg_idx = 0;
Dtype dJ_dDik(0.0);
for (int k=0; k<N_; k++){
if (!label_mat[i][k]){
caffe_sub(K_, bin + i*K_, bin + k*K_, blob_neg_diff_.mutable_cpu_data());
dJ_dDik = Dtype(2.0)*this_loss * Dtype(-1.0)* loss_aug_inference_.cpu_data()[neg_idx] / sum_exp;
neg_idx++;
scaler = dJ_dDik / sqrt(dot_.cpu_data()[i*N_ + k]);
// update x_i
caffe_axpy(K_, scaler * Dtype(1.0), blob_neg_diff_.cpu_data(), bout + i*K_);
// update x_k
caffe_axpy(K_, scaler * Dtype(-1.0), blob_neg_diff_.cpu_data(), bout + k*K_);
}
}
// update from negative distance dJ_dD_{jk}; update x_j, x_k
Dtype dJ_dDjk(0.0);
for (int k=0; k<N_; k++){
if (!label_mat[j][k]){
caffe_sub(K_, bin + j*K_, bin + k*K_, blob_neg_diff_.mutable_cpu_data());
dJ_dDjk = Dtype(2.0)*this_loss * Dtype(-1.0)*loss_aug_inference_.cpu_data()[neg_idx] / sum_exp;
neg_idx++;
scaler = dJ_dDjk / sqrt(dot_.cpu_data()[j*N_ + k]);
// update x_j
caffe_axpy(K_, scaler * Dtype(1.0), blob_neg_diff_.cpu_data(), bout + j*K_);
// update x_k
caffe_axpy(K_, scaler * Dtype(-1.0), blob_neg_diff_.cpu_data(), bout + k*K_);
}
}
} // close this postive pair
}
}
loss = loss / num_constraints / Dtype(2.0);
top[0]->mutable_cpu_data()[0] = loss;
}
template <typename Dtype>
void LiftedStructSimilaritySoftmaxLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
const Dtype alpha = top[0]->cpu_diff()[0] / num_constraints / Dtype(2.0);
int num = bottom[0]->num();
int channels = bottom[0]->channels();
for (int i = 0; i < num; i++){
Dtype* bout = bottom[0]->mutable_cpu_diff();
caffe_scal(channels, alpha, bout + (i*channels));
}
}
#ifdef CPU_ONLY
STUB_GPU(LiftedStructSimilaritySoftmaxLossLayer);
#endif
INSTANTIATE_CLASS(LiftedStructSimilaritySoftmaxLossLayer);
REGISTER_LAYER_CLASS(LiftedStructSimilaritySoftmaxLoss);
} // namespace caffe
| 36 | 138 | 0.615278 | [
"vector"
] |
b821a0bc5fed6b4fcd1a472ee990cd49f95ba337 | 7,399 | cpp | C++ | aws-cpp-sdk-ec2/source/model/VpcEndpointConnection.cpp | crazecdwn/aws-sdk-cpp | e74b9181a56e82ee04cf36a4cb31686047f4be42 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-ec2/source/model/VpcEndpointConnection.cpp | crazecdwn/aws-sdk-cpp | e74b9181a56e82ee04cf36a4cb31686047f4be42 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-ec2/source/model/VpcEndpointConnection.cpp | crazecdwn/aws-sdk-cpp | e74b9181a56e82ee04cf36a4cb31686047f4be42 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/ec2/model/VpcEndpointConnection.h>
#include <aws/core/utils/xml/XmlSerializer.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Utils::Xml;
using namespace Aws::Utils;
namespace Aws
{
namespace EC2
{
namespace Model
{
VpcEndpointConnection::VpcEndpointConnection() :
m_serviceIdHasBeenSet(false),
m_vpcEndpointIdHasBeenSet(false),
m_vpcEndpointOwnerHasBeenSet(false),
m_vpcEndpointState(State::NOT_SET),
m_vpcEndpointStateHasBeenSet(false),
m_creationTimestampHasBeenSet(false),
m_dnsEntriesHasBeenSet(false),
m_networkLoadBalancerArnsHasBeenSet(false)
{
}
VpcEndpointConnection::VpcEndpointConnection(const XmlNode& xmlNode) :
m_serviceIdHasBeenSet(false),
m_vpcEndpointIdHasBeenSet(false),
m_vpcEndpointOwnerHasBeenSet(false),
m_vpcEndpointState(State::NOT_SET),
m_vpcEndpointStateHasBeenSet(false),
m_creationTimestampHasBeenSet(false),
m_dnsEntriesHasBeenSet(false),
m_networkLoadBalancerArnsHasBeenSet(false)
{
*this = xmlNode;
}
VpcEndpointConnection& VpcEndpointConnection::operator =(const XmlNode& xmlNode)
{
XmlNode resultNode = xmlNode;
if(!resultNode.IsNull())
{
XmlNode serviceIdNode = resultNode.FirstChild("serviceId");
if(!serviceIdNode.IsNull())
{
m_serviceId = StringUtils::Trim(serviceIdNode.GetText().c_str());
m_serviceIdHasBeenSet = true;
}
XmlNode vpcEndpointIdNode = resultNode.FirstChild("vpcEndpointId");
if(!vpcEndpointIdNode.IsNull())
{
m_vpcEndpointId = StringUtils::Trim(vpcEndpointIdNode.GetText().c_str());
m_vpcEndpointIdHasBeenSet = true;
}
XmlNode vpcEndpointOwnerNode = resultNode.FirstChild("vpcEndpointOwner");
if(!vpcEndpointOwnerNode.IsNull())
{
m_vpcEndpointOwner = StringUtils::Trim(vpcEndpointOwnerNode.GetText().c_str());
m_vpcEndpointOwnerHasBeenSet = true;
}
XmlNode vpcEndpointStateNode = resultNode.FirstChild("vpcEndpointState");
if(!vpcEndpointStateNode.IsNull())
{
m_vpcEndpointState = StateMapper::GetStateForName(StringUtils::Trim(vpcEndpointStateNode.GetText().c_str()).c_str());
m_vpcEndpointStateHasBeenSet = true;
}
XmlNode creationTimestampNode = resultNode.FirstChild("creationTimestamp");
if(!creationTimestampNode.IsNull())
{
m_creationTimestamp = DateTime(StringUtils::Trim(creationTimestampNode.GetText().c_str()).c_str(), DateFormat::ISO_8601);
m_creationTimestampHasBeenSet = true;
}
XmlNode dnsEntriesNode = resultNode.FirstChild("dnsEntrySet");
if(!dnsEntriesNode.IsNull())
{
XmlNode dnsEntriesMember = dnsEntriesNode.FirstChild("item");
while(!dnsEntriesMember.IsNull())
{
m_dnsEntries.push_back(dnsEntriesMember);
dnsEntriesMember = dnsEntriesMember.NextNode("item");
}
m_dnsEntriesHasBeenSet = true;
}
XmlNode networkLoadBalancerArnsNode = resultNode.FirstChild("networkLoadBalancerArnSet");
if(!networkLoadBalancerArnsNode.IsNull())
{
XmlNode networkLoadBalancerArnsMember = networkLoadBalancerArnsNode.FirstChild("item");
while(!networkLoadBalancerArnsMember.IsNull())
{
m_networkLoadBalancerArns.push_back(StringUtils::Trim(networkLoadBalancerArnsMember.GetText().c_str()));
networkLoadBalancerArnsMember = networkLoadBalancerArnsMember.NextNode("item");
}
m_networkLoadBalancerArnsHasBeenSet = true;
}
}
return *this;
}
void VpcEndpointConnection::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const
{
if(m_serviceIdHasBeenSet)
{
oStream << location << index << locationValue << ".ServiceId=" << StringUtils::URLEncode(m_serviceId.c_str()) << "&";
}
if(m_vpcEndpointIdHasBeenSet)
{
oStream << location << index << locationValue << ".VpcEndpointId=" << StringUtils::URLEncode(m_vpcEndpointId.c_str()) << "&";
}
if(m_vpcEndpointOwnerHasBeenSet)
{
oStream << location << index << locationValue << ".VpcEndpointOwner=" << StringUtils::URLEncode(m_vpcEndpointOwner.c_str()) << "&";
}
if(m_vpcEndpointStateHasBeenSet)
{
oStream << location << index << locationValue << ".VpcEndpointState=" << StateMapper::GetNameForState(m_vpcEndpointState) << "&";
}
if(m_creationTimestampHasBeenSet)
{
oStream << location << index << locationValue << ".CreationTimestamp=" << StringUtils::URLEncode(m_creationTimestamp.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_dnsEntriesHasBeenSet)
{
unsigned dnsEntriesIdx = 1;
for(auto& item : m_dnsEntries)
{
Aws::StringStream dnsEntriesSs;
dnsEntriesSs << location << index << locationValue << ".DnsEntrySet." << dnsEntriesIdx++;
item.OutputToStream(oStream, dnsEntriesSs.str().c_str());
}
}
if(m_networkLoadBalancerArnsHasBeenSet)
{
unsigned networkLoadBalancerArnsIdx = 1;
for(auto& item : m_networkLoadBalancerArns)
{
oStream << location << index << locationValue << ".NetworkLoadBalancerArnSet." << networkLoadBalancerArnsIdx++ << "=" << StringUtils::URLEncode(item.c_str()) << "&";
}
}
}
void VpcEndpointConnection::OutputToStream(Aws::OStream& oStream, const char* location) const
{
if(m_serviceIdHasBeenSet)
{
oStream << location << ".ServiceId=" << StringUtils::URLEncode(m_serviceId.c_str()) << "&";
}
if(m_vpcEndpointIdHasBeenSet)
{
oStream << location << ".VpcEndpointId=" << StringUtils::URLEncode(m_vpcEndpointId.c_str()) << "&";
}
if(m_vpcEndpointOwnerHasBeenSet)
{
oStream << location << ".VpcEndpointOwner=" << StringUtils::URLEncode(m_vpcEndpointOwner.c_str()) << "&";
}
if(m_vpcEndpointStateHasBeenSet)
{
oStream << location << ".VpcEndpointState=" << StateMapper::GetNameForState(m_vpcEndpointState) << "&";
}
if(m_creationTimestampHasBeenSet)
{
oStream << location << ".CreationTimestamp=" << StringUtils::URLEncode(m_creationTimestamp.ToGmtString(DateFormat::ISO_8601).c_str()) << "&";
}
if(m_dnsEntriesHasBeenSet)
{
unsigned dnsEntriesIdx = 1;
for(auto& item : m_dnsEntries)
{
Aws::StringStream dnsEntriesSs;
dnsEntriesSs << location << ".DnsEntrySet." << dnsEntriesIdx++;
item.OutputToStream(oStream, dnsEntriesSs.str().c_str());
}
}
if(m_networkLoadBalancerArnsHasBeenSet)
{
unsigned networkLoadBalancerArnsIdx = 1;
for(auto& item : m_networkLoadBalancerArns)
{
oStream << location << ".NetworkLoadBalancerArnSet." << networkLoadBalancerArnsIdx++ << "=" << StringUtils::URLEncode(item.c_str()) << "&";
}
}
}
} // namespace Model
} // namespace EC2
} // namespace Aws
| 34.096774 | 173 | 0.707393 | [
"model"
] |
b82397dee3fc03154786dee48855a7ed5c4f34e7 | 9,110 | cpp | C++ | src/services/processFileSystem/processFileSystem.cpp | patrick-lafferty/saturn | 6dc36adb42ad9b647704dd19247423a522eeb551 | [
"BSD-3-Clause"
] | 26 | 2018-03-19T15:59:46.000Z | 2021-08-06T16:13:16.000Z | src/services/processFileSystem/processFileSystem.cpp | patrick-lafferty/saturn | 6dc36adb42ad9b647704dd19247423a522eeb551 | [
"BSD-3-Clause"
] | 34 | 2018-01-21T17:43:29.000Z | 2020-06-27T02:00:53.000Z | src/services/processFileSystem/processFileSystem.cpp | patrick-lafferty/saturn | 6dc36adb42ad9b647704dd19247423a522eeb551 | [
"BSD-3-Clause"
] | 3 | 2019-12-08T22:26:35.000Z | 2021-06-25T17:05:57.000Z | /*
Copyright (c) 2017, Patrick Lafferty
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 "processFileSystem.h"
#include <services.h>
#include <system_calls.h>
#include <string.h>
#include <services/virtualFileSystem/virtualFileSystem.h>
#include <stdio.h>
#include "object.h"
#include <stdlib.h>
#include <vector>
#include <saturn/parsing.h>
using namespace VirtualFileSystem;
using namespace Vostok;
namespace PFS {
bool findObject(std::vector<ProcessObject>& objects, uint32_t pid, ProcessObject** found) {
for (auto& object : objects) {
if (object.pid == pid) {
*found = &object;
return true;
}
}
return false;
}
void handleOpenRequest(OpenRequest& request, std::vector<ProcessObject>& processes, std::vector<FileDescriptor>& openDescriptors) {
bool failed {true};
OpenResult result;
result.requestId = request.requestId;
result.serviceType = Kernel::ServiceType::VFS;
result.type = FileDescriptorType::Vostok;
auto addDescriptor = [&](auto instance, auto id, auto type) {
failed = false;
result.success = true;
openDescriptors.push_back({instance, {static_cast<uint32_t>(id)}, type, 0});
result.fileDescriptor = openDescriptors.size() - 1;
};
auto words = split({request.path, strlen(request.path)}, '/');
if (words.size() > 0) {
char pidString[11];
memset(pidString, '\0', sizeof(pidString));
words[0].copy(pidString, words[1].length());
uint32_t pid = strtol(pidString, nullptr, 10);
ProcessObject* process;
auto found = findObject(processes, pid, &process);
if (found) {
if (words.size() > 1) {
//path is /process/<pid>/<function or property>
auto functionId = process->getFunction(words[1]);
if (functionId >= 0) {
addDescriptor(process, functionId, DescriptorType::Function);
}
else {
auto propertyId = process->getProperty(words[1]);
if (propertyId >= 0) {
addDescriptor(process, propertyId, DescriptorType::Property);
}
}
}
else {
//its the process object itself
addDescriptor(process, 0, DescriptorType::Object);
}
}
else if (words.size() == 1 && words[0].compare("process") == 0) {
//its the process object itself
addDescriptor(nullptr, 0, DescriptorType::Object);
}
}
else {
addDescriptor(nullptr, 0, DescriptorType::Object);
}
if (failed) {
result.success = false;
}
send(IPC::RecipientType::ServiceName, &result);
}
void handleCreateRequest(CreateRequest& request, std::vector<ProcessObject>& processes) {
bool failed {true};
CreateResult result;
result.requestId = request.requestId;
result.serviceType = Kernel::ServiceType::VFS;
auto words = split({request.path, strlen(request.path)}, '/');
char pidString[11];
memset(pidString, '\0', sizeof(pidString));
words[0].copy(pidString, words[0].length());
uint32_t pid = strtol(pidString, nullptr, 10);
ProcessObject* process;
auto found = findObject(processes, pid, &process);
if (!found) {
ProcessObject p {pid};
processes.push_back(p);
failed = false;
result.success = true;
}
if (failed) {
result.success = false;
}
send(IPC::RecipientType::ServiceName, &result);
}
void handleReadRequest(ReadRequest& request, std::vector<FileDescriptor>& openDescriptors) {
auto& descriptor = openDescriptors[request.fileDescriptor];
if (descriptor.type == DescriptorType::Object) {
ReadResult result;
result.requestId = request.requestId;
result.success = true;
ArgBuffer args{result.buffer, sizeof(result.buffer)};
args.writeType(ArgTypes::Property);
if (descriptor.instance == nullptr) {
//its the main /process thing, return a list of all objects
for (auto& desc : openDescriptors) {
if (desc.instance != nullptr) {
args.writeValueWithType(static_cast<ProcessObject*>(desc.instance)->pid, ArgTypes::Uint32);
}
}
}
else {
//its a process object, return a summary of it
descriptor.instance->readSelf(request.senderTaskId, request.requestId);
return;
}
args.writeType(ArgTypes::EndArg);
result.recipientId = request.senderTaskId;
send(IPC::RecipientType::TaskId, &result);
}
else {
descriptor.read(request.senderTaskId, request.requestId);
}
}
void handleWriteRequest(WriteRequest& request, std::vector<FileDescriptor>& openDescriptors) {
ArgBuffer args{request.buffer, sizeof(request.buffer)};
openDescriptors[request.fileDescriptor].write(request.senderTaskId, request.requestId, args);
}
void messageLoop() {
std::vector<ProcessObject> processes;
std::vector<FileDescriptor> openDescriptors;
while (true) {
IPC::MaximumMessageBuffer buffer;
receive(&buffer);
switch(buffer.messageNamespace) {
case IPC::MessageNamespace::VFS: {
switch(static_cast<MessageId>(buffer.messageId)) {
case MessageId::OpenRequest: {
auto request = IPC::extractMessage<OpenRequest>(buffer);
handleOpenRequest(request, processes, openDescriptors);
break;
}
case MessageId::CreateRequest: {
auto request = IPC::extractMessage<CreateRequest>(buffer);
handleCreateRequest(request, processes);
break;
}
case MessageId::ReadRequest: {
auto request = IPC::extractMessage<ReadRequest>(buffer);
handleReadRequest(request, openDescriptors);
break;
}
case MessageId::WriteRequest: {
auto request = IPC::extractMessage<WriteRequest>(buffer);
handleWriteRequest(request, openDescriptors);
break;
}
default:
break;
}
break;
}
default:
break;
}
}
}
void service() {
waitForServiceRegistered(Kernel::ServiceType::VFS);
MountRequest request;
const char* path = "/process";
memcpy(request.path, path, strlen(path) + 1);
request.serviceType = Kernel::ServiceType::VFS;
request.cacheable = false;
send(IPC::RecipientType::ServiceName, &request);
messageLoop();
}
} | 37.336066 | 135 | 0.572887 | [
"object",
"vector"
] |
b824138b06816f13dfa138cfd4d0f2cfa1e24236 | 1,482 | cc | C++ | ddoscoo/src/model/ConfigNetworkRulesRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | ddoscoo/src/model/ConfigNetworkRulesRequest.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | ddoscoo/src/model/ConfigNetworkRulesRequest.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ddoscoo/model/ConfigNetworkRulesRequest.h>
using AlibabaCloud::Ddoscoo::Model::ConfigNetworkRulesRequest;
ConfigNetworkRulesRequest::ConfigNetworkRulesRequest() :
RpcServiceRequest("ddoscoo", "2020-01-01", "ConfigNetworkRules")
{
setMethod(HttpRequest::Method::Post);
}
ConfigNetworkRulesRequest::~ConfigNetworkRulesRequest()
{}
std::string ConfigNetworkRulesRequest::getNetworkRules()const
{
return networkRules_;
}
void ConfigNetworkRulesRequest::setNetworkRules(const std::string& networkRules)
{
networkRules_ = networkRules;
setParameter("NetworkRules", networkRules);
}
std::string ConfigNetworkRulesRequest::getSourceIp()const
{
return sourceIp_;
}
void ConfigNetworkRulesRequest::setSourceIp(const std::string& sourceIp)
{
sourceIp_ = sourceIp;
setParameter("SourceIp", sourceIp);
}
| 28.5 | 81 | 0.761808 | [
"model"
] |
b82502938db98a1d3e0b6eee5ed57deae06e79d5 | 945 | cpp | C++ | codes/leetcode/NonoverlappingIntervals.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | codes/leetcode/NonoverlappingIntervals.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | codes/leetcode/NonoverlappingIntervals.cpp | smmehrab/problem-solving | 4aeab1673f18d3270ee5fc9b64ed6805eacf4af5 | [
"MIT"
] | null | null | null | /*
************************************************
username : smmehrab
fullname : s.m.mehrabul islam
email : mehrab.24csedu.001@gmail.com
institute : university of dhaka, bangladesh
session : 2017-2018
************************************************
*/
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
int numberOfIntervals = intervals.size();
if(numberOfIntervals == 0) return 0;
sort(intervals.begin(), intervals.end(), [&](vector<int> a, vector<int> b) {
return a[1] < b[1];
});
int maximumEndTime = INT_MIN;
int minOverlapped = numberOfIntervals;
for(vector<int> interval : intervals){
if(interval[0] >= maximumEndTime){
minOverlapped--;
maximumEndTime = interval[1];
}
}
return minOverlapped;
}
}; | 30.483871 | 84 | 0.499471 | [
"vector"
] |
b82baa84f12e0f29ca0fa76d0bb91ead03b422fd | 1,019 | cpp | C++ | ArtificialIntelligence/StatisticsAndMachineLearning/BasicStatisticsWarmup/basic_statistics_warmup.cpp | suzyz/HackerRank | e97f76c4b39aa448e43e30b479d9718b8b88b2d2 | [
"MIT"
] | null | null | null | ArtificialIntelligence/StatisticsAndMachineLearning/BasicStatisticsWarmup/basic_statistics_warmup.cpp | suzyz/HackerRank | e97f76c4b39aa448e43e30b479d9718b8b88b2d2 | [
"MIT"
] | null | null | null | ArtificialIntelligence/StatisticsAndMachineLearning/BasicStatisticsWarmup/basic_statistics_warmup.cpp | suzyz/HackerRank | e97f76c4b39aa448e43e30b479d9718b8b88b2d2 | [
"MIT"
] | null | null | null | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 2502;
int n,d[maxn];
int main() {
int mode = 0;
/* sd: stanstard deviation */
double sum = 0, mean = 0, median = 0, sd = 0 ,lower_boundary, upper_boundary;
scanf("%d",&n);
for (int i = 0; i < n; ++i)
{
scanf("%d",&d[i]);
sum += d[i];
}
mean = sum/n;
sort (d,d+n);
median = (1.0 * d[(n>>1)] + d[((n-1)>>1)])/2.0;
int count = 1, max_count = 1;
mode = d[0];
int i = 1;
while (i<n)
{
if (d[i]==d[i-1])
{
++count;
if (count>max_count)
{
max_count = count;
mode = d[i];
}
}
else
count = 1;
++i;
}
for (int i = 0; i < n; ++i)
sd += 1.0*(d[i] - mean)*(d[i] - mean);
sd /= n;
sd = sqrt(sd);
lower_boundary = 1.96 * sd / sqrt(n);
upper_boundary = mean + lower_boundary;
lower_boundary = mean - lower_boundary;
printf("%.1f\n%.1f\n%d\n%.1f\n%.1f %.1f\n",mean,median,mode,sd,lower_boundary,upper_boundary);
return 0;
}
| 16.704918 | 95 | 0.546614 | [
"vector"
] |
b837a3b882fef724df27cacb8730efaad38db7ac | 2,091 | cpp | C++ | C++/Codeforces/cf-678/main.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | C++/Codeforces/cf-678/main.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | C++/Codeforces/cf-678/main.cpp | Nicu-Ducal/Competitive-Programming | c84126a4cb701b0764664db490b7e594495c8592 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
template <typename T> ostream& operator<<(ostream &os, const vector<T> &v) { os << '{'; string sep; for (const auto &x : v) os << sep << x, sep = ", "; return os << '}'; }
template <typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
using i64 = long long int;
const int INF = INT_MAX, MOD = 1e9 + 7;
const double EPS = 1e-9, PI = acos(-1);
const int dx[] = {0, 0, 0, -1, 1, -1, 1, 1, -1};
const int dy[] = {0, -1, 1, 0, 0, -1, 1, -1, 1};
struct Graph {
vector<vector<int>> adj;
vector<i64> pop, leaves, sum;
vector<bool> marked;
int n;
Graph(int _n = 0) {
init(_n);
}
void init(int _n) {
n = _n;
adj.resize(n + 1);
pop.resize(n + 1);
leaves.resize(n + 1);
sum.resize(n + 1);
}
void addEdge(int u, int v) {
adj[u].push_back(v);
}
/// Idea: To count the max number of citizens, just take the max of the sum[curent_node]/nr. of
/// leaves that are in this subtree and curent maximum, which can be maximum of a leaf node
i64 DFS(int node) {
i64 mx = 0;
if (adj[node].empty()) {
leaves[node] = 1;
sum[node] = pop[node];
return pop[node];
} else {
for (auto next: adj[node]) {
mx = max(mx, DFS(next));
leaves[node] += leaves[next];
sum[node] += sum[next];
}
sum[node] += pop[node];
mx = max(mx, sum[node] / leaves[node] + (sum[node] % leaves[node] != 0));
return mx;
}
}
};
int main() {
ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
/// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
int n;
cin >> n;
Graph g(n);
for (int i = 2; i <= n; i++) {
int u;
cin >> u;
g.addEdge(u, i);
}
for (int i = 1; i <= n; i++) cin >> g.pop[i];
cout << g.DFS(1);
return 0;
} | 29.041667 | 171 | 0.496891 | [
"vector"
] |
b8396ad0df2e35b3174e91ce8c9493097bffb1e7 | 8,022 | cpp | C++ | Dev/Cpp/EffekseerRendererLLGI/EffekseerRendererLLGI.ModelRenderer.cpp | riccardobl/Effekseer | 40dea55d7d2fafa365e4365adfe58a1059a5a980 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Dev/Cpp/EffekseerRendererLLGI/EffekseerRendererLLGI.ModelRenderer.cpp | riccardobl/Effekseer | 40dea55d7d2fafa365e4365adfe58a1059a5a980 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Dev/Cpp/EffekseerRendererLLGI/EffekseerRendererLLGI.ModelRenderer.cpp | riccardobl/Effekseer | 40dea55d7d2fafa365e4365adfe58a1059a5a980 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
#include "EffekseerRendererLLGI.RenderState.h"
#include "EffekseerRendererLLGI.RendererImplemented.h"
#include "EffekseerRendererLLGI.IndexBuffer.h"
#include "EffekseerRendererLLGI.ModelRenderer.h"
#include "EffekseerRendererLLGI.Shader.h"
#include "EffekseerRendererLLGI.VertexBuffer.h"
#include "GraphicsDevice.h"
namespace EffekseerRendererLLGI
{
const int LLGI_InstanceCount = 40;
ModelRenderer::ModelRenderer(RendererImplemented* renderer,
Shader* shader_ad_lit,
Shader* shader_ad_unlit,
Shader* shader_ad_distortion,
Shader* shader_lighting_texture_normal,
Shader* shader_texture,
Shader* shader_distortion_texture)
: m_renderer(renderer)
, shader_ad_lit_(shader_ad_lit)
, shader_ad_unlit_(shader_ad_unlit)
, shader_ad_distortion_(shader_ad_distortion)
, m_shader_lighting_texture_normal(shader_lighting_texture_normal)
, m_shader_texture(shader_texture)
, m_shader_distortion_texture(shader_distortion_texture)
{
// Ad
{
std::array<Shader*, 2> shaders;
shaders[0] = shader_ad_lit_;
shaders[1] = shader_ad_unlit_;
for (size_t i = 0; i < shaders.size(); i++)
{
shaders[i]->SetVertexConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererAdvancedVertexConstantBuffer<LLGI_InstanceCount>));
shaders[i]->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::PixelConstantBuffer));
}
shader_ad_distortion_->SetVertexConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererAdvancedVertexConstantBuffer<LLGI_InstanceCount>));
shader_ad_distortion_->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::PixelConstantBufferDistortion));
}
{
std::array<Shader*, 2> shaders;
shaders[0] = m_shader_lighting_texture_normal;
shaders[1] = m_shader_texture;
for (size_t i = 0; i < shaders.size(); i++)
{
shaders[i]->SetVertexConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererVertexConstantBuffer<LLGI_InstanceCount>));
shaders[i]->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::PixelConstantBuffer));
}
m_shader_distortion_texture->SetVertexConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererVertexConstantBuffer<LLGI_InstanceCount>));
m_shader_distortion_texture->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::PixelConstantBufferDistortion));
}
VertexType = EffekseerRenderer::ModelRendererVertexType::Instancing;
graphicsDevice_ = m_renderer->GetGraphicsDeviceInternal().Get();
LLGI::SafeAddRef(graphicsDevice_);
}
ModelRenderer::~ModelRenderer()
{
ES_SAFE_DELETE(m_shader_lighting_texture_normal);
ES_SAFE_DELETE(m_shader_texture);
ES_SAFE_DELETE(m_shader_distortion_texture);
ES_SAFE_DELETE(shader_ad_unlit_);
ES_SAFE_DELETE(shader_ad_lit_);
ES_SAFE_DELETE(shader_ad_distortion_);
LLGI::SafeRelease(graphicsDevice_);
}
ModelRendererRef ModelRenderer::Create(RendererImplemented* renderer, FixedShader* fixedShader)
{
assert(renderer != nullptr);
assert(renderer->GetGraphics() != nullptr);
std::vector<VertexLayout> layouts;
layouts.push_back(VertexLayout{LLGI::VertexLayoutFormat::R32G32B32_FLOAT, "TEXCOORD", 0});
layouts.push_back(VertexLayout{LLGI::VertexLayoutFormat::R32G32B32_FLOAT, "TEXCOORD", 1});
layouts.push_back(VertexLayout{LLGI::VertexLayoutFormat::R32G32B32_FLOAT, "TEXCOORD", 2});
layouts.push_back(VertexLayout{LLGI::VertexLayoutFormat::R32G32B32_FLOAT, "TEXCOORD", 3});
layouts.push_back(VertexLayout{LLGI::VertexLayoutFormat::R32G32_FLOAT, "TEXCOORD", 4});
layouts.push_back(VertexLayout{LLGI::VertexLayoutFormat::R8G8B8A8_UNORM, "TEXCOORD", 5});
Shader* shader_lighting_texture_normal = Shader::Create(renderer->GetGraphicsDeviceInternal().Get(),
fixedShader->ModelLit_VS.data(),
(int32_t)fixedShader->ModelLit_VS.size(),
fixedShader->ModelLit_PS.data(),
(int32_t)fixedShader->ModelLit_PS.size(),
"ModelRendererLightingTextureNormal",
layouts,
true);
Shader* shader_texture = Shader::Create(renderer->GetGraphicsDeviceInternal().Get(),
fixedShader->ModelUnlit_VS.data(),
(int32_t)fixedShader->ModelUnlit_VS.size(),
fixedShader->ModelUnlit_PS.data(),
(int32_t)fixedShader->ModelUnlit_PS.size(),
"ModelRendererTexture",
layouts,
true);
auto shader_distortion_texture = Shader::Create(renderer->GetGraphicsDeviceInternal().Get(),
fixedShader->ModelDistortion_VS.data(),
(int32_t)fixedShader->ModelDistortion_VS.size(),
fixedShader->ModelDistortion_PS.data(),
(int32_t)fixedShader->ModelDistortion_PS.size(),
"ModelRendererDistortionTexture",
layouts,
true);
Shader* shader_ad_lit = Shader::Create(renderer->GetGraphicsDeviceInternal().Get(),
fixedShader->AdvancedModelLit_VS.data(),
(int32_t)fixedShader->AdvancedModelLit_VS.size(),
fixedShader->AdvancedModelLit_PS.data(),
(int32_t)fixedShader->AdvancedModelLit_PS.size(),
"ModelRendererLightingTextureNormal",
layouts,
true);
Shader* shader_ad_unlit = Shader::Create(renderer->GetGraphicsDeviceInternal().Get(),
fixedShader->AdvancedModelUnlit_VS.data(),
(int32_t)fixedShader->AdvancedModelUnlit_VS.size(),
fixedShader->AdvancedModelUnlit_PS.data(),
(int32_t)fixedShader->AdvancedModelUnlit_PS.size(),
"ModelRendererTexture",
layouts,
true);
auto shader_ad_distortion = Shader::Create(renderer->GetGraphicsDeviceInternal().Get(),
fixedShader->AdvancedModelDistortion_VS.data(),
(int32_t)fixedShader->AdvancedModelDistortion_VS.size(),
fixedShader->AdvancedModelDistortion_PS.data(),
(int32_t)fixedShader->AdvancedModelDistortion_PS.size(),
"ModelRendererDistortionTexture",
layouts,
true);
if (shader_lighting_texture_normal == nullptr || shader_texture == nullptr || shader_distortion_texture == nullptr ||
shader_ad_lit == nullptr || shader_ad_unlit == nullptr || shader_ad_distortion == nullptr)
{
ES_SAFE_DELETE(shader_lighting_texture_normal);
ES_SAFE_DELETE(shader_texture);
ES_SAFE_DELETE(shader_distortion_texture);
ES_SAFE_DELETE(shader_ad_unlit);
ES_SAFE_DELETE(shader_ad_lit);
ES_SAFE_DELETE(shader_ad_distortion);
}
return ModelRendererRef(new ModelRenderer(renderer, shader_ad_lit, shader_ad_unlit, shader_ad_distortion, shader_lighting_texture_normal, shader_texture, shader_distortion_texture));
}
void ModelRenderer::BeginRendering(const efkModelNodeParam& parameter, int32_t count, void* userData)
{
BeginRendering_(m_renderer, parameter, count, userData);
}
void ModelRenderer::Rendering(const efkModelNodeParam& parameter, const InstanceParameter& instanceParameter, void* userData)
{
Rendering_<RendererImplemented>(m_renderer, parameter, instanceParameter, userData);
}
void ModelRenderer::EndRendering(const efkModelNodeParam& parameter, void* userData)
{
if (parameter.ModelIndex < 0)
{
return;
}
Effekseer::ModelRef model = nullptr;
if (parameter.IsProcedualMode)
{
model = parameter.EffectPointer->GetProcedualModel(parameter.ModelIndex);
}
else
{
model = parameter.EffectPointer->GetModel(parameter.ModelIndex);
}
if (model == nullptr)
{
return;
}
model->StoreBufferToGPU(graphicsDevice_);
if (!model->GetIsBufferStoredOnGPU())
{
return;
}
if (m_renderer->GetRenderMode() == Effekseer::RenderMode::Wireframe)
{
model->GenerateWireIndexBuffer(graphicsDevice_);
if (!model->GetIsWireIndexBufferGenerated())
{
return;
}
}
EndRendering_<RendererImplemented, Shader, Effekseer::Model, true, LLGI_InstanceCount>(
m_renderer, shader_ad_lit_, shader_ad_unlit_, shader_ad_distortion_, m_shader_lighting_texture_normal, m_shader_texture, m_shader_distortion_texture, parameter);
}
} // namespace EffekseerRendererLLGI
| 37.138889 | 183 | 0.746697 | [
"vector",
"model"
] |
b83b9880628e3d10e6ea4e3a712ae6ae52875520 | 8,663 | cc | C++ | trw_sql.cc | prakruti1090/PortScan_Sql | a69c376dccecb3d9276069cfa020432eef2f597e | [
"Apache-2.0"
] | null | null | null | trw_sql.cc | prakruti1090/PortScan_Sql | a69c376dccecb3d9276069cfa020432eef2f597e | [
"Apache-2.0"
] | null | null | null | trw_sql.cc | prakruti1090/PortScan_Sql | a69c376dccecb3d9276069cfa020432eef2f597e | [
"Apache-2.0"
] | null | null | null | #include "mysql.h"
#include <cstdio>
#include <sstream>
#include <fstream>
#include <cstring>
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main() {
MYSQL *conn;
MYSQL_RES *res,*res_tot_flows,*res_sip,*res_dip,*res_flags,*res_packets,*res_d,*res_scanner;
MYSQL_RES *res_hit1,*res_hit2,*mysqlResult,*res_miss,*res_ch1,*res_ch2,*res_sip2,*res_ht1,*res_ht2,*res_ht22,*re
s_ht3,*res_ht33;
MYSQL_ROW row,mysqlRow,row_tot_flows,row_sip,row_dip,row_flags,row_packets,row_d,row_scanner;
MYSQL_ROW row_hit1,row_hit2,row_miss,row_ch1,row_ch2,row_sip2,row_ht1,row_ht2,row_ht22,row_ht3,row_ht33;
unsigned int num_fields;
MYSQL_RES *res_syn,*res_f,*res_nom,*res_noh;
MYSQL_ROW row_syn,row_f,row_nom,row_noh;
int curr_id=1;
float hit_likelihood,miss_likelihood,likelihood;
int noh,nom,miss;
std::string sip,hit,misses,flags,packets,dip,sip1,dip1,mq0;
int tot_flows,ch1,ch2;
//code for connecting to local mysql database
const char *server = "localhost";
const char *user = "root";
const char *password = "letmein"; /* set me first */
//unsigned int port=3307;
const char *database = "TRW_PLAIN";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, 0, NULL, 0))
{
fprintf(stderr, "%s\n", mysql_error(conn));
}
// code for connecting to cryptDB's server and encrypted database
const char *server = "127.0.0.1";
const char *user = "root";
const char *password = "letmein";
unsigned int port=3307;
//change the database name
const char *database = "TRW_crypt";
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,user, password, database, port, NULL, CLIENT_MULTI_STATEMENTS))
{
fprintf(stderr, "%s\n", mysql_error(conn));
}
mysql_query(conn,"drop table if exists ipset;");
mysql_query(conn,"create table ipset(ip varchar(25));");
mysql_query(conn,"insert into ipset values('131.243.18.66');");
mysql_query(conn,"insert into ipset values('131.243.68.51');");
mysql_query(conn,"insert into ipset values('128.3.99.47');");
mysql_query(conn,"insert into ipset values('128.3.96.153');");
mysql_query(conn,"insert into ipset values('128.3.209.164');");
mysql_query(conn,"insert into ipset values('213.147.167.100');");
/*if (mysql_query(conn, "select count(*) from scan;"))
{
fprintf(stderr, "%s\n", mysql_error(conn));
}
res_tot_flows=mysql_store_result(conn);
row_tot_flows = mysql_fetch_row(res_tot_flows);
istringstream tot_flows_buff(row_tot_flows[0]);
tot_flows_buff >> tot_flows;
cout<<tot_flows<<endl;
*/
mysql_query(conn,"drop table if exists scan_sip;");
//std::string status="NULL";
if(mysql_query(conn, "create table scan_sip(s_id integer auto_increment primary key,sip varchar(25),dip varchar(
25),flags varchar(10),packets integer,hit integer,misses integer);"))
{
fprintf(stderr, "%s\n", mysql_error(conn));
}
std::string new_conn="insert into scan_sip(sip,dip,flags,packets) select sip,dip,flags,packets from scan group b
y sip,dip;";
//cout<<new_conn<<endl;
mysql_query(conn,new_conn.c_str());
mysqlResult = mysql_store_result(conn); // Get the Result Set
//mysql_query(conn, "alter table scan_sip add(hit integer);");
//mysql_query(conn, "alter table scan_sip add(misses integer);");
//mysql_query(conn, "alter table scan_sip add(status varchar(10));");
//mysql_query(conn, "insert into scan_sip(hit,misses) values(0,0);");
//mysql_query(conn, "insert into scan_sip(status) values('u|');");
//mysql_query(conn, "update scan_sip set hit=0;");
//mysql_query(conn, "update scan_sip set misses=0;");
//mysql_query(conn, "update scan_sip set status='NULL';");
/*if(mysql_query(conn, "select * from scan_sip into outfile '/tmp/sb1.txt' FIELDS TERMINATED BY '|' LINES TERMIN
ATED BY '\n'")) {
fprintf(stderr, "%s\n", mysql_error(conn));
}*/
if (mysql_query(conn, "select count(*) from scan_sip;"))
{
fprintf(stderr, "%s\n", mysql_error(conn));
}
res_tot_flows=mysql_store_result(conn);
row_tot_flows = mysql_fetch_row(res_tot_flows);
istringstream tot_flows_buff(row_tot_flows[0]);
tot_flows_buff >> tot_flows;
cout<<tot_flows<<endl;
while(curr_id<tot_flows)
{
stringstream ss;
ss << curr_id;
string id_query = ss.str();
cout<<ss.str()<<endl;
/*std::string h1="select count(*) from scan_sip where s_id=ss.str()";
//std::string h2="and flags='s' + " ";
std::string hit1_query= h1 + " " + "and dip in('131.243.18.66','131.243.68.51','128.3.99.47','128.3.96.153',
'128.3.209.164','213.147.167.100');";
*/
/*std::string ht_query="select count(*) from scan_sip s1 inner join ipset i1 where s1.s_id=" +ss.str();
std::string hit1_query=ht_query + " " + "and s1.flags='S' and s1.dip=i1.ip;";
//cout<<hit1_query<<endl;
*/
//std::string h1="select count(*) from scan_sip where s_id=" + ss.str();
std::string h1="select count(*) from scan_sip s1 inner join ipset i1 where s1.s_id=" +ss.str();
std::string hit1_query= h1 + " " + "and s1.flags='S' and s1.dip=i1.ip;";
cout<<hit1_query<<endl;
mysql_query(conn, hit1_query.c_str());
mysql_query(conn, hit1_query.c_str());
res_hit1=mysql_store_result(conn);
row_hit1=mysql_fetch_row(res_hit1);
istringstream buffer1(row_hit1[0]);
int hit1;
buffer1 >> hit1;
cout<<"hit1:"<<hit1<<endl;
std::string hit2_query=h1 + " " + "and s1.flags!='S' and s1.dip!=i1.ip;";
mysql_query(conn, hit2_query.c_str());
//mysql_query(conn, hit1_query.c_str());
cout<<hit2_query<<endl;
res_hit2=mysql_store_result(conn);
row_hit2=mysql_fetch_row(res_hit2);
istringstream buffer2(row_hit2[0]);
int hit2;
buffer2 >> hit2;
std::cout<<"hit2:"<<hit2<<std::endl;
int h = hit1 + hit2;
stringstream hh;
hh << h;
hit = hh.str();
if(h>0)
{
string uph = "update scan_sip set hit=1;";
mysql_query(conn,uph.c_str());
cout<<uph<<endl;
}
if(h==0)
{
string miss_query= h1 + " " + "and s1.flags='S' and s1.dip!=i1.ip;";
cout<<miss_query<<endl;
mysql_query(conn, miss_query.c_str());
res_miss=mysql_store_result(conn);
cout<<miss_query<<endl;
row_miss=mysql_fetch_row(res_miss);
istringstream miss_buff(row_miss[0]);
miss_buff >> miss;
cout<<"miss:"<<miss<<endl;
stringstream ms;
ms << miss;
misses = ms.str();
string up2;
up2="update scan_sip set misses=1;";
cout<<up2<<endl;
mysql_query(conn,up2.c_str());
}
curr_id = curr_id+1;
}
mysql_query(conn,"drop table if exists sc;");
mysql_query(conn,"create table sc(source_ip varchar(25),status varchar(10));");
mysql_query(conn,"select distinct sip from scan_sip where hit>0 or misses>0;");
res_d=mysql_store_result(conn);
string d;
string synq="select count(*) from scan_sip where sip=";
cout<<"distinct sips:"<<endl;
while ((row_d = mysql_fetch_row(res_d))!=NULL)
{
d=string(row_d[0]);
cout<<d<<endl;
string sq=synq + "'" +d + "'" + " " + "and flags='S';";
mysql_query(conn,sq.c_str());
res_syn=mysql_store_result(conn);
row_syn = mysql_fetch_row(res_syn);
istringstream syn_buff(row_syn[0]);
int syns;
syn_buff >> syns;
cout<<"syns:"<<syns<<endl;
string s_dq="'" +d + "'" + ";";
string sp_fq="select count(*) from scan_sip where sip=" + s_dq;
mysql_query(conn,sp_fq.c_str());
res_f=mysql_store_result(conn);
row_f=mysql_fetch_row(res_f);
istringstream f_buff(row_syn[0]);
int f;
f_buff >> f;
cout<<"sip_flows:"<<f<<endl;
string no_hits="select sum(hit) from scan_sip where sip=" + s_dq;
mysql_query(conn,no_hits.c_str());
res_noh=mysql_store_result(conn);
row_noh=mysql_fetch_row(res_noh);
istringstream h_buff(row_noh[0]);
noh;
h_buff >> noh;
cout<<"noh:"<<noh<<endl;
string no_misses="select sum(misses) from scan_sip where sip=" + s_dq;
mysql_query(conn,no_misses.c_str());
res_nom=mysql_store_result(conn);
row_nom=mysql_fetch_row(res_nom);
istringstream m_buff(row_nom[0]);
nom;
m_buff >> nom;
cout<<"nom:"<<nom<<endl;
int k=0;
if(noh > 0)
{
hit_likelihood=1;
while(k < noh)
{
hit_likelihood = hit_likelihood * 0.25;
k++;
}
}
cout<<"hit_likelihood:"<<hit_likelihood<<endl;
int j=0;
if(nom > 0)
{
miss_likelihood=1;
while(j < nom)
{
miss_likelihood = miss_likelihood * 4;
j++;
}
}
cout<<"miss_likelihood:"<<miss_likelihood<<endl;
if(noh == 0)
{
likelihood = miss_likelihood;
}
if(nom == 0)
{
likelihood = hit_likelihood;
}
if(noh > 0 && nom > 0)
{
likelihood = hit_likelihood * miss_likelihood;
}
cout<<"likelihood:"<<likelihood<<endl;
if(likelihood > 99 && syns==f)
{
string sc_iq="insert into sc values(";
string sc_q=sc_iq + "'" +d + "'" + "," + "'scanner');";
mysql_query(conn,sc_q.c_str());
}
}
mysql_query(conn,"select source_ip from sc;");
res_scanner=mysql_store_result(conn);
string scanner;
cout<<"LIST OF SCANNER IP's:"<<endl;
while ((row_scanner = mysql_fetch_row(res_scanner))!=NULL)
{
scanner=string(row_scanner[0]);
cout<<scanner<<endl;
}
mysql_close(conn);
return 0;
}
| 31.732601 | 112 | 0.712802 | [
"vector"
] |
b83de6076448a01c5636a265c0e82434ea9fe4d6 | 13,411 | cpp | C++ | main.cpp | sasawat/crazydiskinfo | 212bc613d8878f0c76021bf0135a15e62da73682 | [
"MIT"
] | null | null | null | main.cpp | sasawat/crazydiskinfo | 212bc613d8878f0c76021bf0135a15e62da73682 | [
"MIT"
] | null | null | null | main.cpp | sasawat/crazydiskinfo | 212bc613d8878f0c76021bf0135a15e62da73682 | [
"MIT"
] | 1 | 2022-03-27T15:09:09.000Z | 2022-03-27T15:09:09.000Z | #include <iostream>
#include <array>
#include <vector>
#include <algorithm>
#include <functional>
#include <locale.h>
#include <ncurses.h>
#include <atasmart.h>
#include <sys/signal.h>
#include <dirent.h>
constexpr int const STATUS_WIDTH = 80;
constexpr int const DEVICE_BAR_HEIGHT = 4;
constexpr int const VERSION_HEIGHT = 1;
int width;
int height;
enum class Health
{
Good,
Caution,
Bad
};
class Attribute
{
public:
uint8_t id;
std::string name;
uint8_t current;
uint8_t worst;
uint8_t threshold;
uint64_t raw;
};
class SMART
{
public:
std::string deviceName;
std::string model;
std::string firmware;
std::string serial;
//TODO
//use std::optional
std::pair<bool, uint64_t> size;
std::pair<bool, uint64_t> powerOnCount;
std::pair<bool, uint64_t> powerOnHour;
std::pair<bool, double> temperature;
std::vector<Attribute> attribute;
SMART(std::string deviceName)
:
deviceName(deviceName)
{
SkDisk * skdisk;
sk_disk_open(deviceName.c_str(), &skdisk);
sk_disk_smart_read_data(skdisk);
const SkIdentifyParsedData * data;
sk_disk_identify_parse(skdisk, &data);
model = data->model;
firmware = data->firmware;
serial = data->serial;
uint64_t value;
if (!sk_disk_get_size(skdisk, &value))
{
std::get<0>(size) = true;
std::get<1>(size) = value;
}
else
{
std::get<0>(size) = false;
}
if (!sk_disk_smart_get_power_cycle(skdisk, &value))
{
std::get<0>(powerOnCount) = true;
std::get<1>(powerOnCount) = value;
}
else
{
std::get<0>(powerOnCount) = false;
}
if (!sk_disk_smart_get_power_on(skdisk, &value))
{
std::get<0>(powerOnHour) = true;
std::get<1>(powerOnHour) = value / (1000llu * 60llu * 60llu);
}
else
{
std::get<0>(powerOnHour) = false;
}
if (!sk_disk_smart_get_temperature(skdisk, &value))
{
std::get<0>(temperature) = true;
std::get<1>(temperature) = (double)(value - 273150llu) / 1000.0;
}
else
{
std::get<0>(temperature) = false;
}
sk_disk_smart_parse_attributes(skdisk, [](SkDisk * skdisk, SkSmartAttributeParsedData const * data, void * userdata)
{
auto attribute = reinterpret_cast<std::vector<Attribute> *>(userdata);
Attribute attr = {};
attr.id = data->id;
attr.name = data->name;
attr.current = data->current_value;
attr.worst = data->worst_value;
attr.threshold = data->threshold;
for (int i = 0; i < 6; ++i)
{
attr.raw += data->raw[i] << (8 * i);
}
attribute->push_back(attr);
}, &attribute);
sk_disk_free(skdisk);
}
};
Health temperatureToHealth(double temperature)
{
if (temperature < 50)
{
return Health::Good;
}
else if (temperature < 55)
{
return Health::Caution;
}
else
{
return Health::Bad;
}
}
Health attributeToHealth(Attribute const & attribute)
{
if ((attribute.threshold != 0) && (attribute.current < attribute.threshold))
{
return Health::Bad;
}
else if (((attribute.id == 0x05) || (attribute.id == 0xC5) || (attribute.id == 0xC6)) && (attribute.raw != 0))
{
return Health::Caution;
}
else
{
return Health::Good;
}
}
Health smartToHealth(SMART const & smart)
{
return attributeToHealth(*std::max_element(smart.attribute.cbegin(), smart.attribute.cend(), [](Attribute const & lhs, Attribute const & rhs)
{
return static_cast<int>(attributeToHealth(lhs)) < static_cast<int>(attributeToHealth(rhs));
}));
}
std::string healthToString(Health health)
{
switch (health)
{
case Health::Good:
return "Good";
case Health::Caution:
return "Caution";
case Health::Bad:
return "Bad";
default:
return "Unknown";
}
}
void drawVersion(WINDOW * window)
{
wresize(window, VERSION_HEIGHT, width);
wattrset(window, COLOR_PAIR(4));
mvwhline(window, 0, 0, '-', width);
wattroff(window, COLOR_PAIR(4));
wattrset(window, COLOR_PAIR(8));
mvwprintw(window, 0, (width - sizeof(" CrazyDiskInfo-1.0.2 ")) / 2, " CrazyDiskInfo-1.0.2 ");
wattroff(window, COLOR_PAIR(8));
wnoutrefresh(window);
}
void drawDeviceBar(WINDOW * window, std::vector<SMART> const & smartList, int select)
{
int x = 0;
for (int i = 0; i < static_cast<int>(smartList.size()); ++i)
{
wattrset(window, COLOR_PAIR(1 + static_cast<int>(smartToHealth(smartList[i]))));
mvwprintw(window, 0, x, "%-7s", healthToString(smartToHealth(smartList[i])).c_str());
wattroff(window, COLOR_PAIR(1 + static_cast<int>(smartToHealth(smartList[i]))));
if (std::get<0>(smartList[i].temperature))
{
wattrset(window, COLOR_PAIR(1 + static_cast<int>(temperatureToHealth(std::get<1>(smartList[i].temperature)))));
mvwprintw(window, 1, x, "%.1f ", smartList[i].temperature);
waddch(window, ACS_DEGREE);
waddstr(window, "C");
wattroff(window, COLOR_PAIR(1 + static_cast<int>(temperatureToHealth(std::get<1>(smartList[i].temperature)))));
}
else
{
mvwprintw(window, 1, x, "-- ");
waddch(window, ACS_DEGREE);
waddstr(window, "C");
}
if (i == select)
{
wattrset(window, COLOR_PAIR(4) | A_BOLD);
mvwprintw(window, 2, x, smartList[i].deviceName.c_str());
wattroff(window, COLOR_PAIR(4) | A_BOLD);
wattrset(window, COLOR_PAIR(4));
mvwhline(window, 3, x, '-', smartList[i].deviceName.length());
wattroff(window, COLOR_PAIR(4));
}
else
{
mvwprintw(window, 2, x, smartList[i].deviceName.c_str());
mvwhline(window, 3, x, ' ', smartList[i].deviceName.length());
}
x += smartList[i].deviceName.length() + 1;
}
pnoutrefresh(window, 0, 0, 1, 0, DEVICE_BAR_HEIGHT, width - 1);
}
void drawStatus(WINDOW * window, SMART const & smart)
{
wresize(window, 10 + smart.attribute.size(), STATUS_WIDTH);
wborder(window, '|', '|', '-', '-', '+', '+', '+', '+');
if (std::get<0>(smart.size))
{
std::vector<std::string> unit = {{"Byte", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}};
int u = 0;
double size = std::get<1>(smart.size);
while (true)
{
double old = size;
size /= 1024;
if (size < 1.0)
{
size = old;
break;
}
++u;
}
char s[STATUS_WIDTH];
int len = snprintf(s, STATUS_WIDTH, " %s [%.1f %s] ", smart.model.c_str(), size, unit[u].c_str());
wattrset(window, COLOR_PAIR(4) | A_BOLD);
mvwprintw(window, 0, (STATUS_WIDTH - len) / 2, "%s", s);
wattroff(window, COLOR_PAIR(4) | A_BOLD);
}
else
{
char s[STATUS_WIDTH];
int len = snprintf(s, STATUS_WIDTH, " %s [--] ", smart.model.c_str());
wattrset(window, COLOR_PAIR(4) | A_BOLD);
mvwprintw(window, 0, (STATUS_WIDTH - len) / 2, "%s", s);
wattroff(window, COLOR_PAIR(4) | A_BOLD);
}
wattrset(window, COLOR_PAIR(4));
mvwprintw(window, 2, (int)(STATUS_WIDTH * (1.0 / 5)), "Firmware:");
wattroff(window, COLOR_PAIR(4));
wattrset(window, COLOR_PAIR(4) | A_BOLD);
wprintw(window, " %s", smart.firmware.c_str());
wattroff(window, COLOR_PAIR(4) | A_BOLD);
wattrset(window, COLOR_PAIR(4));
mvwprintw(window, 3, (int)(STATUS_WIDTH * (1.0 / 5)), "Serial: ");
wattroff(window, COLOR_PAIR(4));
wattrset(window, COLOR_PAIR(4) | A_BOLD);
wprintw(window, " %s", smart.serial.c_str());
wattroff(window, COLOR_PAIR(4) | A_BOLD);
wattrset(window, COLOR_PAIR(4));
mvwprintw(window, 1, 1, "Status");
wattroff(window, COLOR_PAIR(4));
wattrset(window, COLOR_PAIR(1 + static_cast<int>(smartToHealth(smart))));
mvwprintw(window, 2, 2, "+--------+");
mvwprintw(window, 3, 2, "| |");
mvwprintw(window, 4, 2, "+--------+");
mvwprintw(window, 3, 2 + ((sizeof("| |") - healthToString(smartToHealth(smart)).length()) / 2), "%s", healthToString(smartToHealth(smart)).c_str());
wattroff(window, COLOR_PAIR(1 + static_cast<int>(smartToHealth(smart))));
if (std::get<0>(smart.temperature))
{
wattrset(window, COLOR_PAIR(4));
mvwprintw(window, 5, 1, "Temperature");
wattroff(window, COLOR_PAIR(4));
wattrset(window, COLOR_PAIR(1 + static_cast<int>(temperatureToHealth(std::get<1>(smart.temperature)))));
mvwprintw(window, 6, 2, " %0.1f ", std::get<1>(smart.temperature));
waddch(window, ACS_DEGREE);
waddstr(window, "C ");
wattroff(window, COLOR_PAIR(1 + static_cast<int>(temperatureToHealth(std::get<1>(smart.temperature)))));
}
else
{
mvwprintw(window, 5, 1, "Temperature");
mvwprintw(window, 6, 2, " -- ");
waddch(window, ACS_DEGREE);
waddstr(window, "C ");
}
if (std::get<0>(smart.powerOnCount))
{
wattrset(window, COLOR_PAIR(4));
mvwprintw(window, 2, (int)(STATUS_WIDTH * (3.0 / 5)), "Power On Count:");
wattroff(window, COLOR_PAIR(4));
wattrset(window, COLOR_PAIR(4) | A_BOLD);
wprintw(window, " %llu ", std::get<1>(smart.powerOnCount));
wattroff(window, COLOR_PAIR(4) | A_BOLD);
wattrset(window, COLOR_PAIR(4));
wprintw(window, "count");
}
else
{
mvwprintw(window, 2, (int)(STATUS_WIDTH * (3.0 / 5)), "Power On Count:");
wprintw(window, " -- count");
}
if (std::get<0>(smart.powerOnHour))
{
wattrset(window, COLOR_PAIR(4));
mvwprintw(window, 3, (int)(STATUS_WIDTH * (3.0 / 5)), "Power On Hours:");
wattroff(window, COLOR_PAIR(4));
wattrset(window, COLOR_PAIR(4) | A_BOLD);
wprintw(window, " %llu ", std::get<1>(smart.powerOnHour));
wattroff(window, COLOR_PAIR(4) | A_BOLD);
wattrset(window, COLOR_PAIR(4));
wprintw(window, "hours");
wattroff(window, COLOR_PAIR(4));
}
else
{
mvwprintw(window, 3, (int)(STATUS_WIDTH * (3.0 / 5)), "Power On Hours:");
wprintw(window, " -- hours");
}
wattrset(window, COLOR_PAIR(7));
mvwprintw(window, 8, 1, " Status ID AttributeName Current Worst Threshold Raw Values ");
wattroff(window, COLOR_PAIR(7));
for (int i = 0; i < static_cast<int>(smart.attribute.size()); ++i)
{
wattrset(window, COLOR_PAIR(4 + static_cast<int>(attributeToHealth(smart.attribute[i]))));
#ifndef RAWDEC
mvwprintw(window, 9 + i, 1, " %-7s %02X %-28s %7d %5d %9d %012X ",
#else
mvwprintw(window, 9 + i, 1, " %-7s %02X %-28s %7d %5d %9d %012d ",
#endif//RAWDEC
healthToString(attributeToHealth(smart.attribute[i])).c_str(),
smart.attribute[i].id,
smart.attribute[i].name.c_str(),
smart.attribute[i].current,
smart.attribute[i].worst,
smart.attribute[i].threshold,
smart.attribute[i].raw);
wattroff(window, COLOR_PAIR(4 + static_cast<int>(attributeToHealth(smart.attribute[i]))));
}
pnoutrefresh(window, 0, 0,
5, std::max(0, (width - STATUS_WIDTH) / 2),
std::min(height - 1, 5 + 10 + static_cast<int>(smart.attribute.size())), std::min(width - 1, std::max(0, (width - STATUS_WIDTH) / 2) + STATUS_WIDTH));
}
std::function<void(void)> update;
void actionWINCH(int)
{
clear();
endwin();
refresh();
update();
}
int main()
{
setlocale(LC_ALL, "");
initscr();
cbreak();
noecho();
curs_set(0);
getmaxyx(stdscr, height, width);
start_color();
init_pair(1, COLOR_BLACK, COLOR_CYAN);
init_pair(2, COLOR_BLACK, COLOR_YELLOW);
init_pair(3, COLOR_WHITE, COLOR_RED);
init_pair(4, COLOR_CYAN, COLOR_BLACK);
init_pair(5, COLOR_BLACK, COLOR_YELLOW);
init_pair(6, COLOR_WHITE, COLOR_RED);
init_pair(7, COLOR_BLACK, COLOR_GREEN);
init_pair(8, COLOR_YELLOW, COLOR_BLACK);
int select = 0;
std::vector<SMART> smartList;
auto dir = opendir("/sys/block");
while (auto e = readdir(dir))
{
if (std::string(".") != std::string(e->d_name) &&
std::string("..") != std::string(e->d_name) &&
std::string("ram") != std::string(e->d_name).substr(0,3) &&
std::string("loop") != std::string(e->d_name).substr(0,4))
{
SkDisk * skdisk;
SkBool b;
int f = sk_disk_open((std::string("/dev/") + std::string(e->d_name)).c_str(), &skdisk);
if (f < 0)
{
continue;
}
int smart_ret = sk_disk_smart_is_available(skdisk, &b);
sk_disk_free(skdisk);
if (smart_ret < 0)
{
continue;
}
if (b)
{
smartList.push_back(SMART(std::string("/dev/") + std::string(e->d_name)));
}
}
}
std::sort(smartList.begin(), smartList.end(), [](SMART const & lhs, SMART const & rhs){return lhs.deviceName < rhs.deviceName;});
if (smartList.size() == 0)
{
endwin();
std::cerr << "No S.M.A.R.T readable devices." << std::endl;
std::cerr << "If you are non-root user, please use sudo or become root." << std::endl;
return 1;
}
WINDOW * windowVersion;
windowVersion = newwin(1, width, 0, 0);
WINDOW * windowDeviceBar;
{
int x = 0;
for (auto && e : smartList)
{
x += e.deviceName.length() + 1;
}
windowDeviceBar = newpad(DEVICE_BAR_HEIGHT, x);
keypad(windowDeviceBar, true);
}
WINDOW * windowDeviceStatus;
windowDeviceStatus = newpad(10 + smartList[select].attribute.size(), STATUS_WIDTH);
update = [&]()
{
getmaxyx(stdscr, height, width);
wclear(windowVersion);
drawVersion(windowVersion);
wclear(windowDeviceBar);
drawDeviceBar(windowDeviceBar, smartList, select);
wclear(windowDeviceStatus);
drawStatus(windowDeviceStatus, smartList[select]);
doupdate();
};
update();
{
struct sigaction s = {{actionWINCH}};
sigaction(SIGWINCH, &s, nullptr);
}
while(true)
{
switch (wgetch(windowDeviceBar))
{
case KEY_HOME:
select = 0;
clear();
refresh();
update();
break;
case KEY_END:
select = static_cast<int>(smartList.size()) - 1;
clear();
refresh();
update();
break;
case KEY_LEFT:
case 'h':
select = std::max(select - 1, 0);
clear();
refresh();
update();
break;
case KEY_RIGHT:
case 'l':
select = std::min(select + 1, static_cast<int>(smartList.size()) - 1);
clear();
refresh();
update();
break;
case 'q':
endwin();
return 0;
default:
break;
}
}
}
| 25.447818 | 156 | 0.646037 | [
"vector",
"model"
] |
b83e4ee01c46e3703ad01868a8025196791c4f93 | 31,692 | hpp | C++ | include/do_cycles.hpp | daboehme/Comb | e06e54d351f7b31177db89f37b4326c8e96656bd | [
"MIT"
] | null | null | null | include/do_cycles.hpp | daboehme/Comb | e06e54d351f7b31177db89f37b4326c8e96656bd | [
"MIT"
] | null | null | null | include/do_cycles.hpp | daboehme/Comb | e06e54d351f7b31177db89f37b4326c8e96656bd | [
"MIT"
] | null | null | null | //////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2018-2020, Lawrence Livermore National Security, LLC.
//
// Produced at the Lawrence Livermore National Laboratory
//
// LLNL-CODE-758885
//
// All rights reserved.
//
// This file is part of Comb.
//
// For details, see https://github.com/LLNL/Comb
// Please also see the LICENSE file for MIT license.
//////////////////////////////////////////////////////////////////////////////
#ifndef _DO_CYCLES_HPP
#define _DO_CYCLES_HPP
#include <type_traits>
#include "comb.hpp"
#include "CommFactory.hpp"
namespace COMB {
template < typename pol_comm, typename pol_mesh, typename pol_many, typename pol_few >
bool should_do_cycles(CommContext<pol_comm>& con_comm,
ExecContext<pol_mesh>& con_mesh, AllocatorInfo& aloc_mesh,
ExecContext<pol_many>& con_many, AllocatorInfo& aloc_many,
ExecContext<pol_few>& con_few, AllocatorInfo& aloc_few)
{
return aloc_mesh.available() // && aloc_many.available() && aloc_few.available()
&& aloc_many.accessible(con_comm) && aloc_few.accessible(con_comm)
&& aloc_mesh.accessible(con_mesh)
&& aloc_mesh.accessible(con_many) && aloc_many.accessible(con_many)
&& aloc_mesh.accessible(con_few) && aloc_few.accessible(con_few) ;
}
template < typename pol_comm, typename pol_mesh, typename pol_many, typename pol_few >
void do_cycles(CommContext<pol_comm>& con_comm_in,
CommInfo& comm_info, MeshInfo& info,
IdxT num_vars, IdxT ncycles,
ExecContext<pol_mesh>& con_mesh, COMB::Allocator& aloc_mesh,
ExecContext<pol_many>& con_many, COMB::Allocator& aloc_many,
ExecContext<pol_few>& con_few, COMB::Allocator& aloc_few,
Timer& tm, Timer& tm_total)
{
CPUContext tm_con;
tm_total.clear();
tm.clear();
char test_name[1024] = ""; snprintf(test_name, 1024, "Comm %s Mesh %s %s Buffers %s %s %s %s",
pol_comm::get_name(),
pol_mesh::get_name(), aloc_mesh.name(),
pol_many::get_name(), aloc_many.name(), pol_few::get_name(), aloc_few.name());
fgprintf(FileGroup::all, "Starting test %s\n", test_name);
{
Range r0(test_name, Range::orange);
// make a copy of comminfo to duplicate the MPI communicator
CommInfo comminfo(comm_info);
using comm_type = Comm<pol_many, pol_few, pol_comm>;
#ifdef COMB_ENABLE_MPI
// set name of communicator
// include name of memory space if using mpi datatypes for pack/unpack
char comm_name[MPI_MAX_OBJECT_NAME] = "";
snprintf(comm_name, MPI_MAX_OBJECT_NAME, "COMB_MPI_CART_COMM%s%s",
(comm_type::use_mpi_type) ? "_" : "",
(comm_type::use_mpi_type) ? aloc_mesh.name() : "");
comminfo.set_name(comm_name);
#endif
CommContext<pol_comm> con_comm(con_comm_in
#ifdef COMB_ENABLE_MPI
,comminfo.cart.comm
#endif
);
// sometimes set cutoff to 0 (always use pol_many) to simplify algorithms
if (std::is_same<pol_many, pol_few>::value) {
// check comm send (packing) method
switch (comminfo.post_send_method) {
case CommInfo::method::waitsome:
case CommInfo::method::testsome:
// don't change cutoff to see if breaking messages into
// sized groups matters
break;
default:
// already packing individually or all together
// might aw well use simpler algorithm
comminfo.cutoff = 0;
break;
}
}
// make communicator object
comm_type comm(con_comm, comminfo, aloc_mesh, aloc_many, aloc_few);
comm.barrier();
tm_total.start(tm_con, "start-up");
std::vector<MeshData> vars;
vars.reserve(num_vars);
{
CommFactory factory(comminfo);
for (IdxT i = 0; i < num_vars; ++i) {
vars.push_back(MeshData(info, aloc_mesh));
vars[i].allocate();
DataT* data = vars[i].data();
IdxT totallen = info.totallen;
con_mesh.for_all(0, totallen,
detail::set_n1(data));
factory.add_var(vars[i]);
con_mesh.synchronize();
}
factory.populate(comm, con_many, con_few);
}
tm_total.stop(tm_con);
comm.barrier();
Range r1("test correctness", Range::indigo);
tm_total.start(tm_con, "test-comm");
IdxT ntestcycles = std::max(IdxT{1}, ncycles/IdxT{10});
for (IdxT test_cycle = 0; test_cycle < ntestcycles; ++test_cycle) { // test comm
Range r2("cycle", Range::cyan);
bool mock_communication = comm.mock_communication();
IdxT imin = info.min[0];
IdxT jmin = info.min[1];
IdxT kmin = info.min[2];
IdxT imax = info.max[0];
IdxT jmax = info.max[1];
IdxT kmax = info.max[2];
IdxT ilen = info.len[0];
IdxT jlen = info.len[1];
IdxT klen = info.len[2];
IdxT iglobal_offset = info.global_offset[0];
IdxT jglobal_offset = info.global_offset[1];
IdxT kglobal_offset = info.global_offset[2];
IdxT ilen_global = info.global.sizes[0];
IdxT jlen_global = info.global.sizes[1];
IdxT klen_global = info.global.sizes[2];
IdxT iperiodic = info.global.periodic[0];
IdxT jperiodic = info.global.periodic[1];
IdxT kperiodic = info.global.periodic[2];
IdxT ighost_width = info.ghost_widths[0];
IdxT jghost_width = info.ghost_widths[1];
IdxT kghost_width = info.ghost_widths[2];
IdxT ijlen = info.stride[2];
IdxT ijlen_global = ilen_global * jlen_global;
Range r3("pre-comm", Range::red);
// tm.start(tm_con, "pre-comm");
for (IdxT i = 0; i < num_vars; ++i) {
DataT* data = vars[i].data();
IdxT var_i = i + 1;
con_mesh.for_all_3d(0, klen,
0, jlen,
0, ilen,
[=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i, IdxT idx) {
COMB::ignore_unused(idx);
IdxT zone = i + j * ilen + k * ijlen;
IdxT iglobal = i + iglobal_offset;
if (iperiodic) {
iglobal = iglobal % ilen_global;
if (iglobal < 0) iglobal += ilen_global;
}
IdxT jglobal = j + jglobal_offset;
if (jperiodic) {
jglobal = jglobal % jlen_global;
if (jglobal < 0) jglobal += jlen_global;
}
IdxT kglobal = k + kglobal_offset;
if (kperiodic) {
kglobal = kglobal % klen_global;
if (kglobal < 0) kglobal += klen_global;
}
IdxT zone_global = iglobal + jglobal * ilen_global + kglobal * ijlen_global;
DataT expected, found, next;
int branchid = -1;
if (k >= kmin+kghost_width && k < kmax-kghost_width &&
j >= jmin+jghost_width && j < jmax-jghost_width &&
i >= imin+ighost_width && i < imax-ighost_width) {
// interior non-communicated zones
expected = -1.0; found = data[zone]; next =-(zone_global+var_i);
branchid = 0;
} else if (k >= kmin && k < kmax &&
j >= jmin && j < jmax &&
i >= imin && i < imax) {
// interior communicated zones
expected = -1.0; found = data[zone]; next = zone_global + var_i;
branchid = 1;
} else if (iglobal < 0 || iglobal >= ilen_global ||
jglobal < 0 || jglobal >= jlen_global ||
kglobal < 0 || kglobal >= klen_global) {
// out of global bounds exterior zones, some may be owned others not
// some may be communicated if at least one dimension is periodic
// and another is non-periodic
expected = -1.0; found = data[zone]; next = zone_global + var_i;
branchid = 2;
} else {
// in global bounds exterior zones
expected = -1.0; found = data[zone]; next =-(zone_global+var_i);
branchid = 3;
}
if (!mock_communication) {
if (found != expected) {
FGPRINTF(FileGroup::proc, "%p %i zone %i(%i %i %i) g%i(%i %i %i) = %f expected %f next %f\n", data, branchid, zone, i, j, k, zone_global, iglobal, jglobal, kglobal, found, expected, next);
}
// FGPRINTF(FileGroup::proc, "%p[%i] = %f\n", data, zone, 1.0);
assert(found == expected);
}
data[zone] = next;
});
}
con_mesh.synchronize();
// tm.stop(tm_con);
r3.restart("post-recv", Range::pink);
// tm.start(tm_con, "post-recv");
comm.postRecv(con_many, con_few);
// tm.stop(tm_con);
r3.restart("post-send", Range::pink);
// tm.start(tm_con, "post-send");
comm.postSend(con_many, con_few);
// tm.stop(tm_con);
r3.stop();
// for (IdxT i = 0; i < num_vars; ++i) {
// DataT* data = vars[i].data();
// IdxT var_i = i + 1;
// con_mesh.for_all_3d(0, klen,
// 0, jlen,
// 0, ilen,
// [=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i, IdxT idx) {
// COMB::ignore_unused(idx);
// IdxT zone = i + j * ilen + k * ijlen;
// IdxT iglobal = i + iglobal_offset;
// if (iperiodic) {
// iglobal = iglobal % ilen_global;
// if (iglobal < 0) iglobal += ilen_global;
// }
// IdxT jglobal = j + jglobal_offset;
// if (jperiodic) {
// jglobal = jglobal % jlen_global;
// if (jglobal < 0) jglobal += jlen_global;
// }
// IdxT kglobal = k + kglobal_offset;
// if (kperiodic) {
// kglobal = kglobal % klen_global;
// if (kglobal < 0) kglobal += klen_global;
// }
// IdxT zone_global = iglobal + jglobal * ilen_global + kglobal * ijlen_global;
// DataT expected, found, next;
// int branchid = -1;
// if (k >= kmin+kghost_width && k < kmax-kghost_width &&
// j >= jmin+jghost_width && j < jmax-jghost_width &&
// i >= imin+ighost_width && i < imax-ighost_width) {
// // interior non-communicated zones should not have changed value
// expected =-(zone_global+var_i); found = data[zone]; next = -1.0;
// branchid = 0;
// if (!mock_communication) {
// if (found != expected) {
// FGPRINTF(FileGroup::proc, "%p %i zone %i(%i %i %i) g%i(%i %i %i) = %f expected %f next %f\n", data, branchid, zone, i, j, k, zone_global, iglobal, jglobal, kglobal, found, expected, next);
// }
// // FGPRINTF(FileGroup::proc, "%p[%i] = %f\n", data, zone, 1.0);
// assert(found == expected);
// }
// data[zone] = next;
// }
// // other zones may be participating in communication, do not access
// });
// }
// con_mesh.synchronize();
r3.start("wait-recv", Range::pink);
// tm.start(tm_con, "wait-recv");
comm.waitRecv(con_many, con_few);
// tm.stop(tm_con);
r3.restart("wait-send", Range::pink);
// tm.start(tm_con, "wait-send");
comm.waitSend(con_many, con_few);
// tm.stop(tm_con);
r3.restart("post-comm", Range::red);
// tm.start(tm_con, "post-comm");
for (IdxT i = 0; i < num_vars; ++i) {
DataT* data = vars[i].data();
IdxT var_i = i + 1;
con_mesh.for_all_3d(0, klen,
0, jlen,
0, ilen,
[=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i, IdxT idx) {
COMB::ignore_unused(idx);
IdxT zone = i + j * ilen + k * ijlen;
IdxT iglobal = i + iglobal_offset;
if (iperiodic) {
iglobal = iglobal % ilen_global;
if (iglobal < 0) iglobal += ilen_global;
}
IdxT jglobal = j + jglobal_offset;
if (jperiodic) {
jglobal = jglobal % jlen_global;
if (jglobal < 0) jglobal += jlen_global;
}
IdxT kglobal = k + kglobal_offset;
if (kperiodic) {
kglobal = kglobal % klen_global;
if (kglobal < 0) kglobal += klen_global;
}
IdxT zone_global = iglobal + jglobal * ilen_global + kglobal * ijlen_global;
DataT expected, found, next;
int branchid = -1;
if (k >= kmin+kghost_width && k < kmax-kghost_width &&
j >= jmin+jghost_width && j < jmax-jghost_width &&
i >= imin+ighost_width && i < imax-ighost_width) {
// interior non-communicated zones should not have changed value
expected =-(zone_global+var_i); found = data[zone]; next = -1.0;
branchid = 0;
} else if (k >= kmin && k < kmax &&
j >= jmin && j < jmax &&
i >= imin && i < imax) {
// interior communicated zones should not have changed value
expected = zone_global + var_i; found = data[zone]; next = -1.0;
branchid = 1;
} else if (iglobal < 0 || iglobal >= ilen_global ||
jglobal < 0 || jglobal >= jlen_global ||
kglobal < 0 || kglobal >= klen_global) {
// out of global bounds exterior zones should not have changed value
// some may have been communicated, but values should be the same
expected = zone_global + var_i; found = data[zone]; next = -1.0;
branchid = 2;
} else {
// in global bounds exterior zones should have changed value
// should now be populated with data from another rank
expected = zone_global + var_i; found = data[zone]; next = -1.0;
branchid = 3;
}
if (!mock_communication) {
if (found != expected) {
FGPRINTF(FileGroup::proc, "%p %i zone %i(%i %i %i) g%i(%i %i %i) = %f expected %f next %f\n", data, branchid, zone, i, j, k, zone_global, iglobal, jglobal, kglobal, found, expected, next);
}
// FGPRINTF(FileGroup::proc, "%p[%i] = %f\n", data, zone, 1.0);
assert(found == expected);
}
data[zone] = next;
});
}
con_mesh.synchronize();
// tm.stop(tm_con);
r3.stop();
r2.stop();
}
comm.barrier();
tm_total.stop(tm_con);
tm.clear();
r1.restart("bench comm", Range::magenta);
tm_total.start(tm_con, "bench-comm");
for(IdxT cycle = 0; cycle < ncycles; cycle++) {
Range r2("cycle", Range::yellow);
IdxT imin = info.min[0];
IdxT jmin = info.min[1];
IdxT kmin = info.min[2];
IdxT imax = info.max[0];
IdxT jmax = info.max[1];
IdxT kmax = info.max[2];
IdxT ilen = info.len[0];
IdxT jlen = info.len[1];
IdxT klen = info.len[2];
IdxT ijlen = info.stride[2];
Range r3("pre-comm", Range::red);
tm.start(tm_con, "pre-comm");
for (IdxT i = 0; i < num_vars; ++i) {
DataT* data = vars[i].data();
con_mesh.for_all_3d(kmin, kmax,
jmin, jmax,
imin, imax,
detail::set_1(ilen, ijlen, data));
}
con_mesh.synchronize();
tm.stop(tm_con);
r3.restart("post-recv", Range::pink);
tm.start(tm_con, "post-recv");
comm.postRecv(con_many, con_few);
tm.stop(tm_con);
r3.restart("post-send", Range::pink);
tm.start(tm_con, "post-send");
comm.postSend(con_many, con_few);
tm.stop(tm_con);
r3.stop();
/*
for (IdxT i = 0; i < num_vars; ++i) {
DataT* data = vars[i].data();
con_mesh.for_all_3d(0, klen,
0, jlen,
0, ilen,
[=] COMB_HOST COMB_DEVICE (IdxT k, IdxT j, IdxT i, IdxT idx) {
IdxT zone = i + j * ilen + k * ijlen;
DataT expected, found, next;
if (k >= kmin && k < kmax &&
j >= jmin && j < jmax &&
i >= imin && i < imax) {
expected = 1.0; found = data[zone]; next = 1.0;
} else {
expected = -1.0; found = data[zone]; next = -1.0;
}
// if (found != expected) {
// FGPRINTF(FileGroup::proc, "zone %i(%i %i %i) = %f expected %f\n", zone, i, j, k, found, expected);
// }
//FGPRINTF(FileGroup::proc, "%p[%i] = %f\n", data, zone, 1.0);
data[zone] = next;
});
}
*/
r3.start("wait-recv", Range::pink);
tm.start(tm_con, "wait-recv");
comm.waitRecv(con_many, con_few);
tm.stop(tm_con);
r3.restart("wait-send", Range::pink);
tm.start(tm_con, "wait-send");
comm.waitSend(con_many, con_few);
tm.stop(tm_con);
r3.restart("post-comm", Range::red);
tm.start(tm_con, "post-comm");
for (IdxT i = 0; i < num_vars; ++i) {
DataT* data = vars[i].data();
con_mesh.for_all_3d(0, klen,
0, jlen,
0, ilen,
detail::reset_1(ilen, ijlen, data, imin, jmin, kmin, imax, jmax, kmax));
}
con_mesh.synchronize();
tm.stop(tm_con);
r3.stop();
r2.stop();
}
comm.barrier();
tm_total.stop(tm_con);
r1.stop();
print_timer(comminfo, tm);
print_timer(comminfo, tm_total);
}
tm.clear();
tm_total.clear();
// print_proc_memory_stats(comminfo);
}
#ifdef COMB_ENABLE_MPI
template < typename comm_pol >
void do_cycles_mpi_type(std::true_type const&,
CommContext<comm_pol>& con_comm,
CommInfo& comminfo, MeshInfo& info,
COMB::ExecContexts& exec,
AllocatorInfo& mesh_aloc,
COMB::ExecutorsAvailable& exec_avail,
IdxT num_vars, IdxT ncycles, Timer& tm, Timer& tm_total)
{
if (exec_avail.seq && exec_avail.mpi_type && exec_avail.mpi_type && should_do_cycles(con_comm, exec.seq, mesh_aloc, exec.mpi_type, mesh_aloc, exec.mpi_type, mesh_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.seq, mesh_aloc.allocator(), exec.mpi_type, mesh_aloc.allocator(), exec.mpi_type, mesh_aloc.allocator(), tm, tm_total);
#ifdef COMB_ENABLE_OPENMP
if (exec_avail.omp && exec_avail.mpi_type && exec_avail.mpi_type && should_do_cycles(con_comm, exec.omp, mesh_aloc, exec.mpi_type, mesh_aloc, exec.mpi_type, mesh_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.omp, mesh_aloc.allocator(), exec.mpi_type, mesh_aloc.allocator(), exec.mpi_type, mesh_aloc.allocator(), tm, tm_total);
#endif
#ifdef COMB_ENABLE_CUDA
if (exec_avail.cuda && exec_avail.mpi_type && exec_avail.mpi_type && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.mpi_type, mesh_aloc, exec.mpi_type, mesh_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.mpi_type, mesh_aloc.allocator(), exec.mpi_type, mesh_aloc.allocator(), tm, tm_total);
#endif
}
template < typename comm_pol >
void do_cycles_mpi_type(std::false_type const&,
CommContext<comm_pol>&,
CommInfo&, MeshInfo&,
COMB::ExecContexts&,
AllocatorInfo&,
COMB::ExecutorsAvailable&,
IdxT, IdxT, Timer&, Timer&)
{
}
#endif
template < typename comm_pol >
void do_cycles_allocator(CommContext<comm_pol>& con_comm,
CommInfo& comminfo, MeshInfo& info,
COMB::ExecContexts& exec,
AllocatorInfo& mesh_aloc,
AllocatorInfo& cpu_many_aloc, AllocatorInfo& cpu_few_aloc,
AllocatorInfo& cuda_many_aloc, AllocatorInfo& cuda_few_aloc,
COMB::ExecutorsAvailable& exec_avail,
IdxT num_vars, IdxT ncycles, Timer& tm, Timer& tm_total)
{
char name[1024] = ""; snprintf(name, 1024, "Mesh %s", mesh_aloc.allocator().name());
Range r0(name, Range::blue);
if (exec_avail.seq && exec_avail.seq && exec_avail.seq && should_do_cycles(con_comm, exec.seq, mesh_aloc, exec.seq, cpu_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.seq, mesh_aloc.allocator(), exec.seq, cpu_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
#ifdef COMB_ENABLE_OPENMP
if (exec_avail.omp && exec_avail.seq && exec_avail.seq && should_do_cycles(con_comm, exec.omp, mesh_aloc, exec.seq, cpu_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.omp, mesh_aloc.allocator(), exec.seq, cpu_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
if (exec_avail.omp && exec_avail.omp && exec_avail.seq && should_do_cycles(con_comm, exec.omp, mesh_aloc, exec.omp, cpu_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.omp, mesh_aloc.allocator(), exec.omp, cpu_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
if (exec_avail.omp && exec_avail.omp && exec_avail.omp && should_do_cycles(con_comm, exec.omp, mesh_aloc, exec.omp, cpu_many_aloc, exec.omp, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.omp, mesh_aloc.allocator(), exec.omp, cpu_many_aloc.allocator(), exec.omp, cpu_few_aloc.allocator(), tm, tm_total);
#endif
#ifdef COMB_ENABLE_CUDA
if (exec_avail.cuda && exec_avail.seq && exec_avail.seq && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.seq, cpu_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.seq, cpu_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
#ifdef COMB_ENABLE_OPENMP
if (exec_avail.cuda && exec_avail.omp && exec_avail.seq && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.omp, cpu_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.omp, cpu_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
if (exec_avail.cuda && exec_avail.omp && exec_avail.omp && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.omp, cpu_many_aloc, exec.omp, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.omp, cpu_many_aloc.allocator(), exec.omp, cpu_few_aloc.allocator(), tm, tm_total);
#endif
if (exec_avail.cuda && exec_avail.cuda && exec_avail.seq && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda, cuda_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda, cuda_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
if (exec_avail.cuda && exec_avail.cuda && exec_avail.cuda && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda, cuda_many_aloc, exec.cuda, cuda_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda, cuda_many_aloc.allocator(), exec.cuda, cuda_few_aloc.allocator(), tm, tm_total);
{
if (exec_avail.cuda && exec_avail.cuda_batch && exec_avail.seq && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda_batch, cuda_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda_batch, cuda_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
if (exec_avail.cuda && exec_avail.cuda_batch && exec_avail.cuda_batch && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda_batch, cuda_many_aloc, exec.cuda_batch, cuda_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda_batch, cuda_many_aloc.allocator(), exec.cuda_batch, cuda_few_aloc.allocator(), tm, tm_total);
if (exec_avail.cuda && exec_avail.cuda_persistent && exec_avail.seq && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda_persistent, cuda_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda_persistent, cuda_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
if (exec_avail.cuda && exec_avail.cuda_persistent && exec_avail.cuda_persistent && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda_persistent, cuda_many_aloc, exec.cuda_persistent, cuda_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda_persistent, cuda_many_aloc.allocator(), exec.cuda_persistent, cuda_few_aloc.allocator(), tm, tm_total);
SetReset<bool> sr_gs(get_batch_always_grid_sync(), false);
if (exec_avail.cuda && exec_avail.cuda_batch_fewgs && exec_avail.seq && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda_batch, cuda_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda_batch, cuda_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
if (exec_avail.cuda && exec_avail.cuda_batch_fewgs && exec_avail.cuda_batch_fewgs && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda_batch, cuda_many_aloc, exec.cuda_batch, cuda_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda_batch, cuda_many_aloc.allocator(), exec.cuda_batch, cuda_few_aloc.allocator(), tm, tm_total);
if (exec_avail.cuda && exec_avail.cuda_persistent_fewgs && exec_avail.seq && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda_persistent, cuda_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda_persistent, cuda_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
if (exec_avail.cuda && exec_avail.cuda_persistent_fewgs && exec_avail.cuda_persistent_fewgs && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda_persistent, cuda_many_aloc, exec.cuda_persistent, cuda_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda_persistent, cuda_many_aloc.allocator(), exec.cuda_persistent, cuda_few_aloc.allocator(), tm, tm_total);
}
#ifdef COMB_ENABLE_CUDA_GRAPH
if (exec_avail.cuda && exec_avail.cuda_graph && exec_avail.seq && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda_graph, cuda_many_aloc, exec.seq, cpu_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda_graph, cuda_many_aloc.allocator(), exec.seq, cpu_few_aloc.allocator(), tm, tm_total);
if (exec_avail.cuda && exec_avail.cuda_graph && exec_avail.cuda_graph && should_do_cycles(con_comm, exec.cuda, mesh_aloc, exec.cuda_graph, cuda_many_aloc, exec.cuda_graph, cuda_few_aloc))
do_cycles(con_comm, comminfo, info, num_vars, ncycles, exec.cuda, mesh_aloc.allocator(), exec.cuda_graph, cuda_many_aloc.allocator(), exec.cuda_graph, cuda_few_aloc.allocator(), tm, tm_total);
#endif
#else
COMB::ignore_unused(cuda_many_aloc, cuda_few_aloc);
#endif
#ifdef COMB_ENABLE_MPI
do_cycles_mpi_type(typename std::conditional<comm_pol::use_mpi_type, std::true_type, std::false_type>::type{},
con_comm, comminfo, info, exec, mesh_aloc, exec_avail, num_vars, ncycles, tm, tm_total);
#endif
}
template < typename comm_pol >
void do_cycles_allocators(CommContext<comm_pol>& con_comm,
CommInfo& comminfo, MeshInfo& info,
COMB::ExecContexts& exec,
Allocators& alloc,
AllocatorInfo& cpu_many_aloc, AllocatorInfo& cpu_few_aloc,
AllocatorInfo& cuda_many_aloc, AllocatorInfo& cuda_few_aloc,
COMB::ExecutorsAvailable& exec_avail,
IdxT num_vars, IdxT ncycles, Timer& tm, Timer& tm_total)
{
do_cycles_allocator(con_comm,
comminfo, info,
exec,
alloc.host,
cpu_many_aloc, cpu_few_aloc,
cuda_many_aloc, cuda_few_aloc,
exec_avail,
num_vars, ncycles, tm, tm_total);
#ifdef COMB_ENABLE_CUDA
do_cycles_allocator(con_comm,
comminfo, info,
exec,
alloc.cuda_hostpinned,
cpu_many_aloc, cpu_few_aloc,
cuda_many_aloc, cuda_few_aloc,
exec_avail,
num_vars, ncycles, tm, tm_total);
do_cycles_allocator(con_comm,
comminfo, info,
exec,
alloc.cuda_device,
cpu_many_aloc, cpu_few_aloc,
cuda_many_aloc, cuda_few_aloc,
exec_avail,
num_vars, ncycles, tm, tm_total);
do_cycles_allocator(con_comm,
comminfo, info,
exec,
alloc.cuda_managed,
cpu_many_aloc, cpu_few_aloc,
cuda_many_aloc, cuda_few_aloc,
exec_avail,
num_vars, ncycles, tm, tm_total);
do_cycles_allocator(con_comm,
comminfo, info,
exec,
alloc.cuda_managed_host_preferred,
cpu_many_aloc, cpu_few_aloc,
cuda_many_aloc, cuda_few_aloc,
exec_avail,
num_vars, ncycles, tm, tm_total);
do_cycles_allocator(con_comm,
comminfo, info,
exec,
alloc.cuda_managed_host_preferred_device_accessed,
cpu_many_aloc, cpu_few_aloc,
cuda_many_aloc, cuda_few_aloc,
exec_avail,
num_vars, ncycles, tm, tm_total);
do_cycles_allocator(con_comm,
comminfo, info,
exec,
alloc.cuda_managed_device_preferred,
cpu_many_aloc, cpu_few_aloc,
cuda_many_aloc, cuda_few_aloc,
exec_avail,
num_vars, ncycles, tm, tm_total);
do_cycles_allocator(con_comm,
comminfo, info,
exec,
alloc.cuda_managed_device_preferred_host_accessed,
cpu_many_aloc, cpu_few_aloc,
cuda_many_aloc, cuda_few_aloc,
exec_avail,
num_vars, ncycles, tm, tm_total);
#endif // COMB_ENABLE_CUDA
}
} // namespace COMB
#endif // _DO_CYCLES_HPP
| 42.143617 | 223 | 0.587278 | [
"mesh",
"object",
"vector"
] |
b83fc16e298bbe9d0d858fbff24079151612b427 | 2,124 | hpp | C++ | include/strex.hpp | m1nuz/launchdb | bd3ed8817dce00af8091ee5df9e9082fc5698f15 | [
"MIT"
] | null | null | null | include/strex.hpp | m1nuz/launchdb | bd3ed8817dce00af8091ee5df9e9082fc5698f15 | [
"MIT"
] | null | null | null | include/strex.hpp | m1nuz/launchdb | bd3ed8817dce00af8091ee5df9e9082fc5698f15 | [
"MIT"
] | null | null | null | #pragma once
#include <sstream>
#include <vector>
#include <locale>
#include <algorithm>
namespace strex {
template <typename T>
inline T from_string(const std::string& str)
{
std::stringstream buff(str);
T value;
buff >> value;
return value;
}
constexpr unsigned int hash(const char* str, int h = 0)
{
return !str[h] ? 5381 : (hash(str, h + 1) * 33) ^ str[h];
}
inline unsigned int hash(const std::string& str)
{
return hash(str.c_str());
}
inline std::vector<std::string> split(const std::string& text, const std::string& delims) {
std::vector<std::string> tokens;
auto start = text.find_first_not_of(delims);
auto end = std::string::size_type{0};
while ((end = text.find_first_of(delims, start)) != std::string::npos) {
tokens.push_back(text.substr(start, end - start));
start = text.find_first_not_of(delims, end);
}
if (start != std::string::npos)
tokens.push_back(text.substr(start));
return tokens;
}
template <typename C>
inline std::string join(const C& strs, const std::string& delimiter)
{
std::stringstream buff;
size_t s = 1;
for (const std::string& str : strs)
{
buff << str;
if (s != strs.size())
{
buff << delimiter;
}
s++;
}
return buff.str();
}
inline std::string tolower(const std::string& str, const std::locale& loc = std::locale("C")) {
std::string result(str.size(), '\0');
std::transform(str.begin(), str.end(), result.begin(), [&] (char c) {
return std::tolower(c, loc);
});
return result;
}
inline std::string toupper(const std::string& str, const std::locale& loc = std::locale("C")) {
std::string result(str.size(), '\0');
std::transform(str.begin(), str.end(), result.begin(), [&] (char c) {
return std::toupper(c, loc);
});
return result;
}
}
| 24.988235 | 99 | 0.533898 | [
"vector",
"transform"
] |
cdc44ae01646d996136abca3c3887dbf8520aa2e | 4,983 | cpp | C++ | tests/fluid_cylinder_mpi_insimex/fluid_cylinder_mpi_insimex.cpp | yufeimi/OpenIFEM | 51cdd1633e41a3f5a3175e216c8584da43f3dc76 | [
"Apache-2.0"
] | 20 | 2019-04-08T15:24:52.000Z | 2021-04-04T16:52:32.000Z | tests/fluid_cylinder_mpi_insimex/fluid_cylinder_mpi_insimex.cpp | yufeimi/OpenIFEM | 51cdd1633e41a3f5a3175e216c8584da43f3dc76 | [
"Apache-2.0"
] | 18 | 2018-05-10T14:42:23.000Z | 2022-02-24T18:41:54.000Z | tests/fluid_cylinder_mpi_insimex/fluid_cylinder_mpi_insimex.cpp | yufeimi/OpenIFEM | 51cdd1633e41a3f5a3175e216c8584da43f3dc76 | [
"Apache-2.0"
] | 20 | 2018-04-16T01:40:28.000Z | 2021-07-13T05:55:15.000Z | /**
* This program tests InsIMEX solver with a 2D flow around
* cylinder
* case.
* Hard-coded parabolic velocity input is used, and Re = 20.
* Only one step is run, and the test takes about 33s.
*/
#include "mpi_insimex.h"
extern template class Fluid::MPI::InsIMEX<2>;
extern template class Fluid::MPI::InsIMEX<3>;
extern template class Utils::GridCreator<2>;
extern template class Utils::GridCreator<3>;
using namespace dealii;
int main(int argc, char *argv[])
{
try
{
Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);
std::string infile("parameters.prm");
if (argc > 1)
{
infile = argv[1];
}
Parameters::AllParameters params(infile);
auto inflow_bc = [dim = params.dimension](const Point<2> &p,
const unsigned int component,
const double time) -> double {
(void)time;
double left_boundary = (dim == 2 ? 0.0 : -0.3);
unsigned int flow_component = (dim == 2 ? 0 : 2);
if (component == flow_component &&
std::abs(p[flow_component] - left_boundary) < 1e-10)
{
// For a parabolic velocity profile, Uavg = 2/3 * Umax in
// 2D, and 4/9 * Umax in 3D. If nu = 0.001, D = 0.1, then Re
// = 100 * Uavg
double Uavg = 0.2;
double Umax = (dim == 2 ? 3 * Uavg / 2 : 9 * Uavg / 4);
double value = 4 * Umax * p[1] * (0.41 - p[1]) / (0.41 * 0.41);
if (dim == 3)
{
value *= 4 * p[2] * (0.41 - p[2]) / (0.41 * 0.41);
}
return value;
}
return 0.0;
};
auto inflow_bc_3d = [dim =
params.dimension](const Point<3> &p,
const unsigned int component,
const double time) -> double {
(void)time;
double left_boundary = (dim == 2 ? 0.0 : -0.3);
unsigned int flow_component = (dim == 2 ? 0 : 2);
if (component == flow_component &&
std::abs(p[flow_component] - left_boundary) < 1e-10)
{
// For a parabolic velocity profile, Uavg = 2/3 * Umax in
// 2D, and 4/9 * Umax in 3D. If nu = 0.001, D = 0.1, then Re
// = 100 * Uavg
double Uavg = 0.2;
double Umax = (dim == 2 ? 3 * Uavg / 2 : 9 * Uavg / 4);
double value = 4 * Umax * p[1] * (0.41 - p[1]) / (0.41 * 0.41);
if (dim == 3)
{
value *= 4 * p[2] * (0.41 - p[2]) / (0.41 * 0.41);
}
return value;
}
return 0.0;
};
if (params.dimension == 2)
{
parallel::distributed::Triangulation<2> tria(MPI_COMM_WORLD);
Utils::GridCreator<2>::flow_around_cylinder(tria);
Fluid::MPI::InsIMEX<2> flow(tria, params);
flow.add_hard_coded_boundary_condition(0, inflow_bc);
flow.run();
// Check the max values of velocity and pressure
auto solution = flow.get_current_solution();
auto v = solution.block(0), p = solution.block(1);
double vmax = Utils::PETScVectorMax(v);
double pmax = Utils::PETScVectorMax(p);
double verror = std::abs(vmax - 0.374062) / 0.374062;
double perror = std::abs(pmax - 46.5308) / 46.5308;
AssertThrow(verror < 1e-3 && perror < 1e-3,
ExcMessage("Maximum velocity or pressure is incorrect!"));
}
else if (params.dimension == 3)
{
parallel::distributed::Triangulation<3> tria(MPI_COMM_WORLD);
Utils::GridCreator<3>::flow_around_cylinder(tria);
Fluid::MPI::InsIMEX<3> flow(tria, params);
flow.add_hard_coded_boundary_condition(4, inflow_bc_3d);
flow.run();
}
else
{
AssertThrow(false, ExcMessage("This test should be run in 2D!"));
}
}
catch (std::exception &exc)
{
std::cerr << std::endl
<< std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Exception on processing: " << std::endl
<< exc.what() << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
catch (...)
{
std::cerr << std::endl
<< std::endl
<< "----------------------------------------------------"
<< std::endl;
std::cerr << "Unknown exception!" << std::endl
<< "Aborting!" << std::endl
<< "----------------------------------------------------"
<< std::endl;
return 1;
}
return 0;
}
| 36.372263 | 80 | 0.459161 | [
"3d"
] |
cdc83d94b563a16ee6bf6f0560151cd01cd0a8ed | 716 | cxx | C++ | VFRendering/src/RendererBase.cxx | ddkn/spirit | 8e51bcdd78ee05d433d000c7e389fe1e6c3716bc | [
"MIT"
] | 92 | 2016-10-02T16:17:27.000Z | 2022-02-22T11:23:49.000Z | VFRendering/src/RendererBase.cxx | ddkn/spirit | 8e51bcdd78ee05d433d000c7e389fe1e6c3716bc | [
"MIT"
] | 590 | 2016-09-24T12:46:36.000Z | 2022-03-24T18:27:18.000Z | VFRendering/src/RendererBase.cxx | ddkn/spirit | 8e51bcdd78ee05d433d000c7e389fe1e6c3716bc | [
"MIT"
] | 46 | 2016-09-26T07:20:17.000Z | 2022-02-17T19:55:17.000Z | #include "VFRendering/RendererBase.hxx"
namespace VFRendering {
RendererBase::RendererBase(const View& view) : m_view(view), m_options(m_view.options()) {}
const Options& RendererBase::options() const {
return m_options;
}
void RendererBase::options(const Options& options) {
m_options = Options();
updateOptions(options);
}
void RendererBase::optionsHaveChanged(const std::vector<int>& changed_options) {
(void)changed_options;
}
void RendererBase::updateOptions(const Options& options) {
auto changed_options = m_options.update(options);
if (changed_options.size() == 0) {
return;
}
optionsHaveChanged(changed_options);
}
void RendererBase::updateIfNecessary() { }
}
| 23.866667 | 91 | 0.72486 | [
"vector"
] |
cdd256e209bad130153d6b43d3f3f5e04ffdb83e | 515 | cpp | C++ | Zerojudge/b235.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | 9 | 2017-10-08T16:22:03.000Z | 2021-08-20T09:32:17.000Z | Zerojudge/b235.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | null | null | null | Zerojudge/b235.cpp | w181496/OJ | 67d1d32770376865eba8a9dd1767e97dae68989a | [
"MIT"
] | 2 | 2018-01-15T16:35:44.000Z | 2019-03-21T18:30:04.000Z | #include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
vector<int>k;
k.push_back(2);
for(long long int i=3;i<=10000;i+=2)
{
int t=0;
for(long long int j=3;j<=sqrt(i);j+=2)
{
if(i%j==0)
t=1;
}
if(t==0)
k.push_back(i);
}
long long int n,e;
cin>>e;
for(int i=1;i<=e;i++)
{
cin>>n;
cout<<k[n+1]<<endl;
}
return 0;
}
| 17.166667 | 47 | 0.407767 | [
"vector"
] |
cdd8854d352129c1887c29782ff828cce834983c | 10,730 | hpp | C++ | componentLibraries/defaultLibrary/Hydraulic/Restrictors/HydraulicOrificeG.hpp | mjfwest/hopsan | 77a0a1e69fd9588335b7e932f348972186cbdf6f | [
"Apache-2.0"
] | null | null | null | componentLibraries/defaultLibrary/Hydraulic/Restrictors/HydraulicOrificeG.hpp | mjfwest/hopsan | 77a0a1e69fd9588335b7e932f348972186cbdf6f | [
"Apache-2.0"
] | null | null | null | componentLibraries/defaultLibrary/Hydraulic/Restrictors/HydraulicOrificeG.hpp | mjfwest/hopsan | 77a0a1e69fd9588335b7e932f348972186cbdf6f | [
"Apache-2.0"
] | null | null | null | /*-----------------------------------------------------------------------------
Copyright 2017 Hopsan Group
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.
The full license is available in the file LICENSE.
For details about the 'Hopsan Group' or information about Authors and
Contributors see the HOPSANGROUP and AUTHORS files that are located in
the Hopsan source code root directory.
-----------------------------------------------------------------------------*/
#ifndef HYDRAULICORIFICEG_HPP_INCLUDED
#define HYDRAULICORIFICEG_HPP_INCLUDED
#include <iostream>
#include "ComponentEssentials.h"
#include "ComponentUtilities.h"
#include "math.h"
//!
//! @file HydraulicOrificeG.hpp
//! @author Petter Krus <petter.krus@liu.se>
// co-author/auditor **Not yet audited by a second person**
//! @date Wed 5 Aug 2015 09:23:32
//! @brief A general orifice with geometric parameters
//! @ingroup HydraulicComponents
//!
//==This code has been autogenerated using Compgen==
//from
/*{, C:, HopsanTrunk, componentLibraries, defaultLibrary, Hydraulic, \
Restrictors}/HydraulicOrificeG.nb*/
using namespace hopsan;
class HydraulicOrificeG : public ComponentQ
{
private:
double rho;
double visc;
double Ao;
double dh;
double lo;
double Cdt;
double del;
double sf;
Port *mpP1;
Port *mpP2;
double delayParts1[9];
double delayParts2[9];
double delayParts3[9];
Matrix jacobianMatrix;
Vec systemEquations;
Matrix delayedPart;
int i;
int iter;
int mNoiter;
double jsyseqnweight[4];
int order[3];
int mNstep;
//Port P1 variable
double p1;
double q1;
double T1;
double dE1;
double c1;
double Zc1;
//Port P2 variable
double p2;
double q2;
double T2;
double dE2;
double c2;
double Zc2;
//==This code has been autogenerated using Compgen==
//inputVariables
//outputVariables
double Ro;
double DRL;
double Cd;
//Expressions variables
//Port P1 pointer
double *mpND_p1;
double *mpND_q1;
double *mpND_T1;
double *mpND_dE1;
double *mpND_c1;
double *mpND_Zc1;
//Port P2 pointer
double *mpND_p2;
double *mpND_q2;
double *mpND_T2;
double *mpND_dE2;
double *mpND_c2;
double *mpND_Zc2;
//Delay declarations
//==This code has been autogenerated using Compgen==
//inputVariables pointers
//inputParameters pointers
double *mprho;
double *mpvisc;
double *mpAo;
double *mpdh;
double *mplo;
double *mpCdt;
double *mpdel;
double *mpsf;
//outputVariables pointers
double *mpRo;
double *mpDRL;
double *mpCd;
Delay mDelayedPart10;
EquationSystemSolver *mpSolver;
public:
static Component *Creator()
{
return new HydraulicOrificeG();
}
void configure()
{
//==This code has been autogenerated using Compgen==
mNstep=9;
jacobianMatrix.create(3,3);
systemEquations.create(3);
delayedPart.create(4,6);
mNoiter=2;
jsyseqnweight[0]=1;
jsyseqnweight[1]=0.67;
jsyseqnweight[2]=0.5;
jsyseqnweight[3]=0.5;
//Add ports to the component
mpP1=addPowerPort("P1","NodeHydraulic");
mpP2=addPowerPort("P2","NodeHydraulic");
//Add inputVariables to the component
//Add inputParammeters to the component
addInputVariable("rho", "oil density", "kg/m3", 860.,&mprho);
addInputVariable("visc", "Dynamic viscosity ", "m", \
0.12,&mpvisc);
addInputVariable("Ao", "Orifice area", "m2", 1.e-7,&mpAo);
addInputVariable("dh", "Orifice hydraulic diameter", "m", \
0.0025,&mpdh);
addInputVariable("lo", "Length", "m", 0.001,&mplo);
addInputVariable("Cdt", "Turbulent discharge coeff", "", \
0.611,&mpCdt);
addInputVariable("del", "Laminar flow coefficient", "", \
0.157,&mpdel);
addInputVariable("sf", "Shape factor round=1, rectangle=0.", "", \
0,&mpsf);
//Add outputVariables to the component
addOutputVariable("Ro","Rynolds number","",0.,&mpRo);
addOutputVariable("DRL","dh Ro/lo","",0.,&mpDRL);
addOutputVariable("Cd","Discharge coeff","",0.611,&mpCd);
//==This code has been autogenerated using Compgen==
//Add constantParameters
mpSolver = new EquationSystemSolver(this,3);
}
void initialize()
{
//Read port variable pointers from nodes
//Port P1
mpND_p1=getSafeNodeDataPtr(mpP1, NodeHydraulic::Pressure);
mpND_q1=getSafeNodeDataPtr(mpP1, NodeHydraulic::Flow);
mpND_T1=getSafeNodeDataPtr(mpP1, NodeHydraulic::Temperature);
mpND_dE1=getSafeNodeDataPtr(mpP1, NodeHydraulic::HeatFlow);
mpND_c1=getSafeNodeDataPtr(mpP1, NodeHydraulic::WaveVariable);
mpND_Zc1=getSafeNodeDataPtr(mpP1, NodeHydraulic::CharImpedance);
//Port P2
mpND_p2=getSafeNodeDataPtr(mpP2, NodeHydraulic::Pressure);
mpND_q2=getSafeNodeDataPtr(mpP2, NodeHydraulic::Flow);
mpND_T2=getSafeNodeDataPtr(mpP2, NodeHydraulic::Temperature);
mpND_dE2=getSafeNodeDataPtr(mpP2, NodeHydraulic::HeatFlow);
mpND_c2=getSafeNodeDataPtr(mpP2, NodeHydraulic::WaveVariable);
mpND_Zc2=getSafeNodeDataPtr(mpP2, NodeHydraulic::CharImpedance);
//Read variables from nodes
//Port P1
p1 = (*mpND_p1);
q1 = (*mpND_q1);
T1 = (*mpND_T1);
dE1 = (*mpND_dE1);
c1 = (*mpND_c1);
Zc1 = (*mpND_Zc1);
//Port P2
p2 = (*mpND_p2);
q2 = (*mpND_q2);
T2 = (*mpND_T2);
dE2 = (*mpND_dE2);
c2 = (*mpND_c2);
Zc2 = (*mpND_Zc2);
//Read inputVariables from nodes
//Read inputParameters from nodes
rho = (*mprho);
visc = (*mpvisc);
Ao = (*mpAo);
dh = (*mpdh);
lo = (*mplo);
Cdt = (*mpCdt);
del = (*mpdel);
sf = (*mpsf);
//Read outputVariables from nodes
Ro = (*mpRo);
DRL = (*mpDRL);
Cd = (*mpCd);
//==This code has been autogenerated using Compgen==
//Initialize delays
delayedPart[1][1] = delayParts1[1];
delayedPart[2][1] = delayParts2[1];
delayedPart[3][1] = delayParts3[1];
simulateOneTimestep();
}
void simulateOneTimestep()
{
Vec stateVar(3);
Vec stateVark(3);
Vec deltaStateVar(3);
//Read variables from nodes
//Port P1
T1 = (*mpND_T1);
c1 = (*mpND_c1);
Zc1 = (*mpND_Zc1);
//Port P2
T2 = (*mpND_T2);
c2 = (*mpND_c2);
Zc2 = (*mpND_Zc2);
//Read inputVariables from nodes
//Read inputParameters from nodes
rho = (*mprho);
visc = (*mpvisc);
Ao = (*mpAo);
dh = (*mpdh);
lo = (*mplo);
Cdt = (*mpCdt);
del = (*mpdel);
sf = (*mpsf);
//LocalExpressions
//Initializing variable vector for Newton-Raphson
stateVark[0] = q2;
stateVark[1] = p1;
stateVark[2] = p2;
//Iterative solution using Newton-Rapshson
for(iter=1;iter<=mNoiter;iter++)
{
//OrificeG
//Differential-algebraic system of equation parts
//Assemble differential-algebraic equations
systemEquations[0] =q2 - (2*(p1 - p2))/Sqrt((Power(Cdt,2)*Power(dh \
- 32*Power(del,2)*lo*(-3 + sf),2)*Power(visc,2) + \
2*Power(del,4)*Power(dh,4)*rho*Abs(p1 - \
p2))/(Power(Ao,2)*Power(Cdt,2)*Power(del,4)*Power(dh,4)));
systemEquations[1] =p1 - lowLimit(c1 - q2*Zc1,0);
systemEquations[2] =p2 - lowLimit(c2 + q2*Zc2,0);
//Jacobian matrix
jacobianMatrix[0][0] = 1;
jacobianMatrix[0][1] = -2/Sqrt((Power(Cdt,2)*Power(dh - \
32*Power(del,2)*lo*(-3 + sf),2)*Power(visc,2) + \
2*Power(del,4)*Power(dh,4)*rho*Abs(p1 - \
p2))/(Power(Ao,2)*Power(Cdt,2)*Power(del,4)*Power(dh,4))) + (2*(p1 - \
p2)*rho*dxAbs(p1 - \
p2))/(Power(Ao,2)*Power(Cdt,2)*Power((Power(Cdt,2)*Power(dh - \
32*Power(del,2)*lo*(-3 + sf),2)*Power(visc,2) + \
2*Power(del,4)*Power(dh,4)*rho*Abs(p1 - \
p2))/(Power(Ao,2)*Power(Cdt,2)*Power(del,4)*Power(dh,4)),1.5));
jacobianMatrix[0][2] = 2/Sqrt((Power(Cdt,2)*Power(dh - \
32*Power(del,2)*lo*(-3 + sf),2)*Power(visc,2) + \
2*Power(del,4)*Power(dh,4)*rho*Abs(p1 - \
p2))/(Power(Ao,2)*Power(Cdt,2)*Power(del,4)*Power(dh,4))) - (2*(p1 - \
p2)*rho*dxAbs(p1 - \
p2))/(Power(Ao,2)*Power(Cdt,2)*Power((Power(Cdt,2)*Power(dh - \
32*Power(del,2)*lo*(-3 + sf),2)*Power(visc,2) + \
2*Power(del,4)*Power(dh,4)*rho*Abs(p1 - \
p2))/(Power(Ao,2)*Power(Cdt,2)*Power(del,4)*Power(dh,4)),1.5));
jacobianMatrix[1][0] = Zc1*dxLowLimit(c1 - q2*Zc1,0);
jacobianMatrix[1][1] = 1;
jacobianMatrix[1][2] = 0;
jacobianMatrix[2][0] = -(Zc2*dxLowLimit(c2 + q2*Zc2,0));
jacobianMatrix[2][1] = 0;
jacobianMatrix[2][2] = 1;
//==This code has been autogenerated using Compgen==
//Solving equation using LU-faktorisation
mpSolver->solve(jacobianMatrix, systemEquations, stateVark, iter);
q2=stateVark[0];
p1=stateVark[1];
p2=stateVark[2];
//Expressions
q1 = -q2;
Ro = (dh*rho*Abs(q2))/(Ao*visc);
DRL = (dh*Ro)/(0.1*dh + lo);
Cd = Abs(q2)/(Sqrt(2)*Ao*Sqrt((0.1 + Abs(p1 - p2))/rho));
}
//Calculate the delayed parts
delayedPart[1][1] = delayParts1[1];
delayedPart[2][1] = delayParts2[1];
delayedPart[3][1] = delayParts3[1];
//Write new values to nodes
//Port P1
(*mpND_p1)=p1;
(*mpND_q1)=q1;
(*mpND_dE1)=dE1;
//Port P2
(*mpND_p2)=p2;
(*mpND_q2)=q2;
(*mpND_dE2)=dE2;
//outputVariables
(*mpRo)=Ro;
(*mpDRL)=DRL;
(*mpCd)=Cd;
//Update the delayed variabels
}
void deconfigure()
{
delete mpSolver;
}
};
#endif // HYDRAULICORIFICEG_HPP_INCLUDED
| 29.972067 | 79 | 0.582665 | [
"shape",
"vector"
] |
cddc070e00d257954678aca2784f452652e59794 | 1,563 | cpp | C++ | src/main/_2021/day07.cpp | Namdrib/adventofcode | c9479eb85326bcf9881396626523fb2a5524bf87 | [
"MIT"
] | null | null | null | src/main/_2021/day07.cpp | Namdrib/adventofcode | c9479eb85326bcf9881396626523fb2a5524bf87 | [
"MIT"
] | 6 | 2018-12-03T04:43:00.000Z | 2020-12-12T12:42:02.000Z | src/main/_2021/day07.cpp | Namdrib/adventofcode | c9479eb85326bcf9881396626523fb2a5524bf87 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include "../util/helpers.cpp"
using namespace std;
// https://adventofcode.com/2021/day/7
// calculate how much fuel it takes to move every crab to target_pos
// for part one, the cost to move from a position pos to target_pos is linear
// for part two, every step costs one more (e.g. 1 -> 2 -> 3 ...)
size_t get_fuel_cost(const vector<size_t> &in, size_t target_pos, bool part_two)
{
size_t fuel_to_use = accumulate(all(in), (size_t)0, [target_pos, part_two](size_t acc, size_t pos)
{
size_t cost = (target_pos < pos ? pos - target_pos : target_pos - pos);;
if (part_two)
{
cost = cost * (cost + 1) / 2;
}
return acc += cost;
}
);
return fuel_to_use;
}
size_t part_one(const vector<size_t> &in, bool part_two)
{
size_t min_pos = *min_element(all(in));
size_t max_pos = *max_element(all(in));
size_t min_fuel_to_best_pos = numeric_limits<size_t>::max();
// find the horizontal position that requires the least movement
// to align all the crabs to
for (size_t i = min_pos; i <= max_pos; i++)
{
size_t fuel_to_use = get_fuel_cost(in, i, part_two);
if (fuel_to_use < min_fuel_to_best_pos)
{
min_fuel_to_best_pos = fuel_to_use;
}
}
return min_fuel_to_best_pos;
}
size_t part_two(const vector<size_t> &in, bool part_two)
{
return part_one(in, part_two);
}
int main()
{
string s;
getline(cin, s);
vector<size_t> input = extract_nums_from<size_t>(s);
cout << "Part 1: " << part_one(input, false) << endl;
cout << "Part 2: " << part_two(input, true) << endl;
}
| 25.209677 | 100 | 0.673704 | [
"vector"
] |
cddf09896d6d70d72f62196bf47c82edc1bd5971 | 429 | cpp | C++ | Efficient Janitor.cpp | saber-030/Data-Structures-and-Algorithms-CSF211 | caa33c57b10b1fb2474f0c078c803be697b6cae8 | [
"MIT"
] | 1 | 2021-09-09T05:22:51.000Z | 2021-09-09T05:22:51.000Z | Efficient Janitor.cpp | saber-030/Data-Structures-and-Algorithms-CSF211 | caa33c57b10b1fb2474f0c078c803be697b6cae8 | [
"MIT"
] | null | null | null | Efficient Janitor.cpp | saber-030/Data-Structures-and-Algorithms-CSF211 | caa33c57b10b1fb2474f0c078c803be697b6cae8 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main(){
long long n;
cin>>n;
double x;
vector<double> obj(n);
for(long long i=0; i<n; i++){
cin>>x;
obj[i] = x;
}
sort(obj.begin(), obj.end(), greater<double>());
long long i=0, j=n-1, ans = 0;
while(i<j){
if(obj[i] + obj[j] <= 3){
i++;
j--;
}
else{
i++;
}
ans++;
}
if(i==j){
cout<<ans+1<<endl;
}
else{
cout<<ans<<endl;
}
return 0;
} | 12.257143 | 49 | 0.501166 | [
"vector"
] |
cde7797d4c6f91e30faf269db58c2827f96a5cad | 674 | cpp | C++ | src/spellchooser.cpp | mikelukas/errantry | e1c09ca5ef8bc9ef32cf8bcb86306a1415ddd37c | [
"MIT"
] | 1 | 2018-05-11T16:09:35.000Z | 2018-05-11T16:09:35.000Z | src/spellchooser.cpp | mikelukas/errantry | e1c09ca5ef8bc9ef32cf8bcb86306a1415ddd37c | [
"MIT"
] | null | null | null | src/spellchooser.cpp | mikelukas/errantry | e1c09ca5ef8bc9ef32cf8bcb86306a1415ddd37c | [
"MIT"
] | null | null | null | #include "spellchooser.h"
SpellChooser::SpellChooser(vector<const SpellTemplate*>* spellChoices, const Player& player)
: InventoryChooser(spellChoices),
player(player)
{
}
void SpellChooser::displayRelevantStats() const
{
StatsDisplayer::fullDisplayFor(player);
}
void SpellChooser::displayInventoryChoices() const
{
for(int i = 0; i < eligibleChoices->size(); i++)
{
displayChoice(i, (*eligibleChoices)[i]);
}
cout<<endl;
}
void SpellChooser::displayChoice(int choiceNum, const SpellTemplate* spellChoice) const
{
ostringstream choiceNumStr;
choiceNumStr<<choiceNum+1<<")";
cout<<std::left<<setw(4)<<choiceNumStr.str(); displaySpellLine(spellChoice);
}
| 21.741935 | 92 | 0.746291 | [
"vector"
] |
cde792cbd1e69a0a6ffcb24ffdd5a32e68282f77 | 8,415 | hpp | C++ | DemoFramework/FslBase/include/FslBase/Collections/CircularFixedSizeBuffer.hpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoFramework/FslBase/include/FslBase/Collections/CircularFixedSizeBuffer.hpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | DemoFramework/FslBase/include/FslBase/Collections/CircularFixedSizeBuffer.hpp | alexvonduar/gtec-demo-framework | 6f8a7e429d0e15242ba64eb4cb41bfc2dd7dc749 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | #ifndef FSLBASE_COLLECTIONS_CIRCULARFIXEDSIZEBUFFER_HPP
#define FSLBASE_COLLECTIONS_CIRCULARFIXEDSIZEBUFFER_HPP
/****************************************************************************************************************************************************
* Copyright 2019 NXP
* 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 NXP. 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 <cassert>
#include <cstddef>
#include <stdexcept>
#include <utility>
#include <vector>
namespace Fsl
{
//! @brief implements a circular fixed size buffer
// Once the capacity has been reached and a new element is inserted we then remove the element at the other end to make room.
// - So a push_back on a full buffer will do a pop_front before storing the new element at the end.
// - So a push_front on a full buffer will do a pop_back before storing the new element at the end.
template <typename T>
class CircularFixedSizeBuffer
{
public:
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = value_type&;
using const_reference = const value_type&;
private:
std::vector<value_type> m_data;
size_type m_frontIndex{0u};
size_type m_entries{0u};
public:
explicit CircularFixedSizeBuffer(size_type count)
: m_data(count)
{
if (count <= 0u)
{
throw std::invalid_argument("count must be greater than zero");
}
}
const_reference front() const
{
// There must be at least one entry for the front call to be valid
assert(m_entries > 0u);
// Check integrity of internal values
assert(m_frontIndex < m_data.size());
assert(m_entries <= m_data.size());
return m_data[m_frontIndex];
}
reference front()
{
// There must be at least one entry for the front call to be valid
assert(m_entries > 0u);
// Check integrity of internal values
assert(m_frontIndex < m_data.size());
assert(m_entries <= m_data.size());
return m_data[m_frontIndex];
}
const_reference back() const
{
// There must be at least one entry for the back call to be valid
assert(m_entries > 0u);
// Check integrity of internal values
assert(m_frontIndex < m_data.size());
assert(m_entries <= m_data.size());
return m_data[(m_frontIndex + m_entries - 1u) % m_data.size()];
}
reference back()
{
// There must be at least one entry for the back call to be valid
assert(m_entries > 0u);
// Check integrity of internal values
assert(m_frontIndex < m_data.size());
assert(m_entries <= m_data.size());
return m_data[(m_frontIndex + m_entries - 1u) % m_data.size()];
}
reference operator[](size_type pos)
{
// There must be at least one entry for the operator call to be valid
assert(m_entries > 0u);
// pos must be a valid index
assert(pos < m_entries);
// Check integrity of internal values
assert(m_frontIndex < m_data.size());
assert(m_entries <= m_data.size());
return m_data[(m_frontIndex + pos) % m_data.size()];
}
const_reference operator[](size_type pos) const
{
// There must be at least one entry for the operator call to be valid
assert(m_entries > 0u);
// pos must be a valid index
assert(pos < m_entries);
// Check integrity of internal values
assert(m_frontIndex < m_data.size());
assert(m_entries <= m_data.size());
return m_data[(m_frontIndex + pos) % m_data.size()];
}
reference at(size_type pos)
{
if (pos >= size())
{
throw std::out_of_range("index out of bounds");
}
// Check integrity of internal values
assert(m_frontIndex < m_data.size());
assert(m_entries <= m_data.size());
return m_data.at((m_frontIndex + pos) % m_data.size());
}
const_reference at(size_type pos) const
{
if (pos >= size())
{
throw std::out_of_range("index out of bounds");
}
// Check integrity of internal values
assert(m_frontIndex < m_data.size());
assert(m_entries <= m_data.size());
return m_data.at((m_frontIndex + pos) % m_data.size());
}
bool empty() const noexcept
{
return m_entries <= 0u;
}
size_type size() const noexcept
{
return m_entries;
}
void clear() noexcept
{
while (m_entries > 0u)
{
pop_back();
}
assert(m_entries == 0u);
m_frontIndex = 0u;
}
void push_back(const value_type& value)
{
if (m_entries >= m_data.size())
{
// The buffer has reached max capacity so we pop the front element to make room for a new one at the back
pop_front();
}
assert(m_entries < m_data.size());
m_data[(m_frontIndex + m_entries) % m_data.size()] = value;
++m_entries;
assert(m_entries <= m_data.size());
}
void push_back(value_type&& value)
{
if (m_entries >= m_data.size())
{
// The buffer has reached max capacity so we pop the front element to make room for a new one at the back
pop_front();
}
assert(m_entries < m_data.size());
m_data[(m_frontIndex + m_entries) % m_data.size()] = std::move(value);
++m_entries;
assert(m_entries <= m_data.size());
}
void push_front(const value_type& value)
{
if (m_entries >= m_data.size())
{
// The buffer has reached max capacity so we pop the front element to make room for a new one at the back
pop_back();
}
assert(m_entries < m_data.size());
m_frontIndex = (m_frontIndex - 1u) % m_data.size();
m_data[m_frontIndex % m_data.size()] = value;
++m_entries;
assert(m_entries <= m_data.size());
}
void push_front(value_type&& value)
{
if (m_entries >= m_data.size())
{
// The buffer has reached max capacity so we pop the front element to make room for a new one at the back
pop_back();
}
assert(m_entries < m_data.size());
m_frontIndex = (m_frontIndex - 1u) % m_data.size();
m_data[m_frontIndex % m_data.size()] = std::move(value);
++m_entries;
assert(m_entries <= m_data.size());
}
void pop_back()
{
assert(!empty());
--m_entries;
m_data[(m_frontIndex + m_entries) % m_data.size()] = {};
assert(m_entries <= m_data.size());
}
void pop_front()
{
assert(!empty());
m_data[m_frontIndex] = {};
m_frontIndex = (m_frontIndex + 1u) % m_data.size();
--m_entries;
assert(m_frontIndex < m_data.size());
assert(m_entries <= m_data.size());
}
};
}
#endif
| 33.129921 | 150 | 0.617706 | [
"vector"
] |
cde9a59ffaedc42762da74a0aff9a4a67bf5c114 | 15,082 | cpp | C++ | gen/blink/bindings/modules/v8/V8CHROMIUMSubscribeUniform.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | 8 | 2019-05-05T16:38:05.000Z | 2021-11-09T11:45:38.000Z | gen/blink/bindings/modules/v8/V8CHROMIUMSubscribeUniform.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | null | null | null | gen/blink/bindings/modules/v8/V8CHROMIUMSubscribeUniform.cpp | gergul/MiniBlink | 7a11c52f141d54d5f8e1a9af31867cd120a2c3c4 | [
"Apache-2.0"
] | 4 | 2018-12-14T07:52:46.000Z | 2021-06-11T18:06:09.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.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#include "V8CHROMIUMSubscribeUniform.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8GCController.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/modules/v8/V8CHROMIUMValuebuffer.h"
#include "bindings/modules/v8/V8WebGLUniformLocation.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8CHROMIUMSubscribeUniform::wrapperTypeInfo = { gin::kEmbedderBlink, V8CHROMIUMSubscribeUniform::domTemplate, V8CHROMIUMSubscribeUniform::refObject, V8CHROMIUMSubscribeUniform::derefObject, V8CHROMIUMSubscribeUniform::trace, 0, V8CHROMIUMSubscribeUniform::visitDOMWrapper, V8CHROMIUMSubscribeUniform::preparePrototypeObject, V8CHROMIUMSubscribeUniform::installConditionallyEnabledProperties, "CHROMIUMSubscribeUniform", 0, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::NotInheritFromEventTarget, WrapperTypeInfo::Dependent, WrapperTypeInfo::WillBeGarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in CHROMIUMSubscribeUniform.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& CHROMIUMSubscribeUniform::s_wrapperTypeInfo = V8CHROMIUMSubscribeUniform::wrapperTypeInfo;
namespace CHROMIUMSubscribeUniformV8Internal {
static void createValuebufferCHROMIUMMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
CHROMIUMSubscribeUniform* impl = V8CHROMIUMSubscribeUniform::toImpl(info.Holder());
v8SetReturnValue(info, impl->createValuebufferCHROMIUM());
}
static void createValuebufferCHROMIUMMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
CHROMIUMSubscribeUniformV8Internal::createValuebufferCHROMIUMMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void deleteValuebufferCHROMIUMMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "deleteValuebufferCHROMIUM", "CHROMIUMSubscribeUniform", 1, info.Length()), info.GetIsolate());
return;
}
CHROMIUMSubscribeUniform* impl = V8CHROMIUMSubscribeUniform::toImpl(info.Holder());
CHROMIUMValuebuffer* buffer;
{
buffer = V8CHROMIUMValuebuffer::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!buffer && !isUndefinedOrNull(info[0])) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("deleteValuebufferCHROMIUM", "CHROMIUMSubscribeUniform", "parameter 1 is not of type 'CHROMIUMValuebuffer'."));
return;
}
}
impl->deleteValuebufferCHROMIUM(buffer);
}
static void deleteValuebufferCHROMIUMMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
CHROMIUMSubscribeUniformV8Internal::deleteValuebufferCHROMIUMMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void isValuebufferCHROMIUMMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (UNLIKELY(info.Length() < 1)) {
V8ThrowException::throwException(createMinimumArityTypeErrorForMethod(info.GetIsolate(), "isValuebufferCHROMIUM", "CHROMIUMSubscribeUniform", 1, info.Length()), info.GetIsolate());
return;
}
CHROMIUMSubscribeUniform* impl = V8CHROMIUMSubscribeUniform::toImpl(info.Holder());
CHROMIUMValuebuffer* buffer;
{
buffer = V8CHROMIUMValuebuffer::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!buffer && !isUndefinedOrNull(info[0])) {
V8ThrowException::throwTypeError(info.GetIsolate(), ExceptionMessages::failedToExecute("isValuebufferCHROMIUM", "CHROMIUMSubscribeUniform", "parameter 1 is not of type 'CHROMIUMValuebuffer'."));
return;
}
}
v8SetReturnValueBool(info, impl->isValuebufferCHROMIUM(buffer));
}
static void isValuebufferCHROMIUMMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
CHROMIUMSubscribeUniformV8Internal::isValuebufferCHROMIUMMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void bindValuebufferCHROMIUMMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "bindValuebufferCHROMIUM", "CHROMIUMSubscribeUniform", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 2)) {
setMinimumArityTypeError(exceptionState, 2, info.Length());
exceptionState.throwIfNeeded();
return;
}
CHROMIUMSubscribeUniform* impl = V8CHROMIUMSubscribeUniform::toImpl(info.Holder());
unsigned target;
CHROMIUMValuebuffer* buffer;
{
target = toUInt32(info.GetIsolate(), info[0], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
buffer = V8CHROMIUMValuebuffer::toImplWithTypeCheck(info.GetIsolate(), info[1]);
if (!buffer && !isUndefinedOrNull(info[1])) {
exceptionState.throwTypeError("parameter 2 is not of type 'CHROMIUMValuebuffer'.");
exceptionState.throwIfNeeded();
return;
}
}
impl->bindValuebufferCHROMIUM(target, buffer);
}
static void bindValuebufferCHROMIUMMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
CHROMIUMSubscribeUniformV8Internal::bindValuebufferCHROMIUMMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void subscribeValueCHROMIUMMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "subscribeValueCHROMIUM", "CHROMIUMSubscribeUniform", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 2)) {
setMinimumArityTypeError(exceptionState, 2, info.Length());
exceptionState.throwIfNeeded();
return;
}
CHROMIUMSubscribeUniform* impl = V8CHROMIUMSubscribeUniform::toImpl(info.Holder());
unsigned target;
unsigned subscriptions;
{
target = toUInt32(info.GetIsolate(), info[0], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
subscriptions = toUInt32(info.GetIsolate(), info[1], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->subscribeValueCHROMIUM(target, subscriptions);
}
static void subscribeValueCHROMIUMMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
CHROMIUMSubscribeUniformV8Internal::subscribeValueCHROMIUMMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void populateSubscribedValuesCHROMIUMMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "populateSubscribedValuesCHROMIUM", "CHROMIUMSubscribeUniform", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 1)) {
setMinimumArityTypeError(exceptionState, 1, info.Length());
exceptionState.throwIfNeeded();
return;
}
CHROMIUMSubscribeUniform* impl = V8CHROMIUMSubscribeUniform::toImpl(info.Holder());
unsigned target;
{
target = toUInt32(info.GetIsolate(), info[0], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->populateSubscribedValuesCHROMIUM(target);
}
static void populateSubscribedValuesCHROMIUMMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
CHROMIUMSubscribeUniformV8Internal::populateSubscribedValuesCHROMIUMMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void uniformValuebufferCHROMIUMMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "uniformValuebufferCHROMIUM", "CHROMIUMSubscribeUniform", info.Holder(), info.GetIsolate());
if (UNLIKELY(info.Length() < 3)) {
setMinimumArityTypeError(exceptionState, 3, info.Length());
exceptionState.throwIfNeeded();
return;
}
CHROMIUMSubscribeUniform* impl = V8CHROMIUMSubscribeUniform::toImpl(info.Holder());
WebGLUniformLocation* location;
unsigned target;
unsigned subscription;
{
location = V8WebGLUniformLocation::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!location && !isUndefinedOrNull(info[0])) {
exceptionState.throwTypeError("parameter 1 is not of type 'WebGLUniformLocation'.");
exceptionState.throwIfNeeded();
return;
}
target = toUInt32(info.GetIsolate(), info[1], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
subscription = toUInt32(info.GetIsolate(), info[2], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->uniformValuebufferCHROMIUM(location, target, subscription);
}
static void uniformValuebufferCHROMIUMMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
CHROMIUMSubscribeUniformV8Internal::uniformValuebufferCHROMIUMMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
} // namespace CHROMIUMSubscribeUniformV8Internal
void V8CHROMIUMSubscribeUniform::visitDOMWrapper(v8::Isolate* isolate, ScriptWrappable* scriptWrappable, const v8::Persistent<v8::Object>& wrapper)
{
CHROMIUMSubscribeUniform* impl = scriptWrappable->toImpl<CHROMIUMSubscribeUniform>();
// The canvas() method may return a reference or a pointer.
if (Node* owner = WTF::getPtr(impl->canvas())) {
Node* root = V8GCController::opaqueRootForGC(isolate, owner);
isolate->SetReferenceFromGroup(v8::UniqueId(reinterpret_cast<intptr_t>(root)), wrapper);
return;
}
}
static const V8DOMConfiguration::MethodConfiguration V8CHROMIUMSubscribeUniformMethods[] = {
{"createValuebufferCHROMIUM", CHROMIUMSubscribeUniformV8Internal::createValuebufferCHROMIUMMethodCallback, 0, 0, V8DOMConfiguration::ExposedToAllScripts},
{"deleteValuebufferCHROMIUM", CHROMIUMSubscribeUniformV8Internal::deleteValuebufferCHROMIUMMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts},
{"isValuebufferCHROMIUM", CHROMIUMSubscribeUniformV8Internal::isValuebufferCHROMIUMMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts},
{"bindValuebufferCHROMIUM", CHROMIUMSubscribeUniformV8Internal::bindValuebufferCHROMIUMMethodCallback, 0, 2, V8DOMConfiguration::ExposedToAllScripts},
{"subscribeValueCHROMIUM", CHROMIUMSubscribeUniformV8Internal::subscribeValueCHROMIUMMethodCallback, 0, 2, V8DOMConfiguration::ExposedToAllScripts},
{"populateSubscribedValuesCHROMIUM", CHROMIUMSubscribeUniformV8Internal::populateSubscribedValuesCHROMIUMMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts},
{"uniformValuebufferCHROMIUM", CHROMIUMSubscribeUniformV8Internal::uniformValuebufferCHROMIUMMethodCallback, 0, 3, V8DOMConfiguration::ExposedToAllScripts},
};
static void installV8CHROMIUMSubscribeUniformTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "CHROMIUMSubscribeUniform", v8::Local<v8::FunctionTemplate>(), V8CHROMIUMSubscribeUniform::internalFieldCount,
0, 0,
0, 0,
V8CHROMIUMSubscribeUniformMethods, WTF_ARRAY_LENGTH(V8CHROMIUMSubscribeUniformMethods));
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
static const V8DOMConfiguration::ConstantConfiguration V8CHROMIUMSubscribeUniformConstants[] = {
{"SUBSCRIBED_VALUES_BUFFER_CHROMIUM", 0x924B, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedLong},
{"MOUSE_POSITION_CHROMIUM", 0x924C, 0, 0, V8DOMConfiguration::ConstantTypeUnsignedLong},
};
V8DOMConfiguration::installConstants(isolate, functionTemplate, prototypeTemplate, V8CHROMIUMSubscribeUniformConstants, WTF_ARRAY_LENGTH(V8CHROMIUMSubscribeUniformConstants));
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8CHROMIUMSubscribeUniform::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8CHROMIUMSubscribeUniformTemplate);
}
bool V8CHROMIUMSubscribeUniform::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8CHROMIUMSubscribeUniform::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
CHROMIUMSubscribeUniform* V8CHROMIUMSubscribeUniform::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8CHROMIUMSubscribeUniform::refObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<CHROMIUMSubscribeUniform>()->ref();
#endif
}
void V8CHROMIUMSubscribeUniform::derefObject(ScriptWrappable* scriptWrappable)
{
#if !ENABLE(OILPAN)
scriptWrappable->toImpl<CHROMIUMSubscribeUniform>()->deref();
#endif
}
} // namespace blink
| 48.651613 | 642 | 0.767405 | [
"object"
] |
cdee485a8d18596e0184d5114905d6e5d34cefff | 1,583 | hpp | C++ | Particle.hpp | tylerc/Ignatus | 7ceb806554f5af4afa5b22af65bc8249071cfc50 | [
"Unlicense"
] | 1 | 2019-08-13T07:09:47.000Z | 2019-08-13T07:09:47.000Z | Particle.hpp | tylerc/Ignatus | 7ceb806554f5af4afa5b22af65bc8249071cfc50 | [
"Unlicense"
] | null | null | null | Particle.hpp | tylerc/Ignatus | 7ceb806554f5af4afa5b22af65bc8249071cfc50 | [
"Unlicense"
] | null | null | null | #ifndef PARTICLE_HPP
#define PARTICLE_HPP
namespace Ignatus{
class Particle: public virtual AniObject{
public:
bool Loop;
int Slife;
bool Decay;
bool Fade;
sf::Color Stint;
sf::Color Etint;
sf::Color Mtint;
float Friction;
float Turn;
float Wiggle;
float Acceleration;
Pointf Gravity;
struct DNA{
std::string Img;
Pointf Position;
Pointf Velocity;
bool World;
Pointi Dimensions;
int FPS;
bool Loop;
int Slife;
bool Decay;
bool Fade;
sf::Color Stint;
sf::Color Etint;
sf::Color Mtint;
float Friction;
float Turn;
float Wiggle;
float Acceleration;
Pointf Gravity;
DNA(std::string img,Point<float> xy,Point<int> dim,int fps,Point<float> vel,sf::Color stint,sf::Color etint,float fric,float turn,float wiggle,bool loop=true,bool World=true);
};
Particle(std::string img,Point<float> xy,Point<int> dim,int fps,Point<float> vel,sf::Color stint,sf::Color etint,float fric,float turn,float wiggle,bool loop=true,bool World=true);
Particle(Particle::DNA dna);
static void CreateShape(Particle::DNA dna,std::vector<Pointf> pos,bool Align=false);
static void Explosion(int num,Pointf range,Particle::DNA dna,bool even=false);
static void Ring(int num,Pointf range,Particle::DNA dna,bool even=false);
virtual ~Particle();
void Update();
static int Part_Count;
private:
};
}
#endif // PARTICLE_HPP
| 28.781818 | 185 | 0.625395 | [
"vector"
] |
cdf0078f3729543ae212ab284c8e0e542c314821 | 7,545 | cpp | C++ | rootex/vendor/Effekseer/effekseer/src/EffekseerRendererDX11/EffekseerRenderer/EffekseerRendererDX11.ModelRenderer.cpp | ChronicallySerious/Rootex | bf2a0997b6aa5be84dbfc0e7826c31ff693ca0f1 | [
"MIT"
] | 166 | 2019-06-19T19:51:45.000Z | 2022-03-24T13:03:29.000Z | rootex/vendor/Effekseer/effekseer/src/EffekseerRendererDX11/EffekseerRenderer/EffekseerRendererDX11.ModelRenderer.cpp | rahil627/Rootex | 44f827d469bddc7167b34dedf80d7a8b984fdf20 | [
"MIT"
] | 312 | 2019-06-13T19:39:25.000Z | 2022-03-02T18:37:22.000Z | rootex/vendor/Effekseer/effekseer/src/EffekseerRendererDX11/EffekseerRenderer/EffekseerRendererDX11.ModelRenderer.cpp | rahil627/Rootex | 44f827d469bddc7167b34dedf80d7a8b984fdf20 | [
"MIT"
] | 23 | 2019-10-04T11:02:21.000Z | 2021-12-24T16:34:52.000Z |
//----------------------------------------------------------------------------------
// Include
//----------------------------------------------------------------------------------
#include "EffekseerRendererDX11.RenderState.h"
#include "EffekseerRendererDX11.RendererImplemented.h"
#include "EffekseerRendererDX11.IndexBuffer.h"
#include "EffekseerRendererDX11.ModelRenderer.h"
#include "EffekseerRendererDX11.Shader.h"
#include "EffekseerRendererDX11.VertexBuffer.h"
namespace EffekseerRendererDX11
{
#ifdef __EFFEKSEER_BUILD_VERSION16__
namespace ShaderLightingTextureNormal_
{
static
#include "Shader/EffekseerRenderer.ModelRenderer.ShaderLightingTextureNormal_VS.h"
static
#include "Shader/EffekseerRenderer.ModelRenderer.ShaderLightingTextureNormal_PS.h"
} // namespace ShaderLightingTextureNormal_
namespace ShaderTexture_
{
static
#include "Shader/EffekseerRenderer.ModelRenderer.ShaderTexture_VS.h"
static
#include "Shader/EffekseerRenderer.ModelRenderer.ShaderTexture_PS.h"
} // namespace ShaderTexture_
namespace ShaderDistortionTexture_
{
static
#include "Shader/EffekseerRenderer.ModelRenderer.ShaderDistortion_VS.h"
static
#include "Shader/EffekseerRenderer.ModelRenderer.ShaderDistortionTexture_PS.h"
} // namespace ShaderDistortionTexture_
#else
namespace ShaderLightingTextureNormal_
{
static
#include "Shader_15/EffekseerRenderer.ModelRenderer.ShaderLightingTextureNormal_VS.h"
static
#include "Shader_15/EffekseerRenderer.ModelRenderer.ShaderLightingTextureNormal_PS.h"
} // namespace ShaderLightingTextureNormal_
namespace ShaderTexture_
{
static
#include "Shader_15/EffekseerRenderer.ModelRenderer.ShaderTexture_VS.h"
static
#include "Shader_15/EffekseerRenderer.ModelRenderer.ShaderTexture_PS.h"
} // namespace ShaderTexture_
namespace ShaderDistortionTexture_
{
static
#include "Shader_15/EffekseerRenderer.ModelRenderer.ShaderDistortion_VS.h"
static
#include "Shader_15/EffekseerRenderer.ModelRenderer.ShaderDistortionTexture_PS.h"
} // namespace ShaderDistortionTexture_
#endif
ModelRenderer::ModelRenderer(
RendererImplemented* renderer,
Shader* shader_lighting_texture_normal,
Shader* shader_texture,
Shader* shader_distortion_texture)
: m_renderer(renderer)
, m_shader_lighting_texture_normal(shader_lighting_texture_normal)
, m_shader_texture(shader_texture)
, m_shader_distortion_texture(shader_distortion_texture)
{
Shader* shaders[2];
shaders[0] = m_shader_lighting_texture_normal;
shaders[1] = m_shader_texture;
for (int32_t i = 0; i < 2; i++)
{
shaders[i]->SetVertexConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererVertexConstantBuffer<40>));
shaders[i]->SetVertexRegisterCount(sizeof(::EffekseerRenderer::ModelRendererVertexConstantBuffer<40>) / (sizeof(float) * 4));
shaders[i]->SetPixelConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererPixelConstantBuffer));
shaders[i]->SetPixelRegisterCount(sizeof(::EffekseerRenderer::ModelRendererPixelConstantBuffer) / (sizeof(float) * 4));
}
m_shader_distortion_texture->SetVertexConstantBufferSize(sizeof(::EffekseerRenderer::ModelRendererVertexConstantBuffer<40>));
m_shader_distortion_texture->SetVertexRegisterCount(sizeof(::EffekseerRenderer::ModelRendererVertexConstantBuffer<40>) / (sizeof(float) * 4));
#ifdef __EFFEKSEER_BUILD_VERSION16__
m_shader_distortion_texture->SetPixelConstantBufferSize(sizeof(float) * 4 + sizeof(float) * 4 + sizeof(float) * 4);
m_shader_distortion_texture->SetPixelRegisterCount(1 + 1 + 1);
#else
m_shader_distortion_texture->SetPixelConstantBufferSize(sizeof(float) * 4 + sizeof(float) * 4);
m_shader_distortion_texture->SetPixelRegisterCount(1 + 1);
#endif
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
ModelRenderer::~ModelRenderer()
{
ES_SAFE_DELETE(m_shader_lighting_texture_normal);
ES_SAFE_DELETE(m_shader_texture);
ES_SAFE_DELETE(m_shader_distortion_texture);
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
ModelRenderer* ModelRenderer::Create(RendererImplemented* renderer)
{
assert(renderer != NULL);
assert(renderer->GetDevice() != NULL);
// 座標(3) 法線(3)*3 UV(2)
D3D11_INPUT_ELEMENT_DESC decl[] = {
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(float) * 3, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"NORMAL", 1, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(float) * 6, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"NORMAL", 2, DXGI_FORMAT_R32G32B32_FLOAT, 0, sizeof(float) * 9, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, sizeof(float) * 12, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"NORMAL", 3, DXGI_FORMAT_R8G8B8A8_UNORM, 0, sizeof(float) * 14, D3D11_INPUT_PER_VERTEX_DATA, 0},
{"BLENDINDICES", 0, DXGI_FORMAT_R8G8B8A8_UINT, 0, sizeof(float) * 15, D3D11_INPUT_PER_VERTEX_DATA, 0},
};
Shader* shader_lighting_texture_normal = Shader::Create(
renderer,
ShaderLightingTextureNormal_::g_VS,
sizeof(ShaderLightingTextureNormal_::g_VS),
ShaderLightingTextureNormal_::g_PS,
sizeof(ShaderLightingTextureNormal_::g_PS),
"ModelRendererLightingTextureNormal",
decl,
ARRAYSIZE(decl));
Shader* shader_texture = Shader::Create(
renderer,
ShaderTexture_::g_VS,
sizeof(ShaderTexture_::g_VS),
ShaderTexture_::g_PS,
sizeof(ShaderTexture_::g_PS),
"ModelRendererTexture",
decl,
ARRAYSIZE(decl));
auto shader_distortion_texture = Shader::Create(
renderer,
ShaderDistortionTexture_::g_VS,
sizeof(ShaderDistortionTexture_::g_VS),
ShaderDistortionTexture_::g_PS,
sizeof(ShaderDistortionTexture_::g_PS),
"ModelRendererDistortionTexture",
decl,
ARRAYSIZE(decl));
if (shader_lighting_texture_normal == NULL ||
shader_texture == NULL ||
shader_distortion_texture == NULL)
{
ES_SAFE_DELETE(shader_lighting_texture_normal);
ES_SAFE_DELETE(shader_texture);
ES_SAFE_DELETE(shader_distortion_texture);
}
return new ModelRenderer(renderer,
shader_lighting_texture_normal,
shader_texture,
shader_distortion_texture);
}
void ModelRenderer::BeginRendering(const efkModelNodeParam& parameter, int32_t count, void* userData)
{
BeginRendering_(m_renderer, parameter, count, userData);
}
void ModelRenderer::Rendering(const efkModelNodeParam& parameter, const InstanceParameter& instanceParameter, void* userData)
{
Rendering_<
RendererImplemented>(
m_renderer,
parameter,
instanceParameter,
userData);
}
void ModelRenderer::EndRendering(const efkModelNodeParam& parameter, void* userData)
{
if (parameter.ModelIndex < 0)
{
return;
}
auto model = (Model*)parameter.EffectPointer->GetModel(parameter.ModelIndex);
if (model == nullptr)
{
return;
}
model->LoadToGPU();
if (!model->IsLoadedOnGPU)
{
return;
}
EndRendering_<
RendererImplemented,
Shader,
Model,
true,
40>(
m_renderer,
m_shader_lighting_texture_normal,
m_shader_texture,
m_shader_distortion_texture,
parameter);
}
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
} // namespace EffekseerRendererDX11
//----------------------------------------------------------------------------------
//
//----------------------------------------------------------------------------------
| 31.569038 | 143 | 0.707886 | [
"model"
] |
cdf05c8d6e269fd9eaf5950643b7d786ad027552 | 12,657 | cxx | C++ | ds/adsi/nds/odssz.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | ds/adsi/nds/odssz.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | ds/adsi/nds/odssz.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+---------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 1995.
//
// File: ods2nds.cxx
//
// Contents: NDS Object to Variant Copy Routines
//
// Functions:
//
// History: 25-Apr-96 KrishnaG Created.
//
//
//
//----------------------------------------------------------------------------
#include "nds.hxx"
DWORD
AdsTypeDNStringSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_DN_STRING){
return(0);
}
dwSize = (wcslen(lpAdsSrcValue->DNString) + 1)*sizeof(WCHAR);
return(dwSize);
}
DWORD
AdsTypeCaseExactStringSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_CASE_EXACT_STRING){
return(0);
}
dwSize = (wcslen(lpAdsSrcValue->CaseExactString) + 1) *sizeof(WCHAR);
return(dwSize);
}
DWORD
AdsTypeCaseIgnoreStringSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_CASE_IGNORE_STRING){
return(0);
}
dwSize = (wcslen(lpAdsSrcValue->CaseIgnoreString) + 1) *sizeof(WCHAR);
return(dwSize);
}
DWORD
AdsTypePrintableStringSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_PRINTABLE_STRING){
return(0);
}
dwSize = (wcslen(lpAdsSrcValue->PrintableString) + 1) *sizeof(WCHAR);
return(dwSize);
}
DWORD
AdsTypeNumericStringSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_NUMERIC_STRING){
return(0);
}
dwSize = (wcslen(lpAdsSrcValue->NumericString) + 1)* sizeof(WCHAR);
return(dwSize);
}
DWORD
AdsTypeBooleanSize(
PADSVALUE lpAdsSrcValue
)
{
if(lpAdsSrcValue->dwType != ADSTYPE_BOOLEAN){
return(0);
}
return(0);
}
DWORD
AdsTypeIntegerSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_INTEGER){
return(0);
}
return(0);
}
DWORD
AdsTypeOctetStringSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwNumBytes = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_OCTET_STRING){
return(0);
}
dwNumBytes = lpAdsSrcValue->OctetString.dwLength;
return(dwNumBytes);
}
DWORD
AdsTypeTimeSize(
PADSVALUE lpAdsSrcValue
)
{
if(lpAdsSrcValue->dwType != ADSTYPE_UTC_TIME){
return(0);
}
return(0);
}
DWORD
AdsTypeObjectClassSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_OBJECT_CLASS){
return(0);
}
dwSize = (wcslen(lpAdsSrcValue->ClassName) + 1)*sizeof(WCHAR);
return(dwSize);
}
DWORD
AdsTypeCaseIgnoreListSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwLength = 0;
PADS_CASEIGNORE_LIST pAdsNext = lpAdsSrcValue->pCaseIgnoreList;
if(lpAdsSrcValue->dwType != ADSTYPE_CASEIGNORE_LIST){
return(0);
}
if (lpAdsSrcValue->pCaseIgnoreList == NULL) {
return(0);
}
dwSize += sizeof(ADS_CASEIGNORE_LIST);
dwLength = (wcslen(pAdsNext->String) + 1)*sizeof(WCHAR);
dwSize += dwLength;
pAdsNext = pAdsNext->Next;
while (pAdsNext) {
dwSize += sizeof(ADS_CASEIGNORE_LIST);
dwLength = (wcslen(pAdsNext->String) + 1)*sizeof(WCHAR);
dwSize += dwLength;
pAdsNext = pAdsNext->Next;
}
return(dwSize);
}
DWORD
AdsTypeOctetListSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwNumBytes = 0;
DWORD dwLength = 0;
PADS_OCTET_LIST pAdsNext = lpAdsSrcValue->pOctetList;
if(lpAdsSrcValue->dwType != ADSTYPE_OCTET_LIST){
return(0);
}
if (lpAdsSrcValue->pOctetList == NULL) {
return(0);
}
dwSize += sizeof(ADS_OCTET_LIST);
dwNumBytes = pAdsNext->Length;
dwSize += dwNumBytes;
pAdsNext = pAdsNext->Next;
while (pAdsNext) {
dwSize += sizeof(ADS_OCTET_LIST);
dwNumBytes = pAdsNext->Length;
dwSize += dwNumBytes;
pAdsNext = pAdsNext->Next;
}
return(dwSize);
}
DWORD
AdsTypePathSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwLength = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_PATH){
return(0);
}
if (lpAdsSrcValue->pPath == NULL) {
return(0);
}
dwSize += sizeof(ADS_PATH);
dwLength = (wcslen(lpAdsSrcValue->pPath->VolumeName) + 1)*sizeof(WCHAR);
dwSize += dwLength;
dwLength = (wcslen(lpAdsSrcValue->pPath->Path) + 1)*sizeof(WCHAR);
dwSize += dwLength;
return(dwSize);
}
DWORD
AdsTypePostalAddressSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwLength = 0;
long i;
if(lpAdsSrcValue->dwType != ADSTYPE_POSTALADDRESS){
return(0);
}
if (lpAdsSrcValue->pPostalAddress == NULL) {
return(0);
}
dwSize += sizeof(ADS_POSTALADDRESS);
for (i=0;i<6;i++) {
if (lpAdsSrcValue->pPostalAddress->PostalAddress[i]) {
dwLength = (wcslen(lpAdsSrcValue->pPostalAddress->PostalAddress[i]) + 1)*sizeof(WCHAR);
dwSize += dwLength;
}
else {
dwSize += sizeof(WCHAR);
}
}
return(dwSize);
}
DWORD
AdsTypeTimestampSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_TIMESTAMP){
return(0);
}
return(dwSize);
}
DWORD
AdsTypeBackLinkSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwLength = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_BACKLINK){
return(0);
}
dwLength = (wcslen(lpAdsSrcValue->BackLink.ObjectName) + 1)*sizeof(WCHAR);
dwSize += dwLength;
return(dwSize);
}
DWORD
AdsTypeTypedNameSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwLength = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_TYPEDNAME){
return(0);
}
if (lpAdsSrcValue->pTypedName == NULL) {
return(0);
}
dwSize += sizeof(ADS_TYPEDNAME);
dwLength = (wcslen(lpAdsSrcValue->pTypedName->ObjectName) + 1)*sizeof(WCHAR);
dwSize += dwLength;
return(dwSize);
}
DWORD
AdsTypeHoldSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwLength = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_HOLD){
return(0);
}
dwLength = (wcslen(lpAdsSrcValue->Hold.ObjectName) + 1)*sizeof(WCHAR);
dwSize += dwLength;
return(dwSize);
}
DWORD
AdsTypeEmailSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwLength = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_EMAIL){
return(0);
}
dwLength = (wcslen(lpAdsSrcValue->Email.Address) + 1)*sizeof(WCHAR);
dwSize += dwLength;
return(dwSize);
}
DWORD
AdsTypeNetAddressSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwNumBytes = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_NETADDRESS){
return(0);
}
if (lpAdsSrcValue->pNetAddress == NULL) {
return(0);
}
dwSize += sizeof(ADS_NETADDRESS);
dwNumBytes = lpAdsSrcValue->pNetAddress->AddressLength;
dwSize += dwNumBytes;
return(dwSize);
}
DWORD
AdsTypeFaxNumberSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwNumBytes = 0;
DWORD dwLength = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_FAXNUMBER){
return(0);
}
if (lpAdsSrcValue->pFaxNumber == NULL) {
return(0);
}
dwSize += sizeof(ADS_FAXNUMBER);
dwLength = (wcslen(lpAdsSrcValue->pFaxNumber->TelephoneNumber) + 1)*sizeof(WCHAR);
dwSize += dwLength;
dwNumBytes = lpAdsSrcValue->pFaxNumber->NumberOfBits;
dwSize += dwNumBytes;
return(dwSize);
}
DWORD
AdsTypeReplicaPointerSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
DWORD dwNumBytes = 0;
DWORD dwLength = 0;
if(lpAdsSrcValue->dwType != ADSTYPE_REPLICAPOINTER){
return(0);
}
if (lpAdsSrcValue->pReplicaPointer == NULL) {
return(0);
}
dwSize += sizeof(ADS_REPLICAPOINTER);
dwLength = (wcslen(lpAdsSrcValue->pReplicaPointer->ServerName) + 1)*sizeof(WCHAR);
dwSize += dwLength;
dwSize += sizeof(ADS_NETADDRESS);
dwNumBytes = lpAdsSrcValue->pReplicaPointer->ReplicaAddressHints->AddressLength;
dwSize += dwNumBytes;
return(dwSize);
}
DWORD
AdsTypeSize(
PADSVALUE lpAdsSrcValue
)
{
DWORD dwSize = 0;
switch (lpAdsSrcValue->dwType){
case ADSTYPE_DN_STRING:
dwSize = AdsTypeDNStringSize(
lpAdsSrcValue
);
break;
case ADSTYPE_CASE_EXACT_STRING:
dwSize = AdsTypeCaseExactStringSize(
lpAdsSrcValue
);
break;
case ADSTYPE_CASE_IGNORE_STRING:
dwSize = AdsTypeCaseIgnoreStringSize(
lpAdsSrcValue
);
break;
case ADSTYPE_PRINTABLE_STRING:
dwSize = AdsTypePrintableStringSize(
lpAdsSrcValue
);
break;
case ADSTYPE_NUMERIC_STRING:
dwSize = AdsTypeNumericStringSize(
lpAdsSrcValue
);
break;
case ADSTYPE_BOOLEAN:
dwSize = AdsTypeBooleanSize(
lpAdsSrcValue
);
break;
case ADSTYPE_INTEGER:
dwSize = AdsTypeIntegerSize(
lpAdsSrcValue
);
break;
case ADSTYPE_OCTET_STRING:
dwSize = AdsTypeOctetStringSize(
lpAdsSrcValue
);
break;
case ADSTYPE_UTC_TIME:
dwSize = AdsTypeTimeSize(
lpAdsSrcValue
);
break;
case ADSTYPE_OBJECT_CLASS:
dwSize = AdsTypeObjectClassSize(
lpAdsSrcValue
);
break;
case ADSTYPE_CASEIGNORE_LIST:
dwSize = AdsTypeCaseIgnoreListSize(
lpAdsSrcValue
);
break;
case ADSTYPE_FAXNUMBER:
dwSize = AdsTypeFaxNumberSize(
lpAdsSrcValue
);
break;
case ADSTYPE_NETADDRESS:
dwSize = AdsTypeNetAddressSize(
lpAdsSrcValue
);
break;
case ADSTYPE_OCTET_LIST:
dwSize = AdsTypeOctetListSize(
lpAdsSrcValue
);
break;
case ADSTYPE_EMAIL:
dwSize = AdsTypeEmailSize(
lpAdsSrcValue
);
break;
case ADSTYPE_PATH:
dwSize = AdsTypePathSize(
lpAdsSrcValue
);
break;
case ADSTYPE_REPLICAPOINTER:
dwSize = AdsTypeReplicaPointerSize(
lpAdsSrcValue
);
break;
case ADSTYPE_TIMESTAMP:
dwSize = AdsTypeTimestampSize(
lpAdsSrcValue
);
break;
case ADSTYPE_POSTALADDRESS:
dwSize = AdsTypePostalAddressSize(
lpAdsSrcValue
);
break;
case ADSTYPE_BACKLINK:
dwSize = AdsTypeBackLinkSize(
lpAdsSrcValue
);
break;
case ADSTYPE_TYPEDNAME:
dwSize = AdsTypeTypedNameSize(
lpAdsSrcValue
);
break;
case ADSTYPE_HOLD:
dwSize = AdsTypeHoldSize(
lpAdsSrcValue
);
default:
break;
}
return(dwSize);
}
| 19.714953 | 100 | 0.534329 | [
"object"
] |
cdf284dfea815c9997411a8ce62e2b1909716921 | 766 | cpp | C++ | codeforces/1453B.cpp | sgrade/cpptest | 84ade6ec03ea394d4a4489c7559d12b4799c0b62 | [
"MIT"
] | null | null | null | codeforces/1453B.cpp | sgrade/cpptest | 84ade6ec03ea394d4a4489c7559d12b4799c0b62 | [
"MIT"
] | null | null | null | codeforces/1453B.cpp | sgrade/cpptest | 84ade6ec03ea394d4a4489c7559d12b4799c0b62 | [
"MIT"
] | null | null | null | // B. Suffix Operations
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;
using ll = long long;
int main(){
int t;
cin >> t;
while(t--){
ll n;
cin >> n;
vector<ll> a(n);
for (auto &el: a) cin >> el;
// Editorial - https://codeforces.com/blog/entry/85288
ll ans = 0;
for (int i = 1; i < n; ++i) ans += abs(a[i] - a[i-1]);
// Corner cases
ll mx = max(abs(a[0] - a[1]), abs(a[n-2] - a[n-1]));
// The rest
for (int i = 1; i < n-1; ++i){
mx = max(mx, abs(a[i] - a[i-1]) + abs(a[i] - a[i+1]) - abs(a[i-1] - a[i+1]));
}
ans -= mx;
cout << ans << endl;
}
return 0;
}
| 17.409091 | 89 | 0.439948 | [
"vector"
] |
cdf2ae73087a983d8e707238adc75f4c63d96386 | 1,324 | cpp | C++ | DSA/Trees/validate-bst.cpp | abhisheknaiidu/dsa | fe3f54df6802d2520142992b541602ce5ee24f26 | [
"MIT"
] | 54 | 2020-07-31T14:50:23.000Z | 2022-03-14T11:03:02.000Z | DSA/Trees/validate-bst.cpp | abhisheknaiidu/NOOB | fe3f54df6802d2520142992b541602ce5ee24f26 | [
"MIT"
] | null | null | null | DSA/Trees/validate-bst.cpp | abhisheknaiidu/NOOB | fe3f54df6802d2520142992b541602ce5ee24f26 | [
"MIT"
] | 30 | 2020-08-15T17:39:02.000Z | 2022-03-10T06:50:18.000Z | #pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
struct Node {
int data;
Node* left;
Node* right;
};
// utility fxn
Node* newNode(int n) {
Node* temp = new Node;
temp->data = n;
temp->left = temp->right = NULL;
return(temp);
}
bool validateBST(Node* root) {
stack <Node*> s;
Node* prev = NULL, *cur = root;
while(cur || !s.empty()) {
while(cur) {
s.push(cur);
cur = cur->left;
}
cur = s.top();
s.pop();
if(prev != NULL && prev->data >= cur->data) return false;
prev = cur;
cur = cur->right;
}
return true;
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
Node* root = newNode(5);
root->left = newNode(1);
root->right = newNode(7);
root->left->left = newNode(-1);
root->left->right = newNode(2);
root->right->left = newNode(6);
root->right->right = newNode(8);
cout << validateBST(root) << endl;
return 0;
} | 17.891892 | 62 | 0.622356 | [
"vector"
] |
cdf69a3f8de29ea7b56d407d449bc78312805950 | 6,656 | cpp | C++ | src/Plugins/OpenGL/Shader/GLGPUProgram.cpp | MemoryDealer/LORE | 2ce0c6cf03c119e5d1b0b90f3ee044901353283a | [
"MIT"
] | 2 | 2021-07-14T06:05:48.000Z | 2021-07-14T18:07:18.000Z | src/Plugins/OpenGL/Shader/GLGPUProgram.cpp | MemoryDealer/LORE | 2ce0c6cf03c119e5d1b0b90f3ee044901353283a | [
"MIT"
] | null | null | null | src/Plugins/OpenGL/Shader/GLGPUProgram.cpp | MemoryDealer/LORE | 2ce0c6cf03c119e5d1b0b90f3ee044901353283a | [
"MIT"
] | null | null | null | // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
// The MIT License (MIT)
// This source file is part of LORE
// ( Lightweight Object-oriented Rendering Engine )
//
// Copyright (c) 2017-2021 Jordan Sparks
//
// 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 "GLGPUProgram.h"
#include <LORE/Scene/Light.h>
#include <LORE/Shader/Shader.h>
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
using namespace Lore::OpenGL;
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
GLGPUProgram::GLGPUProgram()
: Lore::GPUProgram()
, _program( 0 )
, _uniforms()
, _transform( 0 )
{
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
GLGPUProgram::~GLGPUProgram()
{
glDeleteProgram( _program );
_uniforms.clear();
_transform = 0;
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::init()
{
_program = glCreateProgram();
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::attachShader( Lore::ShaderPtr shader )
{
if ( !shader->isLoaded() ) {
LogWrite( Error, "Shader not loaded, not attaching to GPUProgram %s", _name.c_str() );
return;
}
Lore::GPUProgram::attachShader( shader );
GLuint id = shader->getUintId(); // TODO: Use getData("", &voidptr);
glAttachShader( _program, id );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
bool GLGPUProgram::link()
{
glLinkProgram( _program );
GLint success = 0;
GLchar buf[512];
glGetProgramiv( _program, GL_LINK_STATUS, &success );
if ( !success ) {
glGetProgramInfoLog( _program, sizeof( buf ), nullptr, buf );
LogWrite( Error, "Failed to link program %s (%s): %s", _name.c_str(), glGetError(), buf );
return false;
}
// Can delete shader buffers (or flag them for delete in GL) now that the program is linked.
for ( auto pair : _shaders ) {
ShaderPtr shader = pair.second;
shader->unload();
}
return true;
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::use()
{
glUseProgram( _program );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::addTransformVar( const string& id )
{
_transform = glGetUniformLocation( _program, id.c_str() );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::setTransformVar( const glm::mat4& m )
{
_updateUniform( _transform, m );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::addUniformVar( const string& id )
{
GLuint uniform = glGetUniformLocation( _program, id.c_str() );
_uniforms.insert( { id, uniform } );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::setUniformVar( const string& id, const glm::mat4& m )
{
auto uniform = _getUniform( id );
if ( -1 != uniform ) {
_updateUniform( uniform, m );
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::setUniformVar( const string& id, const glm::vec2& v )
{
auto uniform = _getUniform( id );
if ( -1 != uniform ) {
glUniform2fv( uniform, 1, glm::value_ptr( v ) );
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::setUniformVar( const string& id, const glm::vec3& v )
{
auto uniform = _getUniform( id );
if ( -1 != uniform ) {
glUniform3fv( uniform, 1, glm::value_ptr( v ) );
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::setUniformVar( const string& id, const glm::vec4& v )
{
auto uniform = _getUniform( id );
if ( -1 != uniform ) {
glUniform4fv( uniform, 1, glm::value_ptr( v ) );
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::setUniformVar( const string& id, const real r )
{
auto uniform = _getUniform( id );
if ( -1 != uniform ) {
glUniform1f( uniform, static_cast< GLfloat >( r ) );
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::setUniformVar( const string& id, const uint32_t i )
{
auto uniform = _getUniform( id );
if ( -1 != uniform ) {
glUniform1ui( uniform, static_cast< GLuint >( i ) );
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::setUniformVar( const string& id, const int i )
{
auto uniform = _getUniform( id );
if ( -1 != uniform ) {
glUniform1i( uniform, static_cast<GLint>( i ) );
}
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
GLuint GLGPUProgram::_getUniform( const string& id )
{
auto lookup = _uniforms.find( id );
if ( _uniforms.end() == lookup ) {
LogWrite( Warning, "Tried to get uniform %s in %s which does not exist", id.c_str(), _name.c_str() );
return -1;
}
// Return uniform GLuint value.
return lookup->second;
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
void GLGPUProgram::_updateUniform( const GLint id, const glm::mat4& m )
{
glUniformMatrix4fv( id, 1, GL_FALSE, glm::value_ptr( m ) );
}
// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //
| 29.847534 | 105 | 0.491587 | [
"object"
] |
cdfa4cfa4d5cefc95bc30306722eaf7fc1018eae | 1,448 | cpp | C++ | Codeforces/Airport.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 1 | 2018-08-28T19:58:40.000Z | 2018-08-28T19:58:40.000Z | Codeforces/Airport.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 2 | 2017-04-16T00:48:05.000Z | 2017-08-03T20:12:26.000Z | Codeforces/Airport.cpp | aajjbb/contest-files | b8842681b96017063a7baeac52ae1318bf59d74d | [
"Apache-2.0"
] | 4 | 2016-03-04T19:42:00.000Z | 2018-01-08T11:42:00.000Z | #include <iostream>
#include <fstream>
#include <vector>
#include <list>
#include <deque>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
#include <algorithm>
#include <utility>
#include <functional>
#include <valarray>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <limits.h>
using namespace std;
#define REP(i, n) for(i = 0; i < (n); i++)
#define FOR(i, a, n) for(i = a; i < n; i++)
#define REV(i, a, n) for(i = a; i > n; i--)
template<typename T> T gcd(T a, T b) {
if(!b) return a;
return gcd(b, a % b);
}
template<typename T> T lcm(T a, T b) {
return a * b / gcd(a, b);
}
typedef long long ll;
typedef long double ld;
int i, tmp, n, m, a, b;
priority_queue<int, vector<int>, greater<int> > high;
priority_queue<int, vector<int>, less<int> > low;
int main(void) {
scanf("%d%d", &n, &m);
REP(i, m) {
scanf("%d", &tmp);
high.push(tmp);
low.push(tmp);
}
a = b = 0;
tmp = n;
while(tmp > 0) {
int mx = low.top(); low.pop();
a += mx; mx -= 1; tmp -= 1;
if(mx > 0) low.push(mx);
}
tmp = n;
while(tmp > 0) {
int mx = high.top(); high.pop();
b += mx; mx -= 1; tmp -= 1;
if(mx > 0) high.push(mx);
}
printf("%d %d\n", a, b);
return 0;
}
| 20.985507 | 54 | 0.515884 | [
"vector"
] |
cdfaf9d9cae2e1e698c28a1728b443f3a9d2c844 | 1,439 | hpp | C++ | firmware/shared.hpp | ross2718/breath-controller | 8870dc040734bd63dc26341e27b129c5e1246507 | [
"CC0-1.0"
] | 3 | 2020-11-29T15:42:03.000Z | 2022-03-18T22:43:23.000Z | firmware/shared.hpp | ross2718/breath-controller | 8870dc040734bd63dc26341e27b129c5e1246507 | [
"CC0-1.0"
] | null | null | null | firmware/shared.hpp | ross2718/breath-controller | 8870dc040734bd63dc26341e27b129c5e1246507 | [
"CC0-1.0"
] | null | null | null | /*
* Stuff for working with shared and volatile objects
*
* Shared object is an object that is shared across different threads of
* execution. Such an object (if is not a constant) should be accessed in an
* exclusive way. Note that 'volatile' keyword of C/C++ have nothing to do with
* exclusive access.
*
* Volatile object is an object that is accessed with side effects (for example,
* memory mapped I/O). Accesses to volatile objects should not be reordered or
* optimized out. 'volatile' keyword is the standard C/C++ tool to guarantee
* that, but it works by suppressing optimization, which is almost never we
* actually want. So usually it's better to not use 'volatile' keyword at all,
* but use explicit memory barriers instead.
*/
#ifndef SHARED_HPP_
#define SHARED_HPP_
#ifdef __AVR_ARCH__
# include <util/atomic.h>
# define atomic_block ATOMIC_BLOCK(ATOMIC_RESTORESTATE)
#else
# error "Only AVR is supported"
#endif
inline void memory_barrier() {
asm volatile ("" ::: "memory");
}
template<typename T>
inline T atomic_read(const T &x) {
if (sizeof(x) == 1)
return x;
else {
T t;
atomic_block { t = x; }
return t;
}
}
template<typename T>
inline void atomic_write(T &x, decltype(T{}) val) {
if (sizeof(x) == 1)
x = val;
else
atomic_block { x = val; }
}
#endif
| 28.215686 | 80 | 0.648367 | [
"object"
] |
cdfb81716396f1828f5a25a6697628ce6e282fd9 | 1,571 | cc | C++ | gen_circulant.cc | josefcibulka/book-embedder | 746093a97b388ea38226631eb36ded8fe48155e9 | [
"MIT"
] | null | null | null | gen_circulant.cc | josefcibulka/book-embedder | 746093a97b388ea38226631eb36ded8fe48155e9 | [
"MIT"
] | null | null | null | gen_circulant.cc | josefcibulka/book-embedder | 746093a97b388ea38226631eb36ded8fe48155e9 | [
"MIT"
] | null | null | null | /**
* This program generates circulant graphs for use by book-embedder.
*
* Program for minimizing the number of crossings in a book embedding of a given
* graph to a given number of pages.
*
* Author: Josef Cibulka
* License: see the file LICENSE
*/
#include <cstdio>
#include <cstdlib>
#include <sstream>
#include <string>
#include <vector>
#define MAXP 1000000
#define MAXN 1000000
const std::string usage =
"Exactly three arguments are required -- the number of the pages provided for the drawing, "
"the number of vertices of the graph, and a comma-separated list of the edge lengths. "
"Two vertices u,v are connected iff abs(u-v) mod n is from the list of edge lengths."
"No spaces in the list of edge lengths.\n"
"E.g. \"gen_circulant 2 10 1,2,3\".\n";
void print_usage_and_exit()
{
fprintf(stderr, usage.c_str());
exit(0);
}
int main(int argc, char *argv[])
{
if (argc != 4)
print_usage_and_exit();
int p = -1;
p = atoi(argv[1]);
if (p <= 0 || p > MAXP)
print_usage_and_exit();
int n = -1;
n = atoi(argv[2]);
if (n <= 0 || n > MAXN)
print_usage_and_exit();
std::string lString(argv[3]);
std::istringstream istr(lString);
std::vector<int> lengths;
int i;
while (istr >> i)
{
lengths.push_back(i);
if (istr.peek() == ',')
istr.ignore();
}
printf("%d\n", n);
printf("%d\n", p);
for (int i = 0; i < n; i++)
printf("%d\n", i);
for (int i = 0; i < n; i++)
for (int l : lengths)
printf("%d %d [0]\n", i, (i + l) % n);
return 0;
}
| 21.819444 | 96 | 0.60662 | [
"vector"
] |
cdfdd6253f12229225f10be0eabb4b621dca7c04 | 10,638 | cpp | C++ | CPD_xonly_attr/main_model copy.cpp | nkrishnan94/cell_model | 9ec39dc2a68a0b8d19cd395c71238eee88d8f469 | [
"MIT"
] | null | null | null | CPD_xonly_attr/main_model copy.cpp | nkrishnan94/cell_model | 9ec39dc2a68a0b8d19cd395c71238eee88d8f469 | [
"MIT"
] | null | null | null | CPD_xonly_attr/main_model copy.cpp | nkrishnan94/cell_model | 9ec39dc2a68a0b8d19cd395c71238eee88d8f469 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <fstream>
#include <math.h>
#include <sstream>
#include <string>
#include <unistd.h>
#include <array>
#include <vector>
#include <random>
#include <ctime>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
const double xdim = 100 *pow(10,-6); //x length of simulation in microns
const double ydim = 100*pow(10,-6); //y length of simulation in microns
const double zdim = 100*pow(10,-6); //z length of simulation in microns
unsigned long CPD_flag = 1;
//long int cell_max = int(xdim * ydim * zdim); //max nummber ofcells allowed assuming near denset packing
const int param_N = 4; // number of cell state parameters -> center x coordinate,center y coordinate,center z coordinate, radius, y force
unsigned int tStop = 10000;
unsigned int CPD_time = 0;
float dt =2;
//parameters:
float R = 4.125*pow(10,-6); //um
float a = 2.5; //um
float K= 2.2*pow(10,-9);//*pow(10,0); N/um
float s_b = 1*pow(10,6);
float fric = 0.4*pow(10,-6); //N sec. um
float Dc = 0*pow(10,-6);
float delc = 1.4*2*a*R; //um
float deld = 1.4*2*a*R; //um
float delca = 1.4*a*R; //um
float delda=1.8*a*R; //um
double vel_thresh = .01*pow(10,-6);
const int xcells = 4;
const int ycells = 4;
const int zcells=4;
//const int cell_num = int(xcells*ycells*zcells);
const int cell_num = 2;
int record_time =int(10/dt);
int main(){
using namespace std;
//cout<<cell_num<<endl;
//cout<<cell_num<<"\n";
/*if (cell_num > cell_max){
std::cout << "maximum initial density exceeded" <<"\n";
exit(EXIT_FAILURE);
}*/
default_random_engine generator;
normal_distribution<double> distribution(0,1*pow(10,-6));
long double cells[cell_num][param_N] = {0}; //array containing centers, radius
//long double bonds[100][100] = {0};
long double x_space = (double(xdim)-double(2*R))/double(xcells);
long double y_space = (double(ydim)-double(2*R))/double(ycells);
long double z_space = (double(zdim)-double(1.1*a*R))/double(zcells);
//long double z_space= 2*1.1*R;
cout<< x_space<<endl;
cout<< y_space<<endl;
cout<< z_space<<endl;
//cout<<x_space<<endl;
int cell_count =0;
cells[0][0] = xdim/2-2*1.3*a*R;;
cells[0][1] = ydim/2;
cells[0][2] = zdim/2;
cells[0][3]= double(R);
cells[1][0] = xdim/2;
cells[1][1] = ydim/2 ;
cells[1][2] = zdim/2;
cells[1][3]= double(R);
/*for(int z =0; z<zcells;z++){
for(int y =0; y<ycells;y++){
for(int x =0; x<xcells;x++){
if(cell_count<cell_num){
cells[cell_count][0]= double(R+x*x_space);
cells[cell_count][1] = double(R+y*y_space);
cells[cell_count][2]= double(R+z*z_space);
cells[cell_count][3]= double(R);
//cout << cells[cell_count][2]<<endl;
cell_count+=1;
}
}
}
}*/
ofstream fprof,fvels;
time_t time_start;
clock_t c_init = clock();
struct tm * timeinfo;
char buffer [80];
float ht = 0.5;
time (&time_start);
timeinfo = localtime (&time_start);
strftime (buffer,80,"%F-%H-%M-%S",timeinfo);
ostringstream date_time;
date_time << buffer;
fprof.open("CPD/prof_init_" + date_time.str()+"_.txt");
fvels.open("CPD/vel_"+date_time.str()+"_.txt");
//vector <double> fvels;
/*establish radii
for(int n=0;n<10;n++){
int cell_ind[cell_num] ={0};
for(int i = 0; i <cell_num; i++){
cell_ind[i] =i;
}
random_shuffle(cell_ind, cell_ind + cell_num);
for(int i = 0; i <cell_num; i++){
int ind = cell_ind[i];
double min_dist =500;
for (int j =0; j <cell_num;j++){
double dist=0;
for(int c=0; c< 3;c++){
dist+=pow(cells[ind][c]-cells[j][c],2);
}
//cout<<pow(dist,.5)<<endl;
if ((pow(dist,.5)<min_dist)&&(dist>0)){
min_dist=double(pow(dist,.5));
}
}
cells[i][3] = (double(min_dist)/2)/double(a);
}
}*/
for(int i = 0; i < cell_num; i++){
fprof <<setprecision(8)<< fixed << i << ", " << cells[i][0] << ", " << cells[i][1] << ", " << cells[i][2] <<", " << cells[i][3]<<endl;
}
for(int t =0;t<int(tStop/dt);t++){
cout <<t<<endl;
//refresh force vector
long double forces[cell_num][3] = {0};
long int bonds[cell_num][3] = {0};
for(int i = 0; i <cell_num; i++){
//int ind = cell_ind[i];
for (int j =0; j <cell_num; j++){
if(i!=j){
float dist=0;
for(int c=0; c<3;c++){
//cout <<cells[ind][c] <<", " <<cells[j][c]<<endl;
dist+=pow(cells[i][c]-cells[j][c],2);
}
if(pow(dist,.5)<delc){
float xij = a*(cells[i][3]+cells[j][3]) - pow(dist,.5);
//int sign = -xij/abs(xij);
float fij = K*xij*tanh(s_b*abs(xij));
for(int c=0; c<3;c++){
forces[i][c] += fij *(( cells[i][c]-cells[j][c]) /pow(dist,.5));
}
//cout<<setprecision(11)<<forces[i][2]<<endl;
//cout<<setprecision(11)<<cells[i][2]<<endl;
//cout<<setprecision(11)<<cells[i][3]<<endl;
}
}
/* if(i==j){
if(cells[i][2]<delca){
float xij = a*(cells[i][3]) - cells[i][2];
float fij = .5*K*xij*tanh(s_b*abs(xij));
forces[i][2] += fij;
}
}*/
}
}
//forces[cell_num][3] = {0};
//cout<<forces[0][0]<<endl;
//cout<< dt*forces[0][0]/fric + pow(2*Dc*dt,.5)*distribution(generator)<<endl;
//cout<< cells[0][0] <<endl;
double x;
double y;
double z;
double dx=0;
int cell_thresh =0;
int new_cell_num=0;
for(int i = 0; i <cell_num; i++){
if (cells[i][2]>-1){
//cout<<pow(2*Dc*dt,.5)*distribution(generator)<<endl;
//cout<<i<<endl;
x = cells[i][0];
y = cells[i][1];
z = cells[i][2];
//what about if theyre not meeting these conditions. you fucking idiot.....
/*if((cells[i][0] + dt*forces[i][0]/fric + pow(2*Dc*dt,.5)*distribution(generator) < R )||(cells[i][0] + dt*forces[i][0]/fric + pow(2*Dc*dt,.5)*distribution(generator) + R>xdim )){
forces[i][0] = -forces[i][0];
forces[i][0] = 0;
}
if((cells[i][1] + dt*forces[i][1]/fric + pow(2*Dc*dt,.5)*distribution(generator) < R )||(cells[i][1] + dt*forces[i][1]/fric + pow(2*Dc*dt,.5)*distribution(generator) + R>ydim )){
forces[i][1] = -forces[i][1];
forces[i][1] = 0;
}
if((cells[i][2] + dt*forces[i][2]/fric + pow(2*Dc*dt,.5)*distribution(generator) < R )||(cells[i][2] + dt*forces[i][2]/fric + pow(2*Dc*dt,.5)*distribution(generator) + R>zdim )){
forces[i][2] = -forces[i][2];
forces[i][2] = 0;
}*/
cells[i][0] = cells[i][0] + dt*forces[i][0]/fric + pow(2*Dc*dt,.5)*distribution(generator);
cells[i][1] = cells[i][1] + dt*forces[i][1]/fric + pow(2*Dc*dt,.5)*distribution(generator);
cells[i][2] = cells[i][2] + dt*forces[i][2]/fric + pow(2*Dc*dt,.5)*distribution(generator);
/* if((cells[i][2] + dt*forces[i][2]/fric + pow(2*Dc*dt,.5)*distribution(generator) < R) ){
cells[i][2] =R;
} else{
cells[i][2] = cells[i][2] + dt*forces[i][2]/fric + pow(2*Dc*dt,.5)*distribution(generator);
}*/
new_cell_num+=1;
dx= pow(pow(x-cells[i][0],2)+pow(y-cells[i][1],2)+pow(z-cells[i][2],2),.5);
if (dx>vel_thresh){
cell_thresh+=1;
}
}
}
if ((t % record_time)==0){
ostringstream strT;
strT << int(t*dt);
string proftName = "prof_T_" + strT.str() + "_"+ date_time.str() + ".txt";
//string yforceName = "force_T_" + strT.str() + "_"+ date_time.str() + ".txt";
ofstream fproft;
fproft.open("CPD/"+proftName);
for(int i = 0; i <cell_num; i++){
fproft<< setprecision(11)<< fixed << i << ", " << cells[i][0]*pow(10,6) << ", " << cells[i][1]*pow(10,6) << ", " << cells[i][2]*pow(10,6)<<", " << cells[i][3]*pow(10,6)<<", " << forces[i][0]*pow(10,6)<< ", "<<forces[i][1]*pow(10,6)<< ", "<<forces[i][2]*pow(10,6)<< endl;
}
fvels << setprecision(11)<< t <<", "<< cell_thresh << endl;
}
/*if (t == int(CPD_time/dt) ){
if (CPD_flag==1){
for(int i = 0; i <cell_num; i++){
if( (cells[i][1]>ydim/2-450*pow(10,-6)) &&(cells[i][1]<ydim/2+450*pow(10,-6)) &&(cells[i][2] <20*pow(10,-6)) ){
cells[i][2] =-30;
cells[i][3] = 0;
}
}
}
}*/
}
clock_t c_fin = clock();
double run_time = double(c_fin - c_init)/CLOCKS_PER_SEC;
cout << "Finished!" << "\n";
cout << "Finished in " << run_time << " seconds \n";
puts (buffer);
//cout<<setprecision(8)<< fixed <<double(rsum)/double(cell_num)<<endl;
//fprof <<setprecision(8)<< fixed << i << ", " << cells[i][0] << ", " << cells[i][1] << ", " << cells[i][2] <<", " << cells[i][3]endl;
return 0;
}
| 28.368 | 286 | 0.445666 | [
"vector"
] |
a80059acd3954592565e9845503e97f0210b92bd | 360 | cpp | C++ | 1329.cpp | zhulk3/leetCode | 0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc | [
"Apache-2.0"
] | 2 | 2020-03-13T08:14:01.000Z | 2021-09-03T15:27:49.000Z | 1329.cpp | zhulk3/LeetCode | 0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc | [
"Apache-2.0"
] | null | null | null | 1329.cpp | zhulk3/LeetCode | 0a1dbf8d58558ab9b05c5150aafa9e4344cec5bc | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<vector<int>> diagonalSort(vector<vector<int>>& mat) {
int row = mat.size();
int col = mat[0].size();
vector<vector<int> >ans(row);
for (int i = 0; i < row; i++) {
ans.resize(col);
}
for (int i = col - 1; i >= 0; i--) {
for(int j=i;i<row)
}
}
}; | 18.947368 | 61 | 0.580556 | [
"vector"
] |
a804610487ab1f6e464ae48c16a2457de178eb20 | 46,544 | hpp | C++ | src/netxs/text/utf.hpp | aeiouaeiouaeiouaeiouaeiouaeiou/vtm | f6e257d0f2c98a9be6ce9451abc4927f98525b7e | [
"MIT"
] | null | null | null | src/netxs/text/utf.hpp | aeiouaeiouaeiouaeiouaeiouaeiou/vtm | f6e257d0f2c98a9be6ce9451abc4927f98525b7e | [
"MIT"
] | null | null | null | src/netxs/text/utf.hpp | aeiouaeiouaeiouaeiouaeiouaeiou/vtm | f6e257d0f2c98a9be6ce9451abc4927f98525b7e | [
"MIT"
] | null | null | null | // Copyright (c) NetXS Group.
// Licensed under the MIT license.
#ifndef NETXS_UTF_HPP
#define NETXS_UTF_HPP
#include "unidata.hpp"
#include "../math/intmath.hpp"
#include <string>
#include <string_view>
#include <vector>
#include <map>
#include <algorithm>
#include <charconv>
#include <optional>
#include <sstream>
#define GRAPHEME_CLUSTER_LIMIT (31) // Limits the number of code points in a grapheme cluster to a number sufficient for any possible linguistic situation.
#define CLUSTER_FIELD_SIZE (5)
#define WCWIDTH_FIELD_SIZE (2)
#define WCWIDTH_CLAMP(wcwidth) (wcwidth & (0XFF >> (8 - WCWIDTH_FIELD_SIZE)))
namespace netxs::utf
{
using view = std::string_view;
using text = std::string;
using wide = std::wstring;
using flux = std::stringstream;
using utfx = uint32_t;
using ctrl = unidata::cntrls::type;
static constexpr utfx REPLACEMENT_CHARACTER = 0x0000FFFD;
static constexpr char const* REPLACEMENT_CHARACTER_UTF8 = "\uFFFD"; // 0xEF 0xBF 0xBD (efbfbd) "�"
static constexpr size_t REPLACEMENT_CHARACTER_UTF8_LEN = 3;
static constexpr view REPLACEMENT_CHARACTER_UTF8_VIEW = view(REPLACEMENT_CHARACTER_UTF8, REPLACEMENT_CHARACTER_UTF8_LEN); // '�'
static constexpr view WHITESPACE_CHARACTER_UTF8_VIEW = view(" ", 1); // ' '
// utf: A grapheme cluster decoded from UTF-8.
struct prop : public unidata::unidata
{
//todo size_t is too much for that
size_t utf8len;
bool correct;
size_t cpcount;
utfx cdpoint;
constexpr
prop(size_t size)
: unidata (),
utf8len { size },
correct { faux },
cpcount { 0 },
cdpoint { 0 }
{ }
prop(utfx code, size_t size)
: unidata ( code ),
utf8len { size },
correct { true },
cpcount { 0 },
cdpoint { code }
{ }
constexpr
prop(prop const& attr)
: unidata (attr),
utf8len {attr.utf8len},
correct {attr.correct},
cpcount {attr.cpcount},
cdpoint {attr.cdpoint}
{ }
auto combine(prop const& next)
{
if (next.utf8len && cpcount < GRAPHEME_CLUSTER_LIMIT && next.allied(brgroup))
{
ucwidth = std::max(ucwidth, next.ucwidth);
utf8len += next.utf8len;
cpcount += 1;
return 0_sz;
}
else
{
return utf8len;
}
}
};
// utf: First byte based UTF-8 codepoint lengths.
static constexpr int utf8lengths[] =
{ // 0 1 2 3 4 5 6 7 8 9 A B C D E F
/* 0 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 1 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 2 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 3 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 4 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 5 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 6 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 7 */ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
/* 8 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* 9 */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* A */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* B */ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
/* C */ 0, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
/* D */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
/* E */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
/* F */ 4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
} ;
// utf: Codepoint iterator.
struct cpit
{
using chrptr = view::const_pointer;
chrptr textptr;
size_t balance;
size_t utf8len;
cpit(view const& utf8)
: textptr { utf8.data() },
balance { utf8.size() },
utf8len { 0 }
{ }
void redo(view const& utf8)
{
textptr = utf8.data();
balance = utf8.size();
}
view rest()
{
return view{ textptr, balance };
}
void step()
{
textptr += utf8len;
balance -= utf8len;
utf8len = 0;
}
prop take()
{
utfx cp;
utfx c2;
utfx c3;
utfx c4;
if (balance)
{
auto data = reinterpret_cast<unsigned char const*>(textptr);
cp = *data;
switch (utf8lengths[cp])
{
case 1:
utf8len = 1U;
break;
case 0:
return prop(utf8len = 1);
break;
case 2:
if (balance > 1)
{
if (c2 = *++data; (c2 & 0xC0) == 0x80)
{
utf8len = 2U;
cp = ((cp & 0b00011111) << 6)
| (c2 & 0b00111111);
}
else return prop(utf8len = 1);
}
else return prop(utf8len = 1);
break;
case 3:
if (balance > 2)
{
if (c2 = *++data; (c2 & 0xC0) == 0x80)
{
if (c3 = *++data; (c3 & 0xC0) == 0x80)
{
utf8len = 3U;
cp = ((cp & 0b00001111) << 12)
|((c2 & 0b00111111) << 6)
| (c3 & 0b00111111);
if (cp >= 0xfdd0 && (cp < 0xfdf0 || ((cp & 0xfffe) == 0xfffe)))
{
return prop(utf8len);
}
}
else return prop(utf8len = 2);
}
else return prop(utf8len = 1);
}
else return prop(utf8len = balance);
break;
default: // case 4
if (balance > 3)
{
if (c2 = *++data; (c2 & 0xC0) == 0x80)
{
if (c3 = *++data; (c3 & 0xC0) == 0x80)
{
if (c4 = *++data; (c4 & 0xC0) == 0x80)
{
utf8len = 4U;
cp = ((cp & 0b00000111) << 18)
|((c2 & 0b00111111) << 12)
|((c3 & 0b00111111) << 6)
| (c4 & 0b00111111);
if (cp > 0x10ffff)
{
return prop(utf8len);
}
}
else return prop(utf8len = 3);
}
else return prop(utf8len = 2);
}
else return prop(utf8len = 1);
}
else return prop(utf8len = balance);
break;
}
}
else return prop(utf8len = 0);
return prop{ cp, utf8len };
}
operator bool ()
{
return balance > 0;
}
};
// utf: Grapheme cluster with properties.
struct frag
{
view text;
prop attr;
};
// utf: Break the text into the enriched grapheme clusters.
// Forward the result to the dest using the "serve" and "yield" lambdas.
// serve: Handle escaped control sequences.
// auto s = [&](utf::prop const& traits, view const& utf8) -> view;
// yield: Handle grapheme clusters.
// auto y = [&](frag const& cluster){};
// EGC: parse by grapheme clusters (true) or codepoints (faux)
template<bool EGC = true, class S, class Y>
void decode(S serve, Y yield, view utf8)
{
if (auto code = cpit { utf8 })
{
auto next = code.take();
do
{
if (next.is_cmd())
{
code.step();
auto rest = code.rest();
auto chars = serve(next, rest);
code.redo(chars);
next = code.take();
}
else
{
if constexpr (EGC)
{
auto head = code.textptr;
auto left = next;
do
{
code.step();
if (next.correct)
{
next = code.take();
if (auto size = left.combine(next))
{
auto crop = frag{ view(head, size), left };
yield(crop);
break;
}
}
else
{
next.utf8len = left.utf8len;
auto crop = frag{ REPLACEMENT_CHARACTER_UTF8_VIEW, next };
yield(crop);
next = code.take();
break;
}
}
while (true);
}
else
{
if (next.correct)
{
auto crop = frag{ view(code.textptr,next.utf8len), next };
yield(crop);
}
else
{
auto crop = frag{ REPLACEMENT_CHARACTER_UTF8_VIEW, next };
yield(crop);
}
code.step();
next = code.take();
}
}
}
while (code);
}
}
// utf: Return the first grapheme cluster and its Unicode attributes.
static
auto letter(view const& utf8)
{
if (auto code = cpit{ utf8 })
{
auto next = code.take();
do
{
if (next.is_cmd())
{
//todo revise
//code.step();
return frag{ REPLACEMENT_CHARACTER_UTF8_VIEW, next };
}
else
{
auto head = code.textptr;
auto left = next;
do
{
code.step();
if (next.correct)
{
next = code.take();
if (auto size = left.combine(next))
{
return frag{ view(head, size), left };
}
}
else
{
next.utf8len = left.utf8len;
return frag{ REPLACEMENT_CHARACTER_UTF8_VIEW, next };
}
}
while (true);
}
}
while (code);
}
return frag{ REPLACEMENT_CHARACTER_UTF8_VIEW, prop{ 0 } };
}
struct qiew : public view
{
void pop_front () { view::remove_prefix(1); }
si32 front () const { return static_cast<unsigned char>(view::front()); }
operator bool () const { return view::length(); }
constexpr qiew() noexcept : view() { }
constexpr qiew(view const& v) noexcept : view(v) { }
template<class INT>
constexpr qiew(char const* ptr, INT len) noexcept: view(ptr, len) { }
constexpr qiew& operator = (qiew const&) noexcept = default;
// Pop front a sequence of the same control points and return their count + 1.
auto pop_all(ctrl cmd)
{
si32 n = 1;
auto next = utf::letter(*this);
while (next.attr.control == cmd)
{
view::remove_prefix(next.attr.utf8len);
next = utf::letter(*this);
n++;
}
return n;
}
// Pop front a sequence of the same control points and return their count + 1.
auto pop_all(char c)
{
si32 n = 1;
while (length() && view::front() == c)
{
view::remove_prefix(1);
n++;
}
return n;
}
// Return true and pop front control point when it is equal to cmd.
auto pop_if(ctrl cmd)
{
auto next = utf::letter(*this);
if (next.attr.control == cmd)
{
view::remove_prefix(next.attr.utf8len);
return true;
}
return faux;
}
// Return true and pop front when it is equal to c.
auto pop_if(char c)
{
if (length() && view::front() == c)
{
view::remove_prefix(1);
return true;
}
return faux;
}
};
template<class VIEW, class = std::enable_if_t<std::is_base_of<view, VIEW>::value == true, VIEW>>
inline std::optional<si32> to_int(VIEW& ascii)
{
si32 num;
auto top = ascii.data();
auto end = ascii.length() + top;
if (auto [pos, err] = std::from_chars(top, end, num); err == std::errc())
{
ascii.remove_prefix(pos - top);
return num;
}
else return std::nullopt;
}
template<class T, class = std::enable_if_t<std::is_base_of<view, T>::value == faux, T>>
inline auto to_int(T&& utf8)
{
auto shadow = view{ std::forward<T>(utf8) };
return to_int(shadow);
}
template<class T, class A>
inline auto to_int(T&& utf8, A fallback)
{
auto result = to_int(std::forward<T>(utf8));
return result ? result.value() : fallback;
}
enum codepage
{
cp866,
cp1251,
count
};
struct letter_sync
{
int lb;
int rb;
int cp;
};
static constexpr letter_sync utf8_cp866[] =
{
{ 0x0410, 0x043F, 0x80 }, // А - п
{ 0x0440, 0x044F, 0xE0 }, // р - я
{ 0x0401, 0x0401, 0xF0 }, // Ё
{ 0x0451, 0x0451, 0xF1 }, // ё
{ 0x0404, 0x0404, 0xF2 }, // Є
{ 0x0454, 0x0454, 0xF3 }, // є
{ 0x0407, 0x0407, 0xF4 }, // Ї
{ 0x0457, 0x0457, 0xF5 }, // ї
{ 0x040E, 0x040E, 0xF6 }, // Ў
{ 0x045E, 0x045E, 0xF7 }, // ў
{ 0x00B0, 0x00B0, 0xF8 }, // °
{ 0x2219, 0x2219, 0xF9 }, // ∙
{ 0x00B7, 0x00B7, 0xFA }, // ·
{ 0x221A, 0x221A, 0xFB }, // √
{ 0x2116, 0x2116, 0xFC }, // №
{ 0x00A4, 0x00A4, 0xFD }, // ¤
{ 0x25A0, 0x25A0, 0xFE }, // ■
{ 0x00A0, 0x00A0, 0xFF }, //
{ 0x2591, 0x2591, 0xB0 }, // ░
{ 0x2592, 0x2592, 0xB1 }, // ▒
{ 0x2593, 0x2593, 0xB2 }, // ▓
{ 0x2502, 0x2502, 0xB3 }, // │
{ 0x2524, 0x2524, 0xB4 }, // ┤
{ 0x2561, 0x2561, 0xB5 }, // ╡
{ 0x2562, 0x2562, 0xB6 }, // ╢
{ 0x2556, 0x2556, 0xB7 }, // ╖
{ 0x2555, 0x2555, 0xB8 }, // ╕
{ 0x2563, 0x2563, 0xB9 }, // ╣
{ 0x2551, 0x2551, 0xBA }, // ║
{ 0x2557, 0x2557, 0xBB }, // ╗
{ 0x255D, 0x255D, 0xBC }, // ╝
{ 0x255C, 0x255C, 0xBD }, // ╜
{ 0x255B, 0x255B, 0xBE }, // ╛
{ 0x2510, 0x2510, 0xBF }, // ┐
{ 0x2514, 0x2514, 0xC0 }, // └
{ 0x2534, 0x2534, 0xC1 }, // ┴
{ 0x252C, 0x252C, 0xC2 }, // ┬
{ 0x251C, 0x251C, 0xC3 }, // ├
{ 0x2500, 0x2500, 0xC4 }, // ─
{ 0x253C, 0x253C, 0xC5 }, // ┼
{ 0x255E, 0x255E, 0xC6 }, // ╞
{ 0x255F, 0x255F, 0xC7 }, // ╟
{ 0x255A, 0x255A, 0xC8 }, // ╚
{ 0x2554, 0x2554, 0xC9 }, // ╔
{ 0x2569, 0x2569, 0xCA }, // ╩
{ 0x2566, 0x2566, 0xCB }, // ╦
{ 0x2560, 0x2560, 0xCC }, // ╠
{ 0x2550, 0x2550, 0xCD }, // ═
{ 0x256C, 0x256C, 0xCE }, // ╬
{ 0x2567, 0x2567, 0xCF }, // ╧
{ 0x2568, 0x2568, 0xD0 }, // ╨
{ 0x2564, 0x2564, 0xD1 }, // ╤
{ 0x2565, 0x2565, 0xD2 }, // ╥
{ 0x2559, 0x2559, 0xD3 }, // ╙
{ 0x2558, 0x2558, 0xD4 }, // ╘
{ 0x2552, 0x2552, 0xD5 }, // ╒
{ 0x2553, 0x2553, 0xD6 }, // ╓
{ 0x256B, 0x256B, 0xD7 }, // ╫
{ 0x256A, 0x256A, 0xD8 }, // ╪
{ 0x2518, 0x2518, 0xD9 }, // ┘
{ 0x250C, 0x250C, 0xDA }, // ┌
{ 0x2588, 0x2588, 0xDB }, // █
{ 0x2584, 0x2584, 0xDC }, // ▄
{ 0x258C, 0x258C, 0xDD }, // ▌
{ 0x2590, 0x2590, 0xDE }, // ▐
{ 0x2580, 0x2580, 0xDF }, // ▀
};
static constexpr letter_sync utf8_cp1251[] =
{
{ 0x0410, 0x044F, 0xC0 }, // А - я
{ 0x0402, 0x0402, 0x80 }, // Ђ
{ 0x0403, 0x0403, 0x81 }, // Ѓ
{ 0x201A, 0x201A, 0x82 }, // ‚
{ 0x0453, 0x0453, 0x83 }, // ѓ
{ 0x201E, 0x201E, 0x84 }, // „
{ 0x2026, 0x2026, 0x85 }, // …
{ 0x2020, 0x2020, 0x86 }, // †
{ 0x2021, 0x2021, 0x87 }, // ‡
{ 0x20AC, 0x20AC, 0x88 }, // €
{ 0x2030, 0x2030, 0x89 }, // ‰
{ 0x0409, 0x0409, 0x8A }, // Љ
{ 0x2039, 0x2039, 0x8B }, // ‹
{ 0x040A, 0x040A, 0x8C }, // Њ
{ 0x040C, 0x040C, 0x8D }, // Ќ
{ 0x040B, 0x040B, 0x8E }, // Ћ
{ 0x040F, 0x040F, 0x8F }, // Џ
{ 0x0452, 0x0452, 0x90 }, // ђ
{ 0x2018, 0x2018, 0x91 }, // ‘
{ 0x2019, 0x2019, 0x92 }, // ’
{ 0x201C, 0x201C, 0x93 }, // “
{ 0x201D, 0x201D, 0x94 }, // ”
{ 0x2022, 0x2022, 0x95 }, // •
{ 0x2013, 0x2013, 0x96 }, // –
{ 0x2014, 0x2014, 0x97 }, // —
{ 0x00A0, 0x00A0, 0x98 }, //
{ 0x2122, 0x2122, 0x99 }, // ™
{ 0x0459, 0x0459, 0x9A }, // љ
{ 0x203A, 0x203A, 0x9B }, // ›
{ 0x045A, 0x045A, 0x9C }, // њ
{ 0x045C, 0x045C, 0x9D }, // ќ
{ 0x045B, 0x045B, 0x9E }, // ћ
{ 0x045F, 0x045F, 0x9F }, // џ
{ 0x00A0, 0x00A0, 0xA0 }, //
{ 0x040E, 0x040E, 0xA1 }, // Ў
{ 0x045E, 0x045E, 0xA2 }, // ў
{ 0x0408, 0x0408, 0xA3 }, // Ј
{ 0x00A4, 0x00A4, 0xA4 }, // ¤
{ 0x0490, 0x0490, 0xA5 }, // Ґ
{ 0x00A6, 0x00A6, 0xA6 }, // ¦
{ 0x00A7, 0x00A7, 0xA7 }, // §
{ 0x0401, 0x0401, 0xA8 }, // Ё
{ 0x00A9, 0x00A9, 0xA9 }, // ©
{ 0x0404, 0x0404, 0xAA }, // Є
{ 0x00AB, 0x00AB, 0xAB }, // «
{ 0x00AC, 0x00AC, 0xAC }, // ¬
{ 0x00AD, 0x00AD, 0xAD }, //
{ 0x00AE, 0x00AE, 0xAE }, // ®
{ 0x0407, 0x0407, 0xAF }, // Ї
{ 0x00B0, 0x00B0, 0xB0 }, // °
{ 0x00B1, 0x00B1, 0xB1 }, // ±
{ 0x0406, 0x0406, 0xB2 }, // І
{ 0x0456, 0x0456, 0xB3 }, // і
{ 0x0491, 0x0491, 0xB4 }, // ґ
{ 0x00B5, 0x00B5, 0xB5 }, // µ
{ 0x00B6, 0x00B6, 0xB6 }, // ¶
{ 0x00B7, 0x00B7, 0xB7 }, // ·
{ 0x0451, 0x0451, 0xB8 }, // ё
{ 0x2116, 0x2116, 0xB9 }, // №
{ 0x0454, 0x0454, 0xBA }, // є
{ 0x00BB, 0x00BB, 0xBB }, // »
{ 0x0458, 0x0458, 0xBC }, // ј
{ 0x0405, 0x0405, 0xBD }, // Ѕ
{ 0x0455, 0x0455, 0xBE }, // ѕ
{ 0x0457, 0x0457, 0xBF }, // ї
};
//todo revise, use cp_table as an arg instead of a template parameter
template<auto cp_table, class TEXT_OR_VIEW>
auto cp_convert(TEXT_OR_VIEW const& utf8_text, char invalid_char)
{
text crop;
auto count = sizeof(cp_table) / sizeof(letter_sync);
auto data = utf8_text.data();
auto size = utf8_text.size();
for (auto i = 0UL; i < size && data[i] != 0; ++i)
{
auto c = data[i];
if ((c & 0x80) == 0)
{
crop.push_back(c);
}
else if ((~c) & 0x20 && ++i < size)
{
auto next = data[i];
utfx code = ((c & 0x1F) << 6) + (next & 0x3F);
c = invalid_char;
for (auto j = 0UL; j < count; ++j)
{
if (code >= cp_table[j].lb
&& code <= cp_table[j].rb)
{
c = static_cast<char>(code - cp_table[j].lb + cp_table[j].cp);
break;
}
}
crop.push_back(c);
}
}
return crop;
}
template<class TEXT_OR_VIEW>
text to_dos(TEXT_OR_VIEW const& utf8, char invalid_char = '_', codepage cp = codepage::cp866)
{
switch (cp)
{
case codepage::cp866: return cp_convert<utf8_cp866>(utf8, invalid_char);
case codepage::cp1251: return cp_convert<utf8_cp1251>(utf8, invalid_char);
default: return utf8;
}
}
//todo deprecate
template<class T>
auto to_view(T* c_str, size_t limit)
{
auto iter = c_str;
auto end = c_str + limit;
while (iter < end && *iter != 0) { ++iter; }
return std::basic_string_view<T>(c_str, iter - c_str);
}
static wide to_utf(char const* utf8, size_t size)
{
// � The standard also recommends replacing each error with the replacement character.
//
// In terms of the newline, Unicode introduced U+2028 LINE SEPARATOR
// and U+2029 PARAGRAPH SEPARATOR.
// c̳̻͚̻̩̻͉̯̄̏͑̋͆̎͐ͬ͑͌́͢h̵͔͈͍͇̪̯͇̞͖͇̜͉̪̪̤̙ͧͣ̓̐̓ͤ͋͒ͥ͑̆͒̓͋̑́͞ǎ̡̮̤̤̬͚̝͙̞͎̇ͧ͆͊ͅo̴̲̺͓̖͖͉̜̟̗̮̳͉̻͉̫̯̫̍̋̿̒͌̃̂͊̏̈̏̿ͧ́ͬ̌ͥ̇̓̀͢͜s̵̵̘̹̜̝̘̺̙̻̠̱͚̤͓͚̠͙̝͕͆̿̽ͥ̃͠͡
wide wide_text;
wide_text.reserve(size);
utfx code = {};
auto tail = utf8 + size;
while (utf8 < tail)
{
auto c = static_cast<unsigned char>(*utf8++);
if (c < 0x80) code = c;
else if (c < 0xc0) code =(c & 0x3f) | code << 6;
else if (c < 0xe0) code = c & 0x1f;
else if (c < 0xf0) code = c & 0x0f;
else code = c & 0x07;
if (code <= 0x10ffff)
{
if (utf8 == tail || (*utf8 & 0xc0) != 0x80)
{
if (code < 0xd800 || code >= 0xe000
|| sizeof(wchar_t) > 2) // single | wchar_t == char32_t
{
wide_text.push_back(static_cast<wchar_t>(code));
}
else if (code > 0xffff) // surrogate pair
{
wide_text.append({ static_cast<wchar_t>(0xd800 + (code >> 10)),
static_cast<wchar_t>(0xdc00 + (code & 0x03ff)) });
}
}
}
else wide_text.push_back(REPLACEMENT_CHARACTER);
}
//wide_text.shrink_to_fit();
return wide_text;
}
static inline utfx tocode(wchar_t c)
{
utfx code;
if (c >= 0xd800 && c <= 0xdbff)
{
code = ((c - 0xd800) << 10) + 0x10000;
}
else
{
if (c >= 0xdc00 && c <= 0xdfff) code = c - 0xdc00;
else code = c;
}
return code;
}
namespace
{
static inline void _to_utf(text& utf8, utfx code)
{
if (code <= 0x007f)
{
utf8.push_back(static_cast<char>(code));
}
else if (code <= 0x07ff)
{
utf8.push_back(static_cast<char>(0xc0 | ((code >> 0x06) & 0x1f)));
utf8.push_back(static_cast<char>(0x80 | ( code & 0x3f)));
}
else if (code <= 0xffff)
{
utf8.push_back(static_cast<char>(0xe0 | ((code >> 0x0c) & 0x0f)));
utf8.push_back(static_cast<char>(0x80 | ((code >> 0x06) & 0x3f)));
utf8.push_back(static_cast<char>(0x80 | ( code & 0x3f)));
}
else
{
utf8.push_back(static_cast<char>(0xf0 | ((code >> 0x12) & 0x07)));
utf8.push_back(static_cast<char>(0x80 | ((code >> 0x0c) & 0x3f)));
utf8.push_back(static_cast<char>(0x80 | ((code >> 0x06) & 0x3f)));
utf8.push_back(static_cast<char>(0x80 | ( code & 0x3f)));
}
}
}
static auto to_utf_from_code(utfx code)
{
text utf8;
_to_utf(utf8, code);
return utf8;
}
static text to_utf(wchar_t const* wide_text, size_t size)
{
text utf8;
utf8.reserve(size << 2);
utfx code = 0;
auto tail = wide_text + size;
while (wide_text < tail)
{
auto c = *wide_text++;
if (c >= 0xd800 && c <= 0xdbff)
{
code = ((c - 0xd800) << 10) + 0x10000;
}
else
{
if (c >= 0xdc00 && c <= 0xdfff) code |= c - 0xdc00;
else code = c;
_to_utf(utf8, code);
code = 0;
}
}
//utf8.shrink_to_fit();
return utf8;
}
template<class TEXT_OR_VIEW>
auto to_utf(TEXT_OR_VIEW&& str)
{
return to_utf(str.data(), str.size());
}
template<class T>
auto to_utf(T* c_str)
{
auto iter = c_str;
while (*iter != 0) { ++iter; }
return to_utf(c_str, iter - c_str);
}
template<class TEXT_OR_VIEW>
auto length(TEXT_OR_VIEW&& utf8)
{
si32 length = 0;
for (auto c : utf8)
{
length += (c & 0xc0) != 0x80;
}
return length;
}
// utf: Check utf-8 integrity (last codepoint) and cut off the invalid bytes at the end.
template<class TEXT_OR_VIEW>
void purify(TEXT_OR_VIEW& utf8)
{
if (auto size = utf8.size())
{
auto is_first = [](auto c) { return (c & 0xc0) != 0x80; };
bool first;
while (size && !(first = is_first(utf8[--size]))) // Find first byte.
{ }
if (first) // Check codepoint.
{
auto l = utf::letter(utf8.substr(size));
if (!l.attr.correct)
{
utf8 = utf8.substr(0, size);
}
}
else // Bad UTF-8 encoding (size == 0).
{
//Recycle all bad bytes (log?).
}
}
}
//todo deprecate cus too specific
static si32 shrink(view& utf8)
{
si32 length = 0;
auto size = utf8.size();
auto i = 0_sz;
while (i < size)
{
if ((utf8[i] & 0xc0) != 0x80)
{
if (utf8[i] > 0 && utf8[i] < 32)
{
break;
}
length++;
}
i++;
}
utf8.remove_suffix(size - i);
return length;
}
template<class TEXT_OR_VIEW>
auto substr(TEXT_OR_VIEW&& utf8, size_t start, size_t length = text::npos)
{
if (length == 0) return text{};
auto data = text{ utf8 };
auto head = data.data();
auto stop = head + data.size();
auto calc = [](auto& it, auto& count, auto limit)
{
while (it != limit)
{
if ((*it & 0xc0) != 0x80)
{
if (!count--) break;
}
++it;
}
};
if (start) calc(head, start, stop);
start = head - data.data();
if (length != text::npos)
{
auto tail = head;
calc(tail, length, stop);
return data.substr(start, tail - head);
}
else return data.substr(start);
}
template<class TEXT_OR_VIEW>
auto repeat(TEXT_OR_VIEW&& utf8, size_t count)
{
view what{ utf8 };
text result;
result.reserve(what.length() * count);
while (count--)
{
result += what;
}
return result;
}
auto inline repeat(char letter, size_t count)
{
return text(count, letter);
}
template<class TEXT_OR_VIEW, class C>
auto remove(TEXT_OR_VIEW&& from, C&& what)
{
view _what{ what };
auto s_size = from.size();
auto c_size =_what.size();
if (c_size)
{
while (s_size >= c_size && from.substr(s_size - c_size, c_size) == what)
{
s_size -= c_size;
}
}
return from.substr(0, s_size);
}
template<class W, class R>
static void change(text& utf8, W const& what, R const& replace)
{
view frag{ what };
view fill{ replace };
auto const& npos = text::npos;
auto spot = 0_sz;
auto line_sz = utf8.length();
auto what_sz = frag.length();
auto repl_sz = fill.length();
if (!what_sz || line_sz < what_sz) return;
if (what_sz == repl_sz)
{
while ((spot = utf8.find(frag, spot)) != npos)
{
utf8.replace(spot, what_sz, fill);
spot += what_sz;
}
}
else
{
auto last = 0_sz;
if (what_sz < repl_sz)
{
text temp;
temp.reserve((line_sz / what_sz + 1) * repl_sz); // In order to avoid allocations.
auto shadow = view{ utf8 };
while ((spot = utf8.find(frag, last)) != npos)
{
temp += shadow.substr(last, spot - last);
temp += fill;
spot += what_sz;
last = spot;
}
temp += shadow.substr(last);
utf8 = temp; // Assign to perform simultaneous shrinking and copying.
}
else
{
auto base = utf8.data();
auto repl = fill.data();
auto dest = base;
auto copy = [](auto base, auto& dest, auto size)
{
auto stop = base + size;
while (base != stop) { *dest++ = *base++; }
};
while ((spot = utf8.find(frag, last)) != npos)
{
if (last) copy(base + last, dest, spot - last);
else dest += spot;
copy(repl, dest, repl_sz);
spot += what_sz;
last = spot;
}
copy(base + last, dest, line_sz - last);
utf8.resize(dest - base);
}
}
}
template<class TEXT_OR_VIEW, class T>
auto remain(TEXT_OR_VIEW&& utf8, T const& delimiter)
{
using type = std::remove_cvref_t<TEXT_OR_VIEW>;
view what{ delimiter };
type crop;
auto coor = utf8.find(what);
if (coor != text::npos)
{
crop = utf8.substr(coor + what.size(), text::npos);
}
return crop;
}
template<class TEXT_OR_VIEW>
auto remain(TEXT_OR_VIEW&& utf8, char delimiter = '.')
{
view what{ &delimiter, 1 };
return remain(std::move(utf8), what);
}
// utf: Return left substring (from begin) until delimeter (lazy=faux: from left, true: from right).
template<class T>
T cutoff(T const& txt, T const& delimiter = T{ '.' }, bool lazy = true)
{
return txt.substr(0, lazy ? txt.find(delimiter) : txt.rfind(delimiter));
}
template<class T>
inline T domain(T const& txt)
{
return remain(txt);
}
template<class TEXT_OR_VIEW, class F>
auto adjust(TEXT_OR_VIEW&& utf8, size_t required_width, F const& fill_char, bool right_aligned = faux)
{
text crop;
auto data = view{ utf8 };
if (data.empty())
{
crop = repeat(fill_char, required_width);
}
else
{
if (required_width > 0)
{
crop = substr(data, 0, required_width);
}
auto size = length(crop);
if (required_width > size)
{
if (right_aligned) crop = repeat(fill_char, required_width - size) + crop;
else crop = crop + repeat(fill_char, required_width - size);
}
}
return crop;
}
template<class INT_T, class T = char>
text format(INT_T number, size_t by_group = 3, T const& delimiter = ' ')
{
if (by_group)
{
auto utf8 = std::to_string(std::abs(number));
auto size = utf8.length();
auto coor = (size - 1) % by_group + 1;
auto crop = utf8.substr(0, coor);
for (; coor < size; coor += by_group)
{
crop += delimiter;
crop += utf8.substr(coor, by_group);
}
return number < 0 ? '-' + crop : crop;
}
else return std::to_string(number);
}
template <bool UCASE = faux, class V, class = typename std::enable_if<std::is_integral<V>::value>::type>
auto to_hex(V number, size_t width = sizeof(V) * 2, char filler = '0')
{
static constexpr auto nums = UCASE ? "0123456789ABCDEF"
: "0123456789abcdef";
text crop(width, filler);
auto head = crop.begin();
auto tail = head + width;
auto part = -4 + 4*width;
while (head != tail)
{
*head++ = nums[(number >> part) & 0x0f];
part -= 4;
}
return crop;
}
// utf: to_hex without allocations (the crop should has a reserved capacity).
template <bool UCASE = faux, class V, class = typename std::enable_if<std::is_integral<V>::value>::type>
auto to_hex(text& crop, V number, size_t width = sizeof(V) * 2, char filler = '0')
{
static constexpr auto nums = UCASE ? "0123456789ABCDEF"
: "0123456789abcdef";
auto part = -4 + 4*width;
while (width--)
{
crop.push_back(nums[(number >> part) & 0x0f]);
part -= 4;
}
return crop;
}
template <bool UCASE = faux>
auto to_hex(view buffer, bool formatted = faux)
{
if (formatted)
{
auto size = buffer.size();
auto addr = 0_sz;
text crop;
while (addr < size)
{
auto frag = (size - addr > 16) ? 16
: size - addr;
crop += adjust(std::to_string(addr), 4, '0', true);
for (auto i = 0_sz; i < 16; i++)
{
if (i % 8 == 0)
{
crop += i < frag ? " -" : " ";
}
crop += i < frag ? ' ' + to_hex<UCASE>(buffer[addr + i], 2, true)
: " ";
}
crop += " ";
for (auto i = addr; i < addr + frag; i++)
{
auto c = buffer[i];
crop += (c < 33) ? '.' : c;
}
crop += '\n';
addr += 16;
}
return crop;
}
else
{
static constexpr auto nums = UCASE ? "0123456789ABCDEF"
: "0123456789abcdef";
auto size = buffer.size() << 1;
auto buff = buffer.begin();
text crop(size, '0');
auto head = crop.begin();
auto tail = head + size;
while (head != tail)
{
*head++ = nums[(*buff >> 4) & 0x0f];
*head++ = nums[(*buff) & 0x0f];
buff++;
}
return crop;
}
}
template<class V1, class V2>
auto divide(V1 const& utf8, V2 const& delimiter)
{
using list = std::vector<view>;
text mark(delimiter);
list crop;
if (auto len = mark.size())
{
auto num = 0_sz;
auto cur = 0_sz;
auto pos = 0_sz;
while ((pos = utf8.find(mark, cur)) != V1::npos)
{
++num;
cur = pos + len;
}
crop.reserve(++num);
cur = 0_sz;
pos = 0_sz;
while ((pos = utf8.find(mark, cur)) != V1::npos)
{
crop.push_back(view{ utf8.data() + cur, pos - cur });
cur = pos + len;
}
auto end = view{ utf8.data() + cur, utf8.size() - cur };
crop.push_back(end);
}
return crop;
}
template <class Container>
auto maxlen(Container const& set)
{
auto len = 0_sz;
for (auto& obj : set)
{
auto val = utf::length(obj);
if (val > len) len = val;
}
return len;
}
class filler
{
std::map<text, text> dict;
public:
auto& operator [] (text const& s)
{
return dict[s];
}
auto operator () (text s)
{
for (auto& var : dict) utf::change(s, var.first, var.second);
for (auto& var : dict) utf::change(s, var.first, var.second);
return s;
}
};
namespace
{
template <class T>
void _concat(flux& s, T&& item)
{
s << item;
}
template<class T, class ...Args>
void _concat(flux& s, T&& item, Args&&... args)
{
s << item;
_concat(s, std::forward<Args>(args)...);
}
}
template<class ...Args>
auto concat(Args&&... args)
{
flux s;
_concat(s, std::forward<Args>(args)...);
return s.str();
}
auto base64(view utf8)
{
static constexpr auto code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
text data;
if (auto size = utf8.size())
{
data.resize(((size + 2) / 3) << 2);
auto iter = utf8.begin();
auto tail = utf8.end();
auto dest = data.begin();
do
{
auto crop = (unsigned char)*iter++ << 16;
if (iter != tail) //todo move ifs to the outside of loop (optimization)
crop += (unsigned char)*iter++ << 8;
else
{
*dest++ = code[0x3F & crop >> 18];
*dest++ = code[0x3F & crop >> 12];
*dest++ = '=';
*dest++ = '=';
break;
}
if (iter != tail)
crop += (unsigned char)*iter++;
else
{
*dest++ = code[0x3F & crop >> 18];
*dest++ = code[0x3F & crop >> 12];
*dest++ = code[0x3F & crop >> 6];
*dest++ = '=';
break;
}
*dest++ = code[0x3F & crop >> 18];
*dest++ = code[0x3F & crop >> 12];
*dest++ = code[0x3F & crop >> 6];
*dest++ = code[0x3F & crop ];
}
while (iter != tail);
}
return data;
}
auto unbase64(view bs64)
{
static constexpr auto code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
auto is64 = [](auto c) { return (c > 0x2E && c < 0x3A) // '/' and digits
|| (c > 0x40 && c < 0x5B) // Uppercase letters
|| (c > 0x60 && c < 0x7B) // Lowercase letters
|| (c == 0x2B); }; // '+'
text data;
view look{ code };
//todo reserv data
if (auto size = bs64.size())
{
byte buff[4];
auto head = bs64.begin();
auto tail = head + size;
auto step = 0;
while (head != tail)
{
auto c = *head++;
if (!is64(c) || c == '=') break;
buff[step] = c;
if (++step == 4)
{
step = 0;
for (auto& a : buff) a = static_cast<byte>(look.find(a));
data.push_back(( buff[0] << 2) + ((buff[1] & 0x30) >> 4));
data.push_back(((buff[1] & 0x0F) << 4) + ((buff[2] & 0x3C) >> 2));
data.push_back(((buff[2] & 0x03) << 6) + buff[3]);
}
}
if (step != 0)
{
auto temp = step;
while (temp < 4) buff[temp++] = 0;
for (auto& a : buff) a = static_cast<byte>(look.find(a));
if (step > 1) data.push_back(( buff[0] << 2) + ((buff[1] & 0x30) >> 4));
if (step > 2) data.push_back(((buff[1] & 0x0F) << 4) + ((buff[2] & 0x3C) >> 2));
}
}
return data;
}
// utf: Return a string without control chars (replace all ctrls with printables).
template<bool SPLIT = true>
auto debase(view utf8)
{
text buff;
auto size = utf8.size();
buff.reserve(size * 2);
auto head = size - 1; // Begining with ESC is a special case.
auto s = [&](prop const& traits, view& utf8)
{
switch (traits.cdpoint)
{
case 033:
if constexpr (SPLIT)
{
if (head == utf8.size()) buff += "\\e";
else buff += "\n\\e";
}
else buff += "\\e";
break;
case '\n':
if constexpr (SPLIT)
{
if (utf8.size() && utf8.front() == '\033')
{
buff += "\\n\n\\e";
utf8.remove_prefix(1);
}
else buff += "\\n\n";
}
else buff += "\\n\n";
break;
case '\r': buff += "\\r"; break;
case 8: buff += "\\b"; break;
case 9: buff += "\\t"; break;
default:
{
auto cp = traits.cdpoint;
if (cp < 0x100000) { buff += "\\u"; to_hex<true>(buff, cp, 4); }
else { buff += "\\U"; to_hex<true>(buff, cp, 8); }
}
}
return utf8;
};
auto y = [&](frag const& cluster)
{
if (cluster.text.front() == '\\') buff += "\\\\";
//else if (cluster.text.front() == ' ') buff += "\x20";
else buff += cluster.text;
};
decode<faux>(s, y, utf8);
return buff;
}
template<class ITER>
auto find_char(ITER head, ITER tail, char delim)
{
while (head != tail)
{
auto c = *head;
if (c == delim) break;
else if (c == '\\' && head != tail) ++head;
++head;
}
return head;
};
template<class P>
void trim_front_if(view& utf8, P pred)
{
auto head = utf8.begin();
auto tail = utf8.end();
while (head != tail)
{
auto c = *head;
if (pred(c)) break;
++head;
}
utf8.remove_prefix(std::distance(utf8.begin(), head));
};
void trim_front(view& utf8, view delims)
{
trim_front_if(utf8, [&](char c){ return delims.find(c) == text::npos; });
};
auto get_quote(view& utf8, char delim, view skip = {})
{
auto head = utf8.begin();
auto tail = utf8.end();
auto coor = find_char(head, tail, delim);
if (std::distance(coor, tail) < 2)
{
utf8 = view{};
return text{};
}
++coor;
auto stop = find_char(coor, tail, delim);
if (stop == tail)
{
utf8 = view{};
return text{};
}
utf8.remove_prefix(std::distance(head, stop) + 1);
text str{ coor, stop };
change(str, text{ "\\" } + delim, text{ 1, delim });
if (!skip.empty()) trim_front(utf8, skip);
return str;
};
template<class TEXT_or_VIEW>
auto is_plain(TEXT_or_VIEW&& utf8)
{
auto test = utf8.find('\033');
return test == text::npos;
}
}
#endif // NETXS_UTF_HPP | 32.277393 | 155 | 0.403446 | [
"vector"
] |
a811408b1bc9d1a513f91bb27d46458e71108539 | 1,287 | cpp | C++ | src/card_abstraction.cpp | bluedevils23/slumbot2019 | a1b65b84c89ab2eff9e2e0c16cedcfcbd479dffd | [
"MIT"
] | 80 | 2019-03-28T02:57:51.000Z | 2022-03-17T05:41:48.000Z | src/card_abstraction.cpp | bluedevils23/slumbot2019 | a1b65b84c89ab2eff9e2e0c16cedcfcbd479dffd | [
"MIT"
] | 19 | 2019-06-11T08:01:06.000Z | 2022-01-28T23:13:49.000Z | src/card_abstraction.cpp | bluedevils23/slumbot2019 | a1b65b84c89ab2eff9e2e0c16cedcfcbd479dffd | [
"MIT"
] | 28 | 2019-07-18T01:36:35.000Z | 2021-12-26T14:37:10.000Z | // Requires the Game object to have been initialized first.
#include <stdio.h>
#include <stdlib.h>
#include <memory>
#include <string>
#include <vector>
#include "card_abstraction.h"
#include "constants.h"
#include "files.h"
#include "game.h"
#include "io.h"
#include "params.h"
#include "split.h"
using std::string;
using std::unique_ptr;
using std::vector;
CardAbstraction::CardAbstraction(const Params ¶ms) {
card_abstraction_name_ = params.GetStringValue("CardAbstractionName");
Split(params.GetStringValue("Bucketings").c_str(), ',', false,
&bucketings_);
int max_street = Game::MaxStreet();
if ((int)bucketings_.size() < max_street + 1) {
fprintf(stderr, "Expected at least %i bucketings\n", max_street + 1);
exit(-1);
}
bucket_thresholds_.reset(new int[max_street + 1]);
if (params.IsSet("BucketThresholds")) {
vector<int> v;
ParseInts(params.GetStringValue("BucketThresholds"), &v);
if ((int)v.size() != max_street + 1) {
fprintf(stderr, "Expected %i values in BucketThresholds\n",
max_street + 1);
exit(-1);
}
for (int st = 0; st <= max_street; ++st) {
bucket_thresholds_[st] = v[st];
}
} else {
for (int st = 0; st <= max_street; ++st) {
bucket_thresholds_[st] = kMaxInt;
}
}
}
| 26.265306 | 73 | 0.658897 | [
"object",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.