hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6699f1c26ec120757725350b3486fceea61819c9 | 489 | cpp | C++ | chapter2/LinkList/practice/Search_K.cpp | verfallen/wang-dao | ac25e16010f675fa3cee9fe07de394d111ff61f5 | [
"MIT"
] | null | null | null | chapter2/LinkList/practice/Search_K.cpp | verfallen/wang-dao | ac25e16010f675fa3cee9fe07de394d111ff61f5 | [
"MIT"
] | null | null | null | chapter2/LinkList/practice/Search_K.cpp | verfallen/wang-dao | ac25e16010f675fa3cee9fe07de394d111ff61f5 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
/**
* 2.3节 21题
* 思路:定义p,q 两个指针 相差k,当p指向尾结点时,q指向倒数第k个结点
*/
typedef struct LNode
{
int data;
LNode *Link;
} LNode, *LinkList;
int Search_X(LinkList L, int k)
{
LNode *p = L->Link, *q;
int count = 0;
while (p != NULL)
{
if (count < k)
count++;
else
q = q->Link;
p = p->Link;
}
if (count < k)
return 0;
printf("%d", q->data);
return 1;
} | 13.971429 | 40 | 0.564417 | verfallen |
669c2a2a22e4a849d9f5328f1bcd57d44dee6cb1 | 1,167 | cpp | C++ | vbox/src/VBox/NetworkServices/Dhcpd/TimeStamp.cpp | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | vbox/src/VBox/NetworkServices/Dhcpd/TimeStamp.cpp | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | vbox/src/VBox/NetworkServices/Dhcpd/TimeStamp.cpp | Nurzamal/rest_api_docker | a9cc01dfc235467d490d9663755b33ef6990bdd8 | [
"MIT"
] | null | null | null | /* $Id: TimeStamp.cpp 70836 2018-01-31 14:55:44Z vboxsync $ */
/** @file
* DHCP server - timestamps
*/
/*
* Copyright (C) 2017-2018 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
#include "TimeStamp.h"
#include <iprt/string.h>
size_t TimeStamp::absStrFormat(PFNRTSTROUTPUT pfnOutput, void *pvArgOutput) const
{
RTTIMESPEC Spec;
getAbsTimeSpec(&Spec);
RTTIME Time;
RTTimeExplode(&Time, &Spec);
size_t cb = RTStrFormat(pfnOutput, pvArgOutput, NULL, 0,
"%RI32-%02u-%02uT%02u:%02u:%02uZ",
Time.i32Year, Time.u8Month, Time.u8MonthDay,
Time.u8Hour, Time.u8Minute, Time.u8Second);
return cb;
}
| 31.540541 | 81 | 0.666667 | Nurzamal |
669ec1ce9734b66f47aceae90ed46923043f9497 | 4,157 | hpp | C++ | stapl_release/stapl/runtime/immutable_shared.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/runtime/immutable_shared.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/runtime/immutable_shared.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_RUNTIME_IMMUTABLE_SHARED_HPP
#define STAPL_RUNTIME_IMMUTABLE_SHARED_HPP
#include "serialization.hpp"
#include "type_traits/is_basic.hpp"
#include "type_traits/is_copyable.hpp"
#include <memory>
#include <tuple>
#include <type_traits>
#include <utility>
namespace stapl {
//////////////////////////////////////////////////////////////////////
/// @brief Describes an immutable object.
///
/// @tparam T Object type.
///
/// Immutable objects may be passed by reference when communication happens in
/// shared memory. The object can never be mutated and it is deleted when the
/// last @ref immutable_shared is destroyed.
///
/// Locations that are on shared memory may have a single object accessible
/// through their @ref immutable_shared. Locations that are on different address
/// spaces are guaranteed to have distinct copies of the object.
///
/// @see immutable_wrapper
/// @ingroup ARMIUtilities
//////////////////////////////////////////////////////////////////////
template<typename T,
bool = (sizeof(T)<=sizeof(std::shared_ptr<T>) && is_basic<T>::value)>
class immutable_shared
{
public:
typedef T element_type;
private:
std::shared_ptr<const T> m_p;
public:
template<typename... Args>
explicit immutable_shared(Args&&... args)
: m_p(std::make_shared<const T>(std::forward<Args>(args)...))
{ }
immutable_shared(immutable_shared const&) = default;
immutable_shared(immutable_shared&&) = default;
operator T const&(void) const noexcept
{ return *m_p; }
T const& get(void) const noexcept
{ return *m_p; }
long use_count(void) const
{ return m_p.use_count(); }
bool unique(void) const
{ return m_p.unique(); }
void define_type(typer& t)
{ t.member(m_p); }
};
//////////////////////////////////////////////////////////////////////
/// @internal
/// @brief Specialization of @ref immutable_shared for basic types for which
/// <tt>sizeof(T)<=sizeof(std::shared_ptr<T>)</tt>.
///
/// @ingroup ARMIUtilities
//////////////////////////////////////////////////////////////////////
template<typename T>
class immutable_shared<T, true>
{
public:
typedef const T element_type;
typedef std::tuple<T> member_types;
private:
T m_t;
public:
template<typename... Args>
explicit immutable_shared(Args&&... args)
: m_t(std::forward<Args>(args)...)
{ }
immutable_shared(immutable_shared const&) = default;
immutable_shared(immutable_shared&&) = default;
operator T const&(void) const noexcept
{ return m_t; }
T const& get(void) const noexcept
{ return m_t; }
constexpr long use_count(void) const noexcept
{ return 1l; }
constexpr bool unique(void) const noexcept
{ return true; }
};
//////////////////////////////////////////////////////////////////////
/// @brief Constructs an immutable object of type @p T.
///
/// Immutable objects may be passed by reference when communication happens in
/// shared memory.
///
/// The object can never be mutated and it is deleted when the last
/// @ref immutable_shared is destroyed.
///
/// @see immutable
/// @related immutable_shared
/// @ingroup ARMIUtilities
//////////////////////////////////////////////////////////////////////
template<typename T, typename... Args>
immutable_shared<T> make_immutable_shared(Args&&... args)
{
return immutable_shared<T>(std::forward<Args>(args)...);
}
namespace runtime {
////////////////////////////////////////////////////////////////////
/// @internal
/// @brief Specialization of @ref is_copyable for @ref immutable_shared.
///
/// @ingroup runtimeTypeTraits
////////////////////////////////////////////////////////////////////
template<typename T>
struct is_copyable<immutable_shared<T, false>>
: public std::true_type
{ };
} // namespace runtime
} // namespace stapl
#endif
| 26.647436 | 80 | 0.620159 | parasol-ppl |
66a1909d52bf9cd1f3642a73ab453ebaa4e5ef9f | 3,384 | cpp | C++ | src/cube/src/syntax/cubepl/CubePL0Driver.cpp | OpenCMISS-Dependencies/cube | bb425e6f75ee5dbdf665fa94b241b48deee11505 | [
"Cube"
] | null | null | null | src/cube/src/syntax/cubepl/CubePL0Driver.cpp | OpenCMISS-Dependencies/cube | bb425e6f75ee5dbdf665fa94b241b48deee11505 | [
"Cube"
] | null | null | null | src/cube/src/syntax/cubepl/CubePL0Driver.cpp | OpenCMISS-Dependencies/cube | bb425e6f75ee5dbdf665fa94b241b48deee11505 | [
"Cube"
] | 2 | 2016-09-19T00:16:05.000Z | 2021-03-29T22:06:45.000Z | /****************************************************************************
** CUBE http://www.scalasca.org/ **
*****************************************************************************
** Copyright (c) 1998-2016 **
** Forschungszentrum Juelich GmbH, Juelich Supercomputing Centre **
** **
** Copyright (c) 2009-2015 **
** German Research School for Simulation Sciences GmbH, **
** Laboratory for Parallel Programming **
** **
** This software may be modified and distributed under the terms of **
** a BSD-style license. See the COPYING file in the package base **
** directory for details. **
****************************************************************************/
#ifndef __CUBEPL0_DRIVER_CPP
#define __CUBEPL0_DRIVER_CPP 0
#include <vector>
#include <iostream>
#include <sstream>
#include <float.h>
#include <cmath>
#include "CubeTypes.h"
#include "CubeSysres.h"
#include "CubeLocation.h"
#include "CubeLocationGroup.h"
#include "CubeSystemTreeNode.h"
#include "CubePL0Driver.h"
#include "CubePL0Parser.h"
#include "CubePL0Scanner.h"
#include "CubePL0ParseContext.h"
#include "CubePL0MemoryManager.h"
using namespace std;
using namespace cube;
using namespace cubeplparser;
// cube::CubePL0MemoryManager cubepl_memory_manager;
CubePL0Driver::CubePL0Driver( Cube* _cube ) : CubePLDriver( _cube )
{
};
CubePL0Driver::~CubePL0Driver()
{
};
GeneralEvaluation*
CubePL0Driver::compile( istream* strin, ostream* errs )
{
// stringstream strin(cubepl_program);
CubePL0ParseContext* parseContext = new CubePL0ParseContext( cube );
cubeplparser::CubePL0Scanner* lexer = new cubeplparser::CubePL0Scanner( strin, errs, parseContext );
cubeplparser::CubePL0Parser* parser = new cubeplparser::CubePL0Parser( *parseContext, *lexer );
parser->parse();
GeneralEvaluation* formula = parseContext->result;
delete lexer;
delete parser;
delete parseContext;
return formula;
};
bool
CubePL0Driver::test( std::string& cubepl_program, std::string& error_message )
{
stringstream strin( cubepl_program );
stringstream ssout;
CubePL0ParseContext* parseContext = new CubePL0ParseContext( NULL, true );
cubeplparser::CubePL0Scanner* lexer = new cubeplparser::CubePL0Scanner( &strin, &ssout, parseContext );
cubeplparser::CubePL0Parser* parser = new cubeplparser::CubePL0Parser( *parseContext, *lexer );
parser->parse();
string error_output;
ssout >> error_output;
bool _ok = parseContext->syntax_ok;
if ( error_output.length() != 0 )
{
_ok = false;
parseContext->error_message = "CubePL0Scanner cannot recognize token: " + error_output;
}
if ( !_ok )
{
error_message = parseContext->error_message;
}
delete parseContext->result;
delete lexer;
delete parser;
delete parseContext;
return _ok;
}
std::string
CubePL0Driver::printStatus()
{
return "OK";
};
#endif
| 28.677966 | 114 | 0.568262 | OpenCMISS-Dependencies |
66a4b30447dfe20b2fab17a11a44a32c5e02122c | 2,381 | cpp | C++ | src/kitchen.cpp | skvark/JuveFood | fed694f93ca2998a3cf77f0d83e246bb272ffcbf | [
"MIT"
] | 1 | 2015-02-05T20:00:04.000Z | 2015-02-05T20:00:04.000Z | src/kitchen.cpp | skvark/JuveFood | fed694f93ca2998a3cf77f0d83e246bb272ffcbf | [
"MIT"
] | null | null | null | src/kitchen.cpp | skvark/JuveFood | fed694f93ca2998a3cf77f0d83e246bb272ffcbf | [
"MIT"
] | 1 | 2019-07-03T12:13:37.000Z | 2019-07-03T12:13:37.000Z | #include "kitchen.h"
#include <QDebug>
Kitchen::Kitchen(unsigned int kitchenId,
unsigned int kitchenInfoId,
unsigned int openInfoId,
unsigned int menuTypeId,
QString name,
QString shortName):
kitchenId_(kitchenId),
kitchenInfoId_(kitchenInfoId),
openInfoId_(openInfoId),
menuTypeId_(menuTypeId),
name_(name),
shortName_(shortName)
{}
QString Kitchen::getKitchenName()
{
return name_;
}
QString Kitchen::getShortName()
{
return shortName_;
}
QString Kitchen::getOpeningHours()
{
if(openingHours_.length() > 2) {
return openingHours_;
} else {
return QString("No data available.");
}
}
void Kitchen::setOpeningHours(QString hours)
{
openingHours_ = hours;
}
QList<QPair<QString, QString> > Kitchen::getByWeekdayQuery(QString lang, QDate date)
{
// format:
// GetMenuByWeekday?KitchenId=6&MenuTypeId=60&Week=50&Weekday=3&lang='fi'&format=json
QList<QPair<QString, QString> > query;
QString language = "Finnish";
if(QString::compare(lang, language) == 0) {
language = "'fi'";
} else {
language = "'en'";
}
// Add query components to a list
query.append(qMakePair(QString("KitchenId"), QString::number(kitchenId_, 10)));
query.append(qMakePair(QString("MenuTypeId"), QString::number(menuTypeId_, 10)));
query.append(qMakePair(QString("Week"), QString::number(date.weekNumber(), 10)));
query.append(qMakePair(QString("Weekday"), QString::number(date.dayOfWeek(), 10)));
// Debug for specific day and week
// query.append(qMakePair(QString("Week"), QString("7")));
// query.append(qMakePair(QString("Weekday"), QString("7")));
query.append(qMakePair(QString("lang"), language));
query.append(qMakePair(QString("format"), QString("json")));
return query;
}
QList<QPair<QString, QString> > Kitchen::getKitchenInfoQuery()
{
// format:
// GetKitchenInfo?KitchenInfoId=2360&format=json
QList<QPair<QString, QString> > query;
query.append(qMakePair(QString("KitchenInfoId"), QString::number(openInfoId_, 10)));
query.append(qMakePair(QString("format"), QString("json")));
query.append(qMakePair(QString("lang"), QString("'fi'")));
return query;
}
| 29.7625 | 89 | 0.636287 | skvark |
66a5894397b27f269470b3163bf8479836b1ba61 | 169 | cpp | C++ | Spades Game/Game/CardView/CardEventListener.cpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 6 | 2017-01-04T22:40:50.000Z | 2019-11-24T15:37:46.000Z | Spades Game/Game/CardView/CardEventListener.cpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 1 | 2016-09-18T19:10:01.000Z | 2017-08-04T23:53:38.000Z | Spades Game/Game/CardView/CardEventListener.cpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 2 | 2015-11-21T16:42:18.000Z | 2019-04-21T20:41:39.000Z | #include "Game/CardView/CardEventListener.hpp"
namespace cge
{
CardEventListener::CardEventListener(void)
{
}
CardEventListener::~CardEventListener(void)
{
}
}
| 12.071429 | 46 | 0.751479 | jmasterx |
66a8770cc6fdb72f5d207cc282d3b380fd2a58e4 | 573 | cpp | C++ | main/libs/common/src/network.cpp | ttgc/ThunderSiege6-Chat | 1a1601c2d18429baadc3b6d3d0f9b1354246c1f1 | [
"MIT"
] | null | null | null | main/libs/common/src/network.cpp | ttgc/ThunderSiege6-Chat | 1a1601c2d18429baadc3b6d3d0f9b1354246c1f1 | [
"MIT"
] | null | null | null | main/libs/common/src/network.cpp | ttgc/ThunderSiege6-Chat | 1a1601c2d18429baadc3b6d3d0f9b1354246c1f1 | [
"MIT"
] | null | null | null | #include <algorithm>
#include "network.hpp"
namespace network
{
void setNonBlockingSocket(SOCKET& s)
{
#ifdef _WIN32
u_long nonBlocking = 1;
ioctlsocket(s, FIONBIO, &nonBlocking);
#else // _WIN32
int flags = fcntl(s, F_GETFL, 0);
flags = (flags | O_NONBLOCK);
fcntl(s, F_SETFL, flags);
#endif // _WIN32
}
int getNfds(const std::vector<SOCKET>& sockets)
{
#ifdef _WIN32
return 0;
#else // _WIN32
auto maxs = std::max_element(sockets.begin(), sockets.end());
return (maxs != sockets.end()) ? *maxs : 0;
#endif // _WIN32
}
}
| 20.464286 | 64 | 0.636998 | ttgc |
66a9d84797a5a1b2f533c3b2e2e47d8de382191d | 8,405 | cc | C++ | CCA/Components/Arches/PropertyModelsV2/CCVel.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | 3 | 2020-06-10T08:21:31.000Z | 2020-06-23T18:33:16.000Z | CCA/Components/Arches/PropertyModelsV2/CCVel.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | null | null | null | CCA/Components/Arches/PropertyModelsV2/CCVel.cc | QuocAnh90/Uintah_Aalto | 802c236c331b7eb705d408c352969037e4c5b153 | [
"MIT"
] | 2 | 2019-12-30T05:48:30.000Z | 2020-02-12T16:24:16.000Z | #include <CCA/Components/Arches/PropertyModelsV2/CCVel.h>
#include <CCA/Components/Arches/UPSHelper.h>
using namespace Uintah;
using namespace ArchesCore;
//--------------------------------------------------------------------------------------------------
CCVel::CCVel( std::string task_name, int matl_index ) :
TaskInterface( task_name, matl_index ){}
//--------------------------------------------------------------------------------------------------
CCVel::~CCVel(){}
//--------------------------------------------------------------------------------------------------
void CCVel::problemSetup( ProblemSpecP& db ){
using namespace Uintah::ArchesCore;
m_u_vel_name = parse_ups_for_role( UVELOCITY, db, ArchesCore::default_uVel_name );
m_v_vel_name = parse_ups_for_role( VVELOCITY, db, ArchesCore::default_vVel_name );
m_w_vel_name = parse_ups_for_role( WVELOCITY, db, ArchesCore::default_wVel_name );
m_u_vel_name_cc = m_u_vel_name + "_cc";
m_v_vel_name_cc = m_v_vel_name + "_cc";
m_w_vel_name_cc = m_w_vel_name + "_cc";
m_int_scheme = ArchesCore::get_interpolant_from_string( "second" ); //default second order
m_ghost_cells = 1; //default for 2nd order
if ( db->findBlock("KMomentum") ){
if (db->findBlock("KMomentum")->findBlock("convection")){
std::string conv_scheme;
db->findBlock("KMomentum")->findBlock("convection")->getAttribute("scheme", conv_scheme);
if (conv_scheme == "fourth"){
m_ghost_cells=2;
m_int_scheme = ArchesCore::get_interpolant_from_string( conv_scheme );
}
}
}
if ( db->findBlock("TurbulenceModels")){
if ( db->findBlock("TurbulenceModels")->findBlock("model")){
std::string turb_closure_model;
std::string conv_scheme;
db->findBlock("TurbulenceModels")->findBlock("model")->getAttribute("type", turb_closure_model);
if ( turb_closure_model == "multifractal" ){
if (db->findBlock("KMomentum")->findBlock("convection")){
std::stringstream msg;
msg << "ERROR: Cannot use KMomentum->convection if you are using the multifracal nles closure." << std::endl;
throw InvalidValue(msg.str(),__FILE__,__LINE__);
} else {
m_ghost_cells=2;
conv_scheme="fourth";
m_int_scheme = ArchesCore::get_interpolant_from_string( conv_scheme );
}
}
}
}
}
//--------------------------------------------------------------------------------------------------
void CCVel::create_local_labels(){
register_new_variable<CCVariable<double> >( m_u_vel_name_cc);
register_new_variable<CCVariable<double> >( m_v_vel_name_cc);
register_new_variable<CCVariable<double> >( m_w_vel_name_cc);
}
//--------------------------------------------------------------------------------------------------
void CCVel::register_initialize( AVarInfo& variable_registry , const bool pack_tasks){
typedef ArchesFieldContainer AFC;
register_variable( m_u_vel_name, AFC::REQUIRES,m_ghost_cells , AFC::NEWDW, variable_registry, m_task_name );
register_variable( m_v_vel_name, AFC::REQUIRES,m_ghost_cells , AFC::NEWDW, variable_registry, m_task_name );
register_variable( m_w_vel_name, AFC::REQUIRES,m_ghost_cells , AFC::NEWDW, variable_registry, m_task_name );
register_variable( m_u_vel_name_cc, AFC::COMPUTES, variable_registry, m_task_name );
register_variable( m_v_vel_name_cc, AFC::COMPUTES, variable_registry, m_task_name );
register_variable( m_w_vel_name_cc, AFC::COMPUTES, variable_registry, m_task_name );
}
//--------------------------------------------------------------------------------------------------
void CCVel::initialize( const Patch* patch, ArchesTaskInfoManager* tsk_info ){
compute_velocities( patch, tsk_info );
}
//--------------------------------------------------------------------------------------------------
void CCVel::register_timestep_init( AVarInfo& variable_registry , const bool pack_tasks){
typedef ArchesFieldContainer AFC;
register_variable( m_u_vel_name_cc, AFC::COMPUTES, variable_registry, m_task_name );
register_variable( m_v_vel_name_cc, AFC::COMPUTES, variable_registry, m_task_name );
register_variable( m_w_vel_name_cc, AFC::COMPUTES, variable_registry, m_task_name );
register_variable( m_u_vel_name_cc, AFC::REQUIRES, 0, AFC::OLDDW, variable_registry, m_task_name );
register_variable( m_v_vel_name_cc, AFC::REQUIRES, 0, AFC::OLDDW, variable_registry, m_task_name );
register_variable( m_w_vel_name_cc, AFC::REQUIRES, 0, AFC::OLDDW, variable_registry, m_task_name );
}
//--------------------------------------------------------------------------------------------------
void CCVel::timestep_init( const Patch* patch, ArchesTaskInfoManager* tsk_info ){
constCCVariable<double>& old_u_cc = tsk_info->get_const_uintah_field_add<constCCVariable<double> >(m_u_vel_name_cc);
constCCVariable<double>& old_v_cc = tsk_info->get_const_uintah_field_add<constCCVariable<double> >(m_v_vel_name_cc);
constCCVariable<double>& old_w_cc = tsk_info->get_const_uintah_field_add<constCCVariable<double> >(m_w_vel_name_cc);
CCVariable<double>& u_cc = tsk_info->get_uintah_field_add<CCVariable<double> >(m_u_vel_name_cc);
CCVariable<double>& v_cc = tsk_info->get_uintah_field_add<CCVariable<double> >(m_v_vel_name_cc);
CCVariable<double>& w_cc = tsk_info->get_uintah_field_add<CCVariable<double> >(m_w_vel_name_cc);
u_cc.copy(old_u_cc);
v_cc.copy(old_v_cc);
w_cc.copy(old_w_cc);
}
//--------------------------------------------------------------------------------------------------
void CCVel::register_timestep_eval( VIVec& variable_registry, const int time_substep , const bool packed_tasks){
typedef ArchesFieldContainer AFC;
register_variable( m_u_vel_name, AFC::REQUIRES, m_ghost_cells, AFC::NEWDW, variable_registry, time_substep ,m_task_name );
register_variable( m_v_vel_name, AFC::REQUIRES, m_ghost_cells, AFC::NEWDW, variable_registry, time_substep ,m_task_name );
register_variable( m_w_vel_name, AFC::REQUIRES, m_ghost_cells, AFC::NEWDW, variable_registry, time_substep ,m_task_name );
register_variable( m_u_vel_name_cc, AFC::MODIFIES, variable_registry, time_substep , m_task_name );
register_variable( m_v_vel_name_cc, AFC::MODIFIES, variable_registry, time_substep , m_task_name );
register_variable( m_w_vel_name_cc, AFC::MODIFIES, variable_registry, time_substep , m_task_name );
}
//--------------------------------------------------------------------------------------------------
void CCVel::eval( const Patch* patch, ArchesTaskInfoManager* tsk_info ){
compute_velocities( patch, tsk_info );
}
//--------------------------------------------------------------------------------------------------
void CCVel::compute_velocities( const Patch* patch, ArchesTaskInfoManager* tsk_info ){
constSFCXVariable<double>& u = tsk_info->get_const_uintah_field_add<constSFCXVariable<double> >(m_u_vel_name);
constSFCYVariable<double>& v = tsk_info->get_const_uintah_field_add<constSFCYVariable<double> >(m_v_vel_name);
constSFCZVariable<double>& w = tsk_info->get_const_uintah_field_add<constSFCZVariable<double> >(m_w_vel_name);
CCVariable<double>& u_cc = tsk_info->get_uintah_field_add<CCVariable<double> >(m_u_vel_name_cc);
CCVariable<double>& v_cc = tsk_info->get_uintah_field_add<CCVariable<double> >(m_v_vel_name_cc);
CCVariable<double>& w_cc = tsk_info->get_uintah_field_add<CCVariable<double> >(m_w_vel_name_cc);
u_cc.initialize(0.0);
v_cc.initialize(0.0);
w_cc.initialize(0.0);
Uintah::BlockRange range( patch->getCellLowIndex(), patch->getCellHighIndex() );
ArchesCore::OneDInterpolator my_interpolant_centerx(u_cc, u , 1, 0, 0 );
ArchesCore::OneDInterpolator my_interpolant_centery(v_cc, v , 0, 1, 0 );
ArchesCore::OneDInterpolator my_interpolant_centerz(w_cc, w , 0, 0, 1 );
if ( m_int_scheme == ArchesCore::SECONDCENTRAL ) {
ArchesCore::SecondCentral ci;
Uintah::parallel_for( range, my_interpolant_centerx, ci );
Uintah::parallel_for( range, my_interpolant_centery, ci );
Uintah::parallel_for( range, my_interpolant_centerz, ci );
} else if ( m_int_scheme== ArchesCore::FOURTHCENTRAL ){
ArchesCore::FourthCentral ci;
Uintah::parallel_for( range, my_interpolant_centerx, ci );
Uintah::parallel_for( range, my_interpolant_centery, ci );
Uintah::parallel_for( range, my_interpolant_centerz, ci );
}
}
| 46.181319 | 124 | 0.657228 | QuocAnh90 |
66abaeb0cd6e5f14cecc43cc598ea64f44436c40 | 2,501 | cpp | C++ | Game/Source/EntityManager.cpp | Hydeon-git/Project2_RPG | bed3f6ba412b4f533d6b8c9e401182259fcb43e5 | [
"MIT"
] | 4 | 2021-02-23T20:18:27.000Z | 2021-04-17T22:43:01.000Z | Game/Source/EntityManager.cpp | Hydeon-git/Project2_RPG | bed3f6ba412b4f533d6b8c9e401182259fcb43e5 | [
"MIT"
] | 1 | 2021-02-25T11:10:11.000Z | 2021-02-25T11:10:11.000Z | Game/Source/EntityManager.cpp | Hydeon-git/Project2_RPG | bed3f6ba412b4f533d6b8c9e401182259fcb43e5 | [
"MIT"
] | null | null | null | #include "EntityManager.h"
#include "Player.h"
#include "Enemy.h"
#include "FlyingEnemy.h"
#include "NPC1.h"
#include "NPC2.h"
#include "NPC3.h"
#include "NPC4.h"
#include "NPC5.h"
#include "Enemy1.h"
#include "Enemy2.h"
#include "Enemy3.h"
#include "ModuleParticles.h"
#include "App.h"
#include "Scene.h"
#include "Defs.h"
#include "Log.h"
EntityManager::EntityManager() : Module()
{
name.Create("entitymanager");
}
// Destructor
EntityManager::~EntityManager()
{}
// Called before render is available
bool EntityManager::Awake(pugi::xml_node& config)
{
LOG("Loading Entity Manager");
bool ret = true;
return ret;
}
// Called before quitting
bool EntityManager::CleanUp()
{
if (!active) return true;
return true;
}
Entity* EntityManager::CreateEntity(EntityType type)
{
Entity* ret = nullptr;
switch (type)
{
// L13: Create the corresponding type entity
case EntityType::NPC5: ret = new NPC5(); break;
case EntityType::PLAYER: ret = new Player(); break;
case EntityType::ENEMY: ret = new Enemy(); break;
case EntityType::FLYING_ENEMY: ret = new FlyingEnemy(); break;
case EntityType::PARTICLE: ret = new ModuleParticles(); break;
case EntityType::NPC1: ret = new NPC1(); break;
case EntityType::NPC2: ret = new NPC2(); break;
case EntityType::NPC3: ret = new NPC3(); break;
case EntityType::NPC4: ret = new NPC4(); break;
case EntityType::Enemy1: ret = new Enemy1(); break;
case EntityType::Enemy2: ret = new Enemy2(); break;
case EntityType::Enemy3: ret = new Enemy3(); break;
//case EntityType::ITEM: ret = new Item(); break;
default: break;
}
// Created entities are added to the list
if (ret != nullptr) entities.Add(ret);
return ret;
}
void EntityManager::DestroyEntity(Entity* entity)
{
ListItem <Entity*>* item = entities.start;
while (item != nullptr)
{
if (item->data == entity)
{
entities.Del(item);
break;
}
item = item->next;
}
}
bool EntityManager::PreUpdate()
{
bool ret = true;
ListItem<Entity*>* item = entities.start;
while ((item != nullptr))
{
ret = item->data->PreUpdate();
item = item->next;
}
return ret;
}
bool EntityManager::Update(float dt)
{
if (!app->scene->paused)
{
for (unsigned int i = 0; i < entities.Count(); i++)
{
entities.At(i)->data->Update(dt);
}
}
return true;
}
bool EntityManager::PostUpdate()
{
ListItem<Entity*>* item = entities.start;
while ((item != nullptr))
{
item->data->PostUpdate();
item = item->next;
}
return true;
}
| 18.804511 | 65 | 0.664534 | Hydeon-git |
66ac5ad2a9bea6ff2347c86d4ff84c82f4ae94f8 | 32,689 | cpp | C++ | TAO/tao/PortableServer/Active_Object_Map.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 36 | 2015-01-10T07:27:33.000Z | 2022-03-07T03:32:08.000Z | TAO/tao/PortableServer/Active_Object_Map.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 2 | 2018-08-13T07:30:51.000Z | 2019-02-25T03:04:31.000Z | TAO/tao/PortableServer/Active_Object_Map.cpp | cflowe/ACE | 5ff60b41adbe1772372d1a43bcc1f2726ff8f810 | [
"DOC"
] | 38 | 2015-01-08T14:12:06.000Z | 2022-01-19T08:33:00.000Z | // $Id: Active_Object_Map.cpp 96992 2013-04-11 18:07:48Z huangh $
#include "tao/PortableServer/Active_Object_Map.h"
#include "tao/PortableServer/Active_Object_Map_Entry.h"
#if !defined (__ACE_INLINE__)
# include "tao/PortableServer/Active_Object_Map.inl"
#endif /* __ACE_INLINE__ */
#include "tao/SystemException.h"
#include "ace/Auto_Ptr.h"
#include "ace/CORBA_macros.h"
#include "tao/debug.h"
#include "PortableServer_Functions.h"
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
/* static */
size_t TAO_Active_Object_Map::system_id_size_ = 0;
static void
hexstring (ACE_CString& hexstr, const char* s, size_t l)
{
char buf[3] = {0};
hexstr.fast_resize (2 + l * 2);
hexstr.append ("0x", 2);
while (--l)
{
ACE_OS::sprintf (buf, "%02x", (unsigned int)(unsigned char)*s);
hexstr.append (buf, 2);
++s;
}
}
void
TAO_Active_Object_Map::set_system_id_size (
const TAO_Server_Strategy_Factory::Active_Object_Map_Creation_Parameters &creation_parameters)
{
if (TAO_Active_Object_Map::system_id_size_ == 0)
{
if (creation_parameters.allow_reactivation_of_system_ids_)
{
switch (creation_parameters.object_lookup_strategy_for_system_id_policy_)
{
#if (TAO_HAS_MINIMUM_POA_MAPS == 0)
case TAO_LINEAR:
TAO_Active_Object_Map::system_id_size_ = sizeof (CORBA::ULong);
break;
#endif /* TAO_HAS_MINIMUM_POA_MAPS == 0 */
case TAO_DYNAMIC_HASH:
default:
TAO_Active_Object_Map::system_id_size_ = sizeof (CORBA::ULong);
break;
}
size_t hint_size = 0;
if (creation_parameters.use_active_hint_in_ids_)
hint_size = ACE_Active_Map_Manager_Key::size ();
TAO_Active_Object_Map::system_id_size_ += hint_size;
}
else
{
switch (creation_parameters.object_lookup_strategy_for_system_id_policy_)
{
#if (TAO_HAS_MINIMUM_POA_MAPS == 0)
case TAO_LINEAR:
TAO_Active_Object_Map::system_id_size_ = sizeof (CORBA::ULong);
break;
case TAO_DYNAMIC_HASH:
TAO_Active_Object_Map::system_id_size_ = sizeof (CORBA::ULong);
break;
#endif /* TAO_HAS_MINIMUM_POA_MAPS == 0 */
case TAO_ACTIVE_DEMUX:
default:
TAO_Active_Object_Map::system_id_size_ =
ACE_Active_Map_Manager_Key::size ();
break;
}
}
}
}
TAO_Active_Object_Map::TAO_Active_Object_Map (
int user_id_policy,
int unique_id_policy,
int persistent_id_policy,
const TAO_Server_Strategy_Factory::Active_Object_Map_Creation_Parameters &
creation_parameters)
: user_id_map_ (0)
, servant_map_ (0)
, id_uniqueness_strategy_ (0)
, lifespan_strategy_ (0)
, id_assignment_strategy_ (0)
, id_hint_strategy_ (0)
, using_active_maps_ (false)
{
TAO_Active_Object_Map::set_system_id_size (creation_parameters);
TAO_Id_Uniqueness_Strategy *id_uniqueness_strategy = 0;
if (unique_id_policy)
{
ACE_NEW_THROW_EX (id_uniqueness_strategy,
TAO_Unique_Id_Strategy,
CORBA::NO_MEMORY ());
}
else
{
#if !defined (CORBA_E_MICRO)
ACE_NEW_THROW_EX (id_uniqueness_strategy,
TAO_Multiple_Id_Strategy,
CORBA::NO_MEMORY ());
#else
TAOLIB_ERROR ((LM_ERROR,
"Multiple Id Strategy not supported with CORBA/e\n"));
#endif
}
// Give ownership to the auto pointer.
auto_ptr<TAO_Id_Uniqueness_Strategy>
new_id_uniqueness_strategy (id_uniqueness_strategy);
TAO_Lifespan_Strategy *lifespan_strategy = 0;
if (persistent_id_policy)
{
#if !defined (CORBA_E_MICRO)
ACE_NEW_THROW_EX (lifespan_strategy,
TAO_Persistent_Strategy,
CORBA::NO_MEMORY ());
#else
ACE_UNUSED_ARG (persistent_id_policy);
TAOLIB_ERROR ((LM_ERROR,
"Persistent Id Strategy not supported with CORBA/e\n"));
#endif
}
else
{
ACE_NEW_THROW_EX (lifespan_strategy,
TAO_Transient_Strategy,
CORBA::NO_MEMORY ());
}
// Give ownership to the auto pointer.
auto_ptr<TAO_Lifespan_Strategy> new_lifespan_strategy (lifespan_strategy);
TAO_Id_Assignment_Strategy *id_assignment_strategy = 0;
if (user_id_policy)
{
#if !defined (CORBA_E_MICRO)
ACE_NEW_THROW_EX (id_assignment_strategy,
TAO_User_Id_Strategy,
CORBA::NO_MEMORY ());
#else
TAOLIB_ERROR ((LM_ERROR,
"User Id Assignment not supported with CORBA/e\n"));
#endif
}
else if (unique_id_policy)
{
ACE_NEW_THROW_EX (id_assignment_strategy,
TAO_System_Id_With_Unique_Id_Strategy,
CORBA::NO_MEMORY ());
}
else
{
#if !defined (CORBA_E_MICRO)
ACE_NEW_THROW_EX (id_assignment_strategy,
TAO_System_Id_With_Multiple_Id_Strategy,
CORBA::NO_MEMORY ());
#else
TAOLIB_ERROR ((LM_ERROR,
"System Id Assignment with multiple "
"not supported with CORBA/e\n"));
#endif
}
// Give ownership to the auto pointer.
auto_ptr<TAO_Id_Assignment_Strategy>
new_id_assignment_strategy (id_assignment_strategy);
TAO_Id_Hint_Strategy *id_hint_strategy = 0;
if ((user_id_policy
|| creation_parameters.allow_reactivation_of_system_ids_)
&& creation_parameters.use_active_hint_in_ids_)
{
this->using_active_maps_ = true;
ACE_NEW_THROW_EX (id_hint_strategy,
TAO_Active_Hint_Strategy (
creation_parameters.active_object_map_size_),
CORBA::NO_MEMORY ());
}
else
{
ACE_NEW_THROW_EX (id_hint_strategy,
TAO_No_Hint_Strategy,
CORBA::NO_MEMORY ());
}
// Give ownership to the auto pointer.
auto_ptr<TAO_Id_Hint_Strategy> new_id_hint_strategy (id_hint_strategy);
servant_map *sm = 0;
if (unique_id_policy)
{
switch (creation_parameters.reverse_object_lookup_strategy_for_unique_id_policy_)
{
case TAO_LINEAR:
#if (TAO_HAS_MINIMUM_POA_MAPS == 0)
ACE_NEW_THROW_EX (sm,
servant_linear_map (
creation_parameters.active_object_map_size_),
CORBA::NO_MEMORY ());
break;
#else
TAOLIB_ERROR ((LM_ERROR,
"linear option for "
"-ORBUniqueidPolicyReverseDemuxStrategy "
"not supported with minimum POA maps. "
"Ingoring option to use default...\n"));
/* FALL THROUGH */
#endif /* TAO_HAS_MINIMUM_POA_MAPS == 0 */
case TAO_DYNAMIC_HASH:
default:
ACE_NEW_THROW_EX (sm,
servant_hash_map (
creation_parameters.active_object_map_size_),
CORBA::NO_MEMORY ());
break;
}
}
// Give ownership to the auto pointer.
auto_ptr<servant_map> new_servant_map (sm);
user_id_map *uim = 0;
if (user_id_policy
|| creation_parameters.allow_reactivation_of_system_ids_)
{
switch (creation_parameters.object_lookup_strategy_for_user_id_policy_)
{
case TAO_LINEAR:
#if (TAO_HAS_MINIMUM_POA_MAPS == 0)
ACE_NEW_THROW_EX (uim,
user_id_linear_map (
creation_parameters.active_object_map_size_),
CORBA::NO_MEMORY ());
break;
#else
TAOLIB_ERROR ((LM_ERROR,
"linear option for -ORBUseridPolicyDemuxStrategy "
"not supported with minimum POA maps. "
"Ingoring option to use default...\n"));
/* FALL THROUGH */
#endif /* TAO_HAS_MINIMUM_POA_MAPS == 0 */
case TAO_DYNAMIC_HASH:
default:
ACE_NEW_THROW_EX (uim,
user_id_hash_map (creation_parameters.active_object_map_size_),
CORBA::NO_MEMORY ());
break;
}
}
else
{
switch (creation_parameters.object_lookup_strategy_for_system_id_policy_)
{
#if (TAO_HAS_MINIMUM_POA_MAPS == 0)
case TAO_LINEAR:
ACE_NEW_THROW_EX (uim,
user_id_linear_map (creation_parameters.active_object_map_size_),
CORBA::NO_MEMORY ());
break;
case TAO_DYNAMIC_HASH:
ACE_NEW_THROW_EX (uim,
user_id_hash_map (creation_parameters.active_object_map_size_),
CORBA::NO_MEMORY ());
break;
#else
case TAO_LINEAR:
case TAO_DYNAMIC_HASH:
TAOLIB_ERROR ((LM_ERROR,
"linear and dynamic options for -ORBSystemidPolicyDemuxStrategy "
"are not supported with minimum POA maps. "
"Ingoring option to use default...\n"));
/* FALL THROUGH */
#endif /* TAO_HAS_MINIMUM_POA_MAPS == 0 */
case TAO_ACTIVE_DEMUX:
default:
this->using_active_maps_ = true;
ACE_NEW_THROW_EX (uim,
user_id_active_map (creation_parameters.active_object_map_size_),
CORBA::NO_MEMORY ());
break;
}
}
// Give ownership to the auto pointer.
auto_ptr<user_id_map> new_user_id_map (uim);
id_uniqueness_strategy->set_active_object_map (this);
lifespan_strategy->set_active_object_map (this);
id_assignment_strategy->set_active_object_map (this);
// Finally everything is fine. Make sure to take ownership away
// from the auto pointer.
this->id_uniqueness_strategy_ = new_id_uniqueness_strategy;
this->lifespan_strategy_ = new_lifespan_strategy;
this->id_assignment_strategy_ = new_id_assignment_strategy;
this->id_hint_strategy_ = new_id_hint_strategy;
this->servant_map_ = new_servant_map;
this->user_id_map_ = new_user_id_map;
#if defined (TAO_HAS_MONITOR_POINTS) && (TAO_HAS_MONITOR_POINTS == 1)
ACE_NEW (this->monitor_,
ACE::Monitor_Control::Size_Monitor);
#endif /* TAO_HAS_MONITOR_POINTS==1 */
}
TAO_Active_Object_Map::~TAO_Active_Object_Map (void)
{
user_id_map::iterator iterator = this->user_id_map_->begin ();
user_id_map::iterator end = this->user_id_map_->end ();
for (;
iterator != end;
++iterator)
{
user_id_map::value_type map_entry = *iterator;
delete map_entry.second ();
}
#if defined (TAO_HAS_MONITOR_POINTS) && (TAO_HAS_MONITOR_POINTS == 1)
this->monitor_->remove_from_registry ();
this->monitor_->remove_ref ();
#endif /* TAO_HAS_MONITOR_POINTS==1 */
}
bool
TAO_Active_Object_Map::is_user_id_in_map (
const PortableServer::ObjectId &user_id,
CORBA::Short priority,
bool &priorities_match,
bool &deactivated)
{
TAO_Active_Object_Map_Entry *entry = 0;
bool result = false;
int const find_result = this->user_id_map_->find (user_id, entry);
if (find_result == 0)
{
if (entry->servant_ == 0)
{
if (entry->priority_ != priority)
{
priorities_match = false;
}
}
else
{
result = true;
if (entry->deactivated_)
{
deactivated = true;
}
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
TAO_Id_Uniqueness_Strategy::~TAO_Id_Uniqueness_Strategy (void)
{
}
void
TAO_Id_Uniqueness_Strategy::set_active_object_map (
TAO_Active_Object_Map *active_object_map)
{
this->active_object_map_ = active_object_map;
}
int
TAO_Unique_Id_Strategy::is_servant_in_map (PortableServer::Servant servant,
bool &deactivated)
{
TAO_Active_Object_Map_Entry *entry = 0;
int result = this->active_object_map_->servant_map_->find (servant,
entry);
if (result == 0)
{
result = 1;
if (entry->deactivated_)
{
deactivated = true;
}
}
else
{
result = 0;
}
return result;
}
int
TAO_Unique_Id_Strategy::bind_using_user_id (
PortableServer::Servant servant,
const PortableServer::ObjectId &user_id,
CORBA::Short priority,
TAO_Active_Object_Map_Entry *&entry)
{
int result =
this->active_object_map_->user_id_map_->find (user_id, entry);
if (result == 0)
{
if (servant != 0)
{
entry->servant_ = servant;
result =
this->active_object_map_->servant_map_->bind (entry->servant_,
entry);
#if defined (TAO_HAS_MONITOR_POINTS) && (TAO_HAS_MONITOR_POINTS == 1)
if (result == 0)
{
this->active_object_map_->monitor_->receive (
this->active_object_map_->servant_map_->current_size ());
}
#endif /* TAO_HAS_MONITOR_POINTS==1 */
}
}
else
{
ACE_NEW_RETURN (entry,
TAO_Active_Object_Map_Entry,
-1);
entry->user_id_ = user_id;
entry->servant_ = servant;
entry->priority_ = priority;
result = this->active_object_map_->id_hint_strategy_->bind (*entry);
if (result == 0)
{
result =
this->active_object_map_->user_id_map_->bind (entry->user_id_,
entry);
if (result == 0)
{
if (servant != 0)
{
result =
this->active_object_map_->servant_map_->bind (
entry->servant_,
entry);
}
if (result != 0)
{
this->active_object_map_->user_id_map_->unbind (
entry->user_id_);
this->active_object_map_->id_hint_strategy_->unbind (
*entry);
delete entry;
}
else
{
#if defined (TAO_HAS_MONITOR_POINTS) && (TAO_HAS_MONITOR_POINTS == 1)
this->active_object_map_->monitor_->receive (
this->active_object_map_->servant_map_->current_size ());
#endif /* TAO_HAS_MONITOR_POINTS==1 */
}
}
else
{
this->active_object_map_->id_hint_strategy_->unbind (*entry);
delete entry;
}
}
else
{
delete entry;
}
}
#if (TAO_HAS_MINIMUM_CORBA == 0)
if (result == 0 && TAO_debug_level > 7)
{
CORBA::String_var idstr (PortableServer::ObjectId_to_string (user_id));
CORBA::String_var repository_id (
servant ? servant->_repository_id () : 0);
ACE_CString hex_idstr;
hexstring (hex_idstr, idstr.in (), user_id.length ());
TAOLIB_DEBUG ((LM_DEBUG,
"TAO (%P|%t) - TAO_Unique_Id_Strategy::"
"bind_using_user_id: type=%C, id=%C\n",
repository_id.in (),
hex_idstr.c_str()
));
}
#endif
return result;
}
int
TAO_Unique_Id_Strategy::unbind_using_user_id (
const PortableServer::ObjectId &user_id)
{
TAO_Active_Object_Map_Entry *entry = 0;
int result = this->active_object_map_->user_id_map_->unbind (user_id,
entry);
if (result == 0)
{
if (TAO_debug_level > 7)
{
CORBA::String_var idstr (
PortableServer::ObjectId_to_string (entry->user_id_));
ACE_CString hex_idstr;
hexstring (hex_idstr, idstr.in (), entry->user_id_.length ());
TAOLIB_DEBUG ((LM_DEBUG,
"TAO (%P|%t) - TAO_Unique_Id_Strategy::unbind_using_user_id: id=%C\n",
hex_idstr.c_str()
));
}
if (entry->servant_ != 0)
{
result =
this->active_object_map_->servant_map_->unbind (entry->servant_);
}
if (result == 0)
{
result =
this->active_object_map_->id_hint_strategy_->unbind (*entry);
#if defined (TAO_HAS_MONITOR_POINTS) && (TAO_HAS_MONITOR_POINTS == 1)
this->active_object_map_->monitor_->receive (
this->active_object_map_->servant_map_->current_size ());
#endif /* TAO_HAS_MONITOR_POINTS==1 */
}
if (result == 0)
{
delete entry;
}
}
return result;
}
int
TAO_Unique_Id_Strategy::find_user_id_using_servant (
PortableServer::Servant servant,
PortableServer::ObjectId_out user_id)
{
TAO_Active_Object_Map_Entry *entry = 0;
int result = this->active_object_map_->servant_map_->find (servant, entry);
if (result == 0)
{
if (entry->deactivated_)
{
result = -1;
}
else
{
ACE_NEW_RETURN (user_id,
PortableServer::ObjectId (entry->user_id_),
-1);
}
}
return result;
}
int
TAO_Unique_Id_Strategy::find_system_id_using_servant (
PortableServer::Servant servant,
PortableServer::ObjectId_out system_id,
CORBA::Short &priority)
{
TAO_Active_Object_Map_Entry *entry = 0;
int result = this->active_object_map_->servant_map_->find (servant,
entry);
if (result == 0)
{
if (entry->deactivated_)
{
result = -1;
}
else
{
result =
this->active_object_map_->id_hint_strategy_->system_id (
system_id,
*entry);
if (result == 0)
{
priority = entry->priority_;
}
}
}
return result;
}
CORBA::Boolean
TAO_Unique_Id_Strategy::remaining_activations (
PortableServer::Servant servant)
{
ACE_UNUSED_ARG (servant);
// Since servant are always unique here, return false.
return 0;
}
////////////////////////////////////////////////////////////////////////////////
#if !defined (CORBA_E_MICRO)
int
TAO_Multiple_Id_Strategy::is_servant_in_map (PortableServer::Servant, bool &)
{
return -1;
}
int
TAO_Multiple_Id_Strategy::bind_using_user_id (
PortableServer::Servant servant,
const PortableServer::ObjectId &user_id,
CORBA::Short priority,
TAO_Active_Object_Map_Entry *&entry)
{
int result =
this->active_object_map_->user_id_map_->find (user_id, entry);
if (result == 0)
{
if (servant != 0)
{
entry->servant_ = servant;
}
}
else
{
ACE_NEW_RETURN (entry,
TAO_Active_Object_Map_Entry,
-1);
entry->user_id_ = user_id;
entry->servant_ = servant;
entry->priority_ = priority;
result =
this->active_object_map_->id_hint_strategy_->bind (*entry);
if (result == 0)
{
result =
this->active_object_map_->user_id_map_->bind (entry->user_id_,
entry);
if (result != 0)
{
this->active_object_map_->id_hint_strategy_->unbind (*entry);
delete entry;
}
else
{
#if defined (TAO_HAS_MONITOR_POINTS) && (TAO_HAS_MONITOR_POINTS == 1)
this->active_object_map_->monitor_->receive (
this->active_object_map_->user_id_map_->current_size ());
#endif /* TAO_HAS_MONITOR_POINTS==1 */
}
}
else
{
delete entry;
}
}
#if (TAO_HAS_MINIMUM_CORBA == 0)
if (result == 0 && TAO_debug_level > 7)
{
CORBA::String_var idstr (PortableServer::ObjectId_to_string (user_id));
CORBA::String_var repository_id (
servant ? servant->_repository_id () : 0);
ACE_CString hex_idstr;
hexstring (hex_idstr, idstr.in (), user_id.length ());
TAOLIB_DEBUG ((LM_DEBUG,
"TAO (%P|%t) - TAO_Multiple_Id_Strategy::"
"bind_using_user_id: type=%C, id=%C\n",
repository_id.in (),
hex_idstr.c_str()
));
}
#endif
return result;
}
int
TAO_Multiple_Id_Strategy::unbind_using_user_id (
const PortableServer::ObjectId &user_id)
{
TAO_Active_Object_Map_Entry *entry = 0;
int result = this->active_object_map_->user_id_map_->unbind (user_id,
entry);
if (result == 0)
{
if (TAO_debug_level > 7)
{
CORBA::String_var idstr (
PortableServer::ObjectId_to_string (entry->user_id_));
ACE_CString hex_idstr;
hexstring (hex_idstr, idstr.in (), entry->user_id_.length ());
TAOLIB_DEBUG ((LM_DEBUG,
"TAO (%P|%t) - TAO_Multiple_Id_Strategy::unbind_using_user_id: id=%C\n",
hex_idstr.c_str()
));
}
result = this->active_object_map_->id_hint_strategy_->unbind (*entry);
if (result == 0)
{
delete entry;
}
#if defined (TAO_HAS_MONITOR_POINTS) && (TAO_HAS_MONITOR_POINTS == 1)
this->active_object_map_->monitor_->receive (
this->active_object_map_->user_id_map_->current_size ());
#endif /* TAO_HAS_MONITOR_POINTS==1 */
}
return result;
}
int
TAO_Multiple_Id_Strategy::find_user_id_using_servant (
PortableServer::Servant,
PortableServer::ObjectId_out)
{
return -1;
}
int
TAO_Multiple_Id_Strategy::find_system_id_using_servant (
PortableServer::Servant,
PortableServer::ObjectId_out,
CORBA::Short &)
{
return -1;
}
CORBA::Boolean
TAO_Multiple_Id_Strategy::remaining_activations (
PortableServer::Servant servant)
{
TAO_Active_Object_Map::user_id_map::iterator end =
this->active_object_map_->user_id_map_->end ();
for (TAO_Active_Object_Map::user_id_map::iterator iter =
this->active_object_map_->user_id_map_->begin ();
iter != end;
++iter)
{
TAO_Active_Object_Map::user_id_map::value_type map_pair = *iter;
TAO_Active_Object_Map_Entry *entry = map_pair.second ();
if (entry->servant_ == servant)
{
return 1;
}
}
return 0;
}
#endif
TAO_Lifespan_Strategy::~TAO_Lifespan_Strategy (void)
{
}
void
TAO_Lifespan_Strategy::set_active_object_map (
TAO_Active_Object_Map *active_object_map)
{
this->active_object_map_ = active_object_map;
}
int
TAO_Transient_Strategy::find_servant_using_system_id_and_user_id (
const PortableServer::ObjectId &system_id,
const PortableServer::ObjectId &user_id,
PortableServer::Servant &servant,
TAO_Active_Object_Map_Entry *&entry)
{
int result = this->active_object_map_->id_hint_strategy_->find (system_id,
entry);
if (result == 0)
{
if (entry->deactivated_)
{
result = -1;
}
else if (entry->servant_ == 0)
{
result = -1;
}
else
{
servant = entry->servant_;
}
}
else
{
result = this->active_object_map_->user_id_map_->find (user_id,
entry);
if (result == 0)
{
if (entry->deactivated_)
{
result = -1;
}
else if (entry->servant_ == 0)
{
result = -1;
}
else
{
servant = entry->servant_;
}
}
}
if (result == -1)
{
entry = 0;
}
return result;
}
////////////////////////////////////////////////////////////////////////////////
#if !defined (CORBA_E_MICRO)
int
TAO_Persistent_Strategy::find_servant_using_system_id_and_user_id (
const PortableServer::ObjectId &system_id,
const PortableServer::ObjectId &user_id,
PortableServer::Servant &servant,
TAO_Active_Object_Map_Entry *&entry)
{
int result =
this->active_object_map_->id_hint_strategy_->find (system_id,
entry);
if (result == 0 && user_id == entry->user_id_)
{
if (entry->deactivated_)
{
result = -1;
}
else if (entry->servant_ == 0)
{
result = -1;
}
else
{
servant = entry->servant_;
}
}
else
{
result =
this->active_object_map_->user_id_map_->find (user_id, entry);
if (result == 0)
{
if (entry->deactivated_)
{
result = -1;
}
else if (entry->servant_ == 0)
{
result = -1;
}
else
{
servant = entry->servant_;
}
}
}
if (result == -1)
{
entry = 0;
}
return result;
}
#endif
TAO_Id_Assignment_Strategy::~TAO_Id_Assignment_Strategy (void)
{
}
void
TAO_Id_Assignment_Strategy::set_active_object_map (
TAO_Active_Object_Map *active_object_map)
{
this->active_object_map_ = active_object_map;
}
#if !defined (CORBA_E_MICRO)
int
TAO_User_Id_Strategy::bind_using_system_id (PortableServer::Servant,
CORBA::Short,
TAO_Active_Object_Map_Entry *&)
{
return -1;
}
#endif
int
TAO_System_Id_With_Unique_Id_Strategy::bind_using_system_id (
PortableServer::Servant servant,
CORBA::Short priority,
TAO_Active_Object_Map_Entry *&entry)
{
ACE_NEW_RETURN (entry,
TAO_Active_Object_Map_Entry,
-1);
int result =
this->active_object_map_->user_id_map_->bind_create_key (entry,
entry->user_id_);
if (result == 0)
{
entry->servant_ = servant;
entry->priority_ = priority;
result = this->active_object_map_->id_hint_strategy_->bind (*entry);
if (result == 0)
{
if (servant != 0)
{
result =
this->active_object_map_->servant_map_->bind (entry->servant_,
entry);
}
if (result != 0)
{
this->active_object_map_->user_id_map_->unbind (entry->user_id_);
this->active_object_map_->id_hint_strategy_->unbind (*entry);
delete entry;
}
else
{
#if defined (TAO_HAS_MONITOR_POINTS) && (TAO_HAS_MONITOR_POINTS == 1)
this->active_object_map_->monitor_->receive (
this->active_object_map_->servant_map_->current_size ());
#endif /* TAO_HAS_MONITOR_POINTS==1 */
}
}
else
{
this->active_object_map_->user_id_map_->unbind (entry->user_id_);
delete entry;
}
}
else
{
delete entry;
}
#if (TAO_HAS_MINIMUM_CORBA == 0)
if (result == 0 && TAO_debug_level > 7)
{
CORBA::String_var idstr (
PortableServer::ObjectId_to_string (entry->user_id_));
CORBA::String_var repository_id (
servant ? servant->_repository_id () : 0);
ACE_CString hex_idstr;
hexstring (hex_idstr, idstr.in (), entry->user_id_.length ());
TAOLIB_DEBUG ((LM_DEBUG,
"TAO (%P|%t) - TAO_System_Id_With_Unique_Id_Strategy::"
"bind_using_system_id: type=%C, id=%C\n",
repository_id.in (),
hex_idstr.c_str()
));
}
#endif
return result;
}
#if !defined (CORBA_E_MICRO)
int
TAO_System_Id_With_Multiple_Id_Strategy::bind_using_system_id (
PortableServer::Servant servant,
CORBA::Short priority,
TAO_Active_Object_Map_Entry *&entry)
{
ACE_NEW_RETURN (entry,
TAO_Active_Object_Map_Entry,
-1);
int result =
this->active_object_map_->user_id_map_->bind_create_key (entry,
entry->user_id_);
if (result == 0)
{
entry->servant_ = servant;
entry->priority_ = priority;
result = this->active_object_map_->id_hint_strategy_->bind (*entry);
if (result != 0)
{
this->active_object_map_->user_id_map_->unbind (entry->user_id_);
delete entry;
}
#if defined (TAO_HAS_MONITOR_POINTS) && (TAO_HAS_MONITOR_POINTS == 1)
this->active_object_map_->monitor_->receive (
this->active_object_map_->user_id_map_->current_size ());
#endif /* TAO_HAS_MONITOR_POINTS==1 */
}
else
{
delete entry;
}
#if (TAO_HAS_MINIMUM_CORBA == 0)
if (result == 0 && TAO_debug_level > 7)
{
CORBA::String_var idstr (
PortableServer::ObjectId_to_string (entry->user_id_));
CORBA::String_var repository_id (
servant ? servant->_repository_id () : 0);
ACE_CString hex_idstr;
hexstring (hex_idstr, idstr.in (), entry->user_id_.length ());
TAOLIB_DEBUG ((LM_DEBUG,
"TAO (%P|%t) - TAO_System_Id_With_Multiple_Id_Strategy::"
"bind_using_system_id: type=%C, id=%C\n",
repository_id.in (),
hex_idstr.c_str()
));
}
#endif
return result;
}
#endif
////////////////////////////////////////////////////////////////////////////////
TAO_Id_Hint_Strategy::~TAO_Id_Hint_Strategy (void)
{
}
////////////////////////////////////////////////////////////////////////////////
TAO_Active_Hint_Strategy::TAO_Active_Hint_Strategy (CORBA::ULong map_size)
: system_id_map_ (map_size)
{
}
TAO_Active_Hint_Strategy::~TAO_Active_Hint_Strategy (void)
{
}
int
TAO_Active_Hint_Strategy::recover_key (
const PortableServer::ObjectId &system_id,
PortableServer::ObjectId &user_id)
{
return this->system_id_map_.recover_key (system_id, user_id);
}
int
TAO_Active_Hint_Strategy::bind (TAO_Active_Object_Map_Entry &entry)
{
entry.system_id_ = entry.user_id_;
return this->system_id_map_.bind_modify_key (&entry,
entry.system_id_);
}
int
TAO_Active_Hint_Strategy::unbind (TAO_Active_Object_Map_Entry &entry)
{
return this->system_id_map_.unbind (entry.system_id_);
}
int
TAO_Active_Hint_Strategy::find (const PortableServer::ObjectId &system_id,
TAO_Active_Object_Map_Entry *&entry)
{
return this->system_id_map_.find (system_id,
entry);
}
size_t
TAO_Active_Hint_Strategy::hint_size (void)
{
return ACE_Active_Map_Manager_Key::size ();
}
int
TAO_Active_Hint_Strategy::system_id (PortableServer::ObjectId_out system_id,
TAO_Active_Object_Map_Entry &entry)
{
ACE_NEW_RETURN (system_id,
PortableServer::ObjectId (entry.system_id_),
-1);
return 0;
}
////////////////////////////////////////////////////////////////////////////////
TAO_No_Hint_Strategy::~TAO_No_Hint_Strategy (void)
{
}
int
TAO_No_Hint_Strategy::recover_key (const PortableServer::ObjectId &system_id,
PortableServer::ObjectId &user_id)
{
// Smartly copy all the data; <user_id does not own the data>.
user_id.replace (system_id.maximum (),
system_id.length (),
const_cast<CORBA::Octet *> (system_id.get_buffer ()),
0);
return 0;
}
int
TAO_No_Hint_Strategy::bind (TAO_Active_Object_Map_Entry &)
{
return 0;
}
int
TAO_No_Hint_Strategy::unbind (TAO_Active_Object_Map_Entry &)
{
return 0;
}
int
TAO_No_Hint_Strategy::find (const PortableServer::ObjectId &,
TAO_Active_Object_Map_Entry *&)
{
return -1;
}
size_t
TAO_No_Hint_Strategy::hint_size (void)
{
return 0;
}
int
TAO_No_Hint_Strategy::system_id (PortableServer::ObjectId_out system_id,
TAO_Active_Object_Map_Entry &entry)
{
ACE_NEW_RETURN (system_id,
PortableServer::ObjectId (entry.user_id_),
-1);
return 0;
}
TAO_END_VERSIONED_NAMESPACE_DECL
| 27.150332 | 96 | 0.573343 | cflowe |
66ad1a5b992e32cff0acc9c3e7c85a7e33d4ea7e | 3,189 | cpp | C++ | src/interrupts.cpp | kshitej/HobOs | 21cbe04a882389d402f936eaf0e1dd4c15a140be | [
"0BSD"
] | 9 | 2016-07-07T18:12:27.000Z | 2022-03-11T06:41:38.000Z | src/interrupts.cpp | solson/spideros | a9c34f3aec10283d5623e821d70c2d9fb5fce843 | [
"0BSD"
] | null | null | null | src/interrupts.cpp | solson/spideros | a9c34f3aec10283d5623e821d70c2d9fb5fce843 | [
"0BSD"
] | null | null | null | #include "assert.h"
#include "interrupts.h"
#include "display.h"
#include "idt.h"
#include "ports.h"
// TODO: Deal with the magic numbers in this file.
namespace interrupts {
template<int n>
[[gnu::naked]] void interrupt() {
asm volatile("cli");
asm volatile("push %0" : : "i"(n));
asm volatile("jmp interruptCommon");
}
// Set the IDT gates for interrupts from 0 up to N - 1
template<unsigned N>
[[gnu::always_inline]] void setIdtGates() {
setIdtGates<N - 1>();
idt::setGate(N - 1, interrupt<N - 1>, 0x8, 0, 0, idt::INTR32);
}
template<> void setIdtGates<0>() {}
void init() {
remapPic();
setIdtGates<48>();
}
// Master PIC command and data port numbers.
const u16 PIC1_COMMAND_PORT = 0x20;
const u16 PIC1_DATA_PORT = 0x21;
// Slave PIC command and data port numbers.
const u16 PIC2_COMMAND_PORT = 0xA0;
const u16 PIC2_DATA_PORT = 0xA1;
// End-of-interupt command to send to the PICs when we are finished handling an
// interrupt to resume regularly scheduled programming.
const u8 PIC_EOI = 0x20;
// Normally, IRQs 0 to 7 are mapped to entries 8 to 15. This is a problem in
// protected mode, because IDT entry 8 is a Double Fault. Without remapping,
// every time irq0 fires, you get a Double Fault Exception, which is not
// actually what's happening. We send commands to the Programmable Interrupt
// Controller (PICs, also called the 8259s) in order to remap irq0 to 15 to IDT
// entries 32 to 47.
void remapPic() {
// Tell the PICs to wait for our 3 initialization bytes (we want to
// reinitialize).
ports::outb(PIC1_COMMAND_PORT, 0x11);
ports::outb(PIC2_COMMAND_PORT, 0x11);
// Set master PIC offset to 0x20 (= IRQ0 = 32).
ports::outb(PIC1_DATA_PORT, 0x20);
// Set slave PIC offset to 0x28 (= IRQ8 = 40).
ports::outb(PIC2_DATA_PORT, 0x28);
// Set the wiring to 'attached to corresponding interrupt pin'.
ports::outb(PIC1_DATA_PORT, 0x04);
ports::outb(PIC2_DATA_PORT, 0x02);
// We want to use 8086/8088 mode (bit 0).
ports::outb(PIC1_DATA_PORT, 0x01);
ports::outb(PIC2_DATA_PORT, 0x01);
// Restore masking (if a bit is not set_PORT, the interrupts is on).
ports::outb(PIC1_DATA_PORT, 0x00);
ports::outb(PIC2_DATA_PORT, 0x00);
}
IrqHandlerFn irqHandlerFns[16]; // Implicitly zero-initialized.
void setIrqHandler(u32 irqNum, IrqHandlerFn handlerFn) {
assert(irqNum < 16);
irqHandlerFns[irqNum] = handlerFn;
}
extern "C" void interruptHandler(Registers* regs) {
if (regs->interruptNum >= 32 && regs->interruptNum < 48) {
const u32 irqNum = regs->interruptNum - 32;
if (irqHandlerFns[irqNum]) {
irqHandlerFns[irqNum](regs);
} else {
display::println("Got unhandled irq ", irqNum);
}
// We need to send an EOI (end-of-interrupt command) to the interrupt
// controller when we are done. Only send EOI to slave controller if it's
// involved (irqs 8 and up).
if(regs->interruptNum >= 8) {
ports::outb(PIC2_COMMAND_PORT, PIC_EOI);
}
ports::outb(PIC1_COMMAND_PORT, PIC_EOI);
} else {
display::println("Got isr interrupt: ", regs->interruptNum);
// Disable interrupts and halt.
asm volatile("cli; hlt");
}
}
} // namespace interrupts
| 29.803738 | 79 | 0.691753 | kshitej |
66ad2f5ba38ad343a121298d8006a45e31af7c9a | 685 | cpp | C++ | source/Gui/Animation/AnimationHandler.cpp | tillpp/GraphIDE | f88f1ca02a8f9f09fe965b69651ea45fbb1b5d1e | [
"MIT"
] | 2 | 2021-10-10T00:28:03.000Z | 2021-11-11T20:33:40.000Z | source/Gui/Animation/AnimationHandler.cpp | tillpp/GraphIDE | f88f1ca02a8f9f09fe965b69651ea45fbb1b5d1e | [
"MIT"
] | null | null | null | source/Gui/Animation/AnimationHandler.cpp | tillpp/GraphIDE | f88f1ca02a8f9f09fe965b69651ea45fbb1b5d1e | [
"MIT"
] | null | null | null | #include "AnimationHandler.h"
AnimationHandler::AnimationHandler(GuiComponent& g)
:gui(g)
{
}
AnimationHandler::~AnimationHandler()
{
}
Animation* AnimationHandler::createAnimation(std::string name){
if(animations.find(name)!=animations.end()){
return nullptr;
}
Animation* rv = new Animation(&gui,name);
animations[name] = rv;
return rv;
}
void AnimationHandler::use(std::string name){
if(animations.find(name)==animations.end())
return;
currentAnimation = animations[name];
}
void AnimationHandler::update(){
if(currentAnimation)
currentAnimation->update();
}
void AnimationHandler::updateAttribute(){
if(currentAnimation)
currentAnimation->updateAttribute();
} | 20.757576 | 63 | 0.748905 | tillpp |
66af9fc1e9530b4bf27d447fb23b1099ea3eac76 | 2,508 | cpp | C++ | OpenGL/Lib/source/ShaderLoader.cpp | Hexeption/Dotel | 56c3712da58078d7fed6668ed89a7d4c07423d0d | [
"BSD-3-Clause"
] | 7 | 2017-09-26T15:06:20.000Z | 2022-01-02T16:35:45.000Z | OpenGL/Lib/source/ShaderLoader.cpp | Hexeption/Dotel | 56c3712da58078d7fed6668ed89a7d4c07423d0d | [
"BSD-3-Clause"
] | null | null | null | OpenGL/Lib/source/ShaderLoader.cpp | Hexeption/Dotel | 56c3712da58078d7fed6668ed89a7d4c07423d0d | [
"BSD-3-Clause"
] | 2 | 2017-09-02T11:10:25.000Z | 2017-09-04T18:09:27.000Z | //
// Created by Keirb on 13/11/2017.
//
#include "ShaderLoader.h"
Dotel::ShaderLoader::ShaderLoader(const char *vertexPath, const char *fragmentPath)
{
vShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
fShaderFile.exceptions(std::ifstream::failbit | std::ifstream::badbit);
try
{
vShaderFile.open(vertexPath);
fShaderFile.open(fragmentPath);
vShaderStream << vShaderFile.rdbuf();
fShaderStream << fShaderFile.rdbuf();
vShaderFile.close();
fShaderFile.close();
vertexCode = vShaderStream.str();
fragmentCode = fShaderStream.str();
} catch (std::ifstream::failure e)
{
std::cout << "ERROR::SHADER::FILE_NOT_SUCCESSFULLY_READ" << std::endl;
}
vShaderCode = vertexCode.c_str();
fShaderCode = fragmentCode.c_str();
vertex = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex, 1, &vShaderCode, NULL);
glCompileShader(vertex);
checkShaderCompile(vertex, "VERTEX");
fragment = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment, 1, &fShaderCode, NULL);
glCompileShader(fragment);
checkShaderCompile(fragment, "FRAGMENT");
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertex);
glAttachShader(shaderProgram, fragment);
glLinkProgram(shaderProgram);
glDeleteShader(vertex);
glDeleteShader(fragment);
}
Dotel::ShaderLoader::~ShaderLoader()
{
Disable();
}
void Dotel::ShaderLoader::Use()
{
glUseProgram(shaderProgram);
}
void Dotel::ShaderLoader::Disable()
{
glUseProgram(0);
}
void Dotel::ShaderLoader::checkShaderCompile(GLuint shader, string type)
{
int success;
char infoLog[1024];
if (type != "PROGRAM")
{
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
std::cout << "ERROR::SHADER_COMPILATION_ERROR of type: " << type << "\n" << infoLog
<< "\n -- --------------------------------------------------- -- " << std::endl;
}
} else
{
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success)
{
glGetProgramInfoLog(shader, 1024, NULL, infoLog);
std::cout << "ERROR::PROGRAM_LINKING_ERROR of type: " << type << "\n" << infoLog
<< "\n -- --------------------------------------------------- -- " << std::endl;
}
}
}
| 27.26087 | 102 | 0.600478 | Hexeption |
66b2ccb790fa0ba656b95c51e46cc07b28f382ad | 3,946 | hpp | C++ | fly/types/concurrency/detail/concurrent_container.hpp | trflynn89/libfly | 711352b278314350ffa0d96c48b0af685d9c61b8 | [
"MIT"
] | 12 | 2020-12-26T04:40:48.000Z | 2022-02-12T17:58:33.000Z | fly/types/concurrency/detail/concurrent_container.hpp | trflynn89/libfly | 711352b278314350ffa0d96c48b0af685d9c61b8 | [
"MIT"
] | 308 | 2017-09-20T22:19:57.000Z | 2022-02-26T00:16:11.000Z | fly/types/concurrency/detail/concurrent_container.hpp | trflynn89/libfly | 711352b278314350ffa0d96c48b0af685d9c61b8 | [
"MIT"
] | 2 | 2020-12-26T04:41:02.000Z | 2021-06-17T18:24:03.000Z | #pragma once
#include <chrono>
#include <condition_variable>
#include <mutex>
namespace fly::detail {
/**
* Wrapper around an STL container to provide thread safe access.
*
* @author Timothy Flynn (trflynn89@pm.me)
* @version July 27, 2016
*/
template <typename T, typename Container>
class ConcurrentContainer
{
public:
using size_type = typename Container::size_type;
using value_type = T;
/**
* Destructor.
*/
virtual ~ConcurrentContainer() = default;
/**
* Move an item onto the container.
*
* @param item Item to push onto the container.
*/
void push(T &&item);
/**
* Pop an item from the container. If the container is empty, wait indefinitely for item to be
* available.
*
* @param item Location to store the popped item.
*/
void pop(T &item);
/**
* Pop an item from the container. If the container is empty, wait (at most) for the specified
* amount of time for an item to be available.
*
* @param item Location to store the popped item.
* @param duration The amount of time to wait.
*
* @return True if an object was popped in the given duration.
*/
template <typename R, typename P>
bool pop(T &item, std::chrono::duration<R, P> duration);
/**
* @return True if the container is empty.
*/
bool empty() const;
/**
* @return The number of items in the container.
*/
size_type size() const;
protected:
/**
* Implementation-specific method to move an item onto the container.
*
* @param item Item to push onto the container.
*/
virtual void push_internal(T &&item) = 0;
/**
* Implementation-specific method to pop an item from the container.
*
* @param item Location to store the popped item.
*/
virtual void pop_internal(T &item) = 0;
mutable std::mutex m_container_mutex;
Container m_container;
private:
std::condition_variable m_push_condition;
};
//==================================================================================================
template <typename T, typename Container>
void ConcurrentContainer<T, Container>::push(T &&item)
{
{
std::unique_lock<std::mutex> lock(m_container_mutex);
push_internal(std::move(item));
}
m_push_condition.notify_one();
}
//==================================================================================================
template <typename T, typename Container>
void ConcurrentContainer<T, Container>::pop(T &item)
{
std::unique_lock<std::mutex> lock(m_container_mutex);
while (m_container.empty())
{
m_push_condition.wait(lock);
}
pop_internal(item);
}
//==================================================================================================
template <typename T, typename Container>
template <typename R, typename P>
bool ConcurrentContainer<T, Container>::pop(T &item, std::chrono::duration<R, P> wait_time)
{
std::unique_lock<std::mutex> lock(m_container_mutex);
auto empty_test = [this] {
return !m_container.empty();
};
bool item_popped = m_push_condition.wait_for(lock, wait_time, std::move(empty_test));
if (item_popped)
{
pop_internal(item);
}
return item_popped;
}
//==================================================================================================
template <typename T, typename Container>
bool ConcurrentContainer<T, Container>::empty() const
{
std::unique_lock<std::mutex> lock(m_container_mutex);
return m_container.empty();
}
//==================================================================================================
template <typename T, typename Container>
auto ConcurrentContainer<T, Container>::size() const -> size_type
{
std::unique_lock<std::mutex> lock(m_container_mutex);
return m_container.size();
}
} // namespace fly::detail
| 26.306667 | 100 | 0.573746 | trflynn89 |
66b539f1171587aeba159dd1f136ed99e95508a5 | 2,692 | cc | C++ | math.cc | linyufly/ConjugateGradient | 0f160e286fd3282e461adccdc49fb5d27daa463d | [
"MIT"
] | 1 | 2019-05-08T03:36:46.000Z | 2019-05-08T03:36:46.000Z | math.cc | linyufly/ConjugateGradient | 0f160e286fd3282e461adccdc49fb5d27daa463d | [
"MIT"
] | null | null | null | math.cc | linyufly/ConjugateGradient | 0f160e286fd3282e461adccdc49fb5d27daa463d | [
"MIT"
] | null | null | null | // Author: Mingcheng Chen (linyufly@gmail.com)
#include "math.h"
#include "sparse_matrix.h"
#include <cmath>
#include <cstdio>
#include <algorithm>
namespace {
const double kEpsilon = 1e-8;
// Multiply A^tA with b.
void multiply_ata_b(
const SparseMatrix &a_trans, const SparseMatrix &a,
const double *b, double *c) {
double *temp = new double[a.get_num_rows()];
a.multiply_column(b, temp);
a_trans.multiply_column(temp, c);
delete [] temp;
}
double inner_product(const double *a, const double *b, int n) {
double result = 0.0;
for (int c = 0; c < n; c++) {
result += a[c] * b[c];
}
return result;
}
void add(const double *a, const double *b, double beta, int n, double *c) {
for (int i = 0; i < n; i++) {
c[i] = a[i] + b[i] * beta;
}
}
}
void Math::conjugate_gradient(
const SparseMatrix &a, const double *b, int num_iterations, double *x) {
SparseMatrix a_trans = a.transpose();
double *a_trans_b = new double[a_trans.get_num_rows()];
a_trans.multiply_column(b, a_trans_b);
// Solve a_trans * a * x = a_trans_b.
double *r = new double[a_trans.get_num_rows()];
double *p = new double[a_trans.get_num_rows()];
double *temp = new double[a_trans.get_num_rows()];
// temp = A'A * x
multiply_ata_b(a_trans, a, x, temp);
// r = A'b - temp
add(a_trans_b, temp, -1.0, a_trans.get_num_rows(), r);
// p = r
std::copy(r, r + a_trans.get_num_rows(), p);
// rs_old = r' * r
double rs_old = inner_product(r, r, a_trans.get_num_rows());
if (sqrt(rs_old) < kEpsilon) {
printf("The initial solution is good.\n");
return;
}
for (int iteration = 0;
iteration < num_iterations && iteration < a_trans.get_num_rows();
iteration++) {
// temp = A'A * p
multiply_ata_b(a_trans, a, p, temp);
// alpha = rs_old / (p' * temp)
double alpha = rs_old / inner_product(p, temp, a_trans.get_num_rows());
// x = x + alpha * p
add(x, p, alpha, a_trans.get_num_rows(), x);
// r = r - alpha * temp
add(r, temp, -alpha, a_trans.get_num_rows(), r);
// rs_new = r' * r
double rs_new = inner_product(r, r, a_trans.get_num_rows());
// Traditionally, if norm(rs_new) is small enough, the iteration can stop.
if (sqrt(rs_new) < kEpsilon) {
/// DEBUG ///
printf("rs_new = %.20lf\n", rs_new);
break;
}
// p = r + (rs_new / rs_old) * p
add(r, p, rs_new / rs_old, a_trans.get_num_rows(), p);
// rs_old = rs_new
rs_old = rs_new;
/// DEBUG ///
printf(" rs_old = %.20lf\n", rs_old);
}
/// DEBUG ///
printf("rs_old = %.20lf\n", rs_old);
delete [] r;
delete [] p;
delete [] temp;
delete [] a_trans_b;
}
| 22.621849 | 78 | 0.60364 | linyufly |
66b6221709d6fcd49595b7cdf6de8571f5e71e64 | 5,543 | cpp | C++ | src/terrTriDomain.cpp | mnentwig/glTest5 | 004804482fb5bb72c8f32f50464b7feb8cfa12c3 | [
"MIT"
] | null | null | null | src/terrTriDomain.cpp | mnentwig/glTest5 | 004804482fb5bb72c8f32f50464b7feb8cfa12c3 | [
"MIT"
] | null | null | null | src/terrTriDomain.cpp | mnentwig/glTest5 | 004804482fb5bb72c8f32f50464b7feb8cfa12c3 | [
"MIT"
] | null | null | null | #include "terrTriDomain.h"
#include "terrTri.h"
#include <vector>
#include <algorithm> // std::find
#include <glm/vec2.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/intersect.hpp>
#include "geomUtils2d.hpp"
#include <iostream>
terrTriDomain::terrTriDomain(){
this->state_closed = false;
}
void terrTriDomain::reserveVertexSpace(unsigned int n){
assert(this->state_closed == false);
if (n > this->vertices.size ())
this->vertices.resize (n);
this->trisUsingVertex.resize (n);
}
void terrTriDomain::setVertex(terrTriVertIx index, const glm::vec3& pt){
assert(index < this->vertices.size ());
assert(this->state_closed == false);
// assert(std::find (this->vertices.begin (), this->vertices.end (), pt) == this->vertices.end ());
this->vertices[index] = pt;
assert(this->trisUsingVertex[index] == NULL);
this->trisUsingVertex[index] = new std::vector<terrTri*> ();
}
const glm::vec3& terrTriDomain::getVertex(terrTriVertIx index) const{
return this->vertices[index];
}
#if 0
void terrTriDomain::debug(){
int n01 = 0;
int n12 = 0;
int n20 = 0;
int count = 0;
for (auto it = this->allTerrTris.begin (); it != this->allTerrTris.end (); ++it) {
if ((*it)->getNeighbor01 ()) ++n01;
if ((*it)->getNeighbor12 ()) ++n12;
if ((*it)->getNeighbor20 ()) ++n20;
++count;
}
std::cout << n01 << " " << n12 << " " << n20 << " out of " << count << std::endl;
}
#endif
void terrTriDomain::registerTri(terrTriVertIx p0, terrTriVertIx p1, terrTriVertIx p2){
assert(this->state_closed == false);
terrTri *t = new terrTri (p0, p1, p2);
this->allTerrTris.push_back (t);
std::vector<terrTri*> *n0 = this->trisUsingVertex[p0];
std::vector<terrTri*> *n1 = this->trisUsingVertex[p1];
std::vector<terrTri*> *n2 = this->trisUsingVertex[p2];
for (auto it = n0->begin (); it != n0->end (); ++it) {
if (std::find (n1->begin (), n1->end (), *it) != n1->end ()) {
t->n01 = *it;
(*it)->registerNeighbor (t, p0, p1);
break;
}
}
for (auto it = n1->begin (); it != n1->end (); ++it) {
if (std::find (n2->begin (), n2->end (), *it) != n2->end ()) {
t->n12 = *it;
(*it)->registerNeighbor (t, p1, p2);
break;
}
}
for (auto it = n2->begin (); it != n2->end (); ++it) {
if (std::find (n0->begin (), n0->end (), *it) != n0->end ()) {
t->n20 = *it;
(*it)->registerNeighbor (t, p2, p0);
break;
}
}
// === once neighbor search is complete, add tri to lookup-by-vertex table ===
n0->push_back (t);
n1->push_back (t);
n2->push_back (t);
}
void terrTriDomain::close(){
assert(this->state_closed == false);
// === calculate vertex normals by averaging all tris that use it ===
this->vertexNormals.resize (this->allTerrTris.size ());// note: elements are zeroed via default constructor
for (auto it = this->allTerrTris.begin (); it != this->allTerrTris.end (); ++it) {
terrTri *t = *it;
glm::vec3 normal = t->getNormal (this);
this->vertexNormals[t->getIxV0 ()] += normal;
this->vertexNormals[t->getIxV1 ()] += normal;
this->vertexNormals[t->getIxV2 ()] += normal;
}
// === normalize length of all vertex normals ===
for (auto it = this->vertexNormals.begin (); it != this->vertexNormals.end (); ++it) {
//assert(glm::length (*it) > 1e-3);// vertex without tris using it?
if (glm::length (*it) > 1e-3){ // TODO: why unused vertices?
*it = glm::normalize (*it);
}
}
this->state_closed = true;
}
const glm::vec3& terrTriDomain::getVertexNormal(terrTriVertIx ix) const{
assert(this->state_closed == true);
return this->vertexNormals[ix];
}
terrTriDomain::~terrTriDomain(){
for (auto it = this->allTerrTris.begin (); it != this->allTerrTris.end (); ++it)
delete (*it);
}
terrTri* terrTriDomain::locateTriByVerticalProjection(const glm::vec3& pos){
auto it = this->allTerrTris.begin ();
while (it != this->allTerrTris.end ()) {
terrTri *t = *(it++);
if (geomUtils2d::pointInTriangleNoY (pos, t->getV0 (this), t->getV1 (this), t->getV2 (this))) {
return t;
}
}
return NULL;
}
void terrTriDomain::motion(terrTri** knownLastTri, glm::vec3& position, glm::vec3& dirFwd, glm::vec3& dirUp, float dist){
// === initialize ===
if (*knownLastTri == NULL) {
auto it = this->allTerrTris.begin ();
while (it != this->allTerrTris.end ()) {
terrTri *t = *(it++);
glm::vec2 isBary;
float d;
glm::vec3 v0 = t->getV0 (this);
glm::vec3 v1 = t->getV1 (this);
glm::vec3 v2 = t->getV2 (this);
if (glm::intersectRayTriangle (position, dirUp, v0, v1, v2, isBary, d)) {
*knownLastTri = t;
position = v0 + isBary[0] * (v1 - v0) + isBary[1] * (v2 - v0);
position += dirUp;
// printf("%f %f\n", (double)isBary.x, (double)isBary.y);
break;
}
}
}
}
std::vector<terrTri*>* terrTriDomain::getTrisUsingVertex(terrTriVertIx pt){
return this->trisUsingVertex[pt];
}
#if 0
void terrTriDomain::collectNeighbors(std::vector<terrTri*>* collection, terrTriVertIx pt) const{
// note: below alg is O{N^2} but N is known to be small (typical number of neighbors)
for (auto itSrc = this->trisUsingVertex[pt]->begin (); itSrc != this->trisUsingVertex[pt]->end (); ++itSrc) {
// don't add if already in list
for (auto itDest = collection->begin (); itDest != collection->end (); ++itDest) {
if (*itSrc == *itDest) {
goto neighborIsAlreadyInList;
}
}
collection->push_back(*itSrc);
neighborIsAlreadyInList:;
}
}
#endif
| 31.674286 | 121 | 0.611041 | mnentwig |
66b97549d02ce38d4f084c32d7a3ed8d59be8601 | 6,363 | cpp | C++ | packages/monte_carlo/collision/native/test/tstAceLaw11NuclearScatteringEnergyDistribution.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/collision/native/test/tstAceLaw11NuclearScatteringEnergyDistribution.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/collision/native/test/tstAceLaw11NuclearScatteringEnergyDistribution.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------------//
//!
//! \file tstAceLaw5NuclearScatteringEnergyDistribution.cpp
//! \author Eli Moll
//! \brief Ace law 11 neutron scattering energy distribution unit tests
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <iostream>
// Trilinos Includes
#include <Teuchos_UnitTestHarness.hpp>
#include <Teuchos_RCP.hpp>
#include <Teuchos_Array.hpp>
// FRENSIE Includes
#include "MonteCarlo_UnitTestHarnessExtensions.hpp"
#include "MonteCarlo_AceLaw11NuclearScatteringEnergyDistribution.hpp"
#include "Utility_RandomNumberGenerator.hpp"
#include "Utility_WattDistribution.hpp"
//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( AceLaw11NuclearScatteringEnergyDistribution,
sample_lower_bounds )
{
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
a_distribution;
a_distribution.resize(2);
a_distribution[0].first = 1.0;
a_distribution[0].second = 1.0;
a_distribution[1].first = 2.0;
a_distribution[1].second = 2.0;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
b_distribution;
b_distribution.resize(2);
b_distribution[0].first = 1.0;
b_distribution[0].second = 3.0;
b_distribution[1].first = 2.0;
b_distribution[1].second = 4.0;
// Create the fake stream
std::vector<double> fake_stream( 4 );
fake_stream[0] = 0.75;
fake_stream[1] = 0.75;
fake_stream[2] = 0.5;
fake_stream[3] = 0.1;
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
double restriction_energy = 0.05;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution distribution(
a_distribution,
b_distribution,
restriction_energy );
TEST_COMPARE(distribution.sampleEnergy(0.5) ,==,
Utility::WattDistribution::sample( 0.5,
a_distribution[0].second,
b_distribution[0].second,
restriction_energy ));
}
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( AceLaw11NuclearScatteringEnergyDistribution,
sample_upper_bounds )
{
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
a_distribution;
a_distribution.resize(2);
a_distribution[0].first = 1.0;
a_distribution[0].second = 1.0;
a_distribution[1].first = 2.0;
a_distribution[1].second = 2.0;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
b_distribution;
b_distribution.resize(2);
b_distribution[0].first = 1.0;
b_distribution[0].second = 3.0;
b_distribution[1].first = 2.0;
b_distribution[1].second = 4.0;
// Create the fake stream
std::vector<double> fake_stream( 4 );
fake_stream[0] = 0.75;
fake_stream[1] = 0.75;
fake_stream[2] = 0.5;
fake_stream[3] = 0.1;
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
double restriction_energy = 0.05;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution distribution(
a_distribution,
b_distribution,
restriction_energy );
TEST_COMPARE(distribution.sampleEnergy(3.0) ,==,
Utility::WattDistribution::sample( 3.0,
a_distribution[1].second,
b_distribution[1].second,
restriction_energy ));
}
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST( AceLaw11NuclearScatteringEnergyDistribution,
sampleEnergy )
{
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
a_distribution;
a_distribution.resize(2);
a_distribution[0].first = 1.0;
a_distribution[0].second = 1.0;
a_distribution[1].first = 2.0;
a_distribution[1].second = 2.0;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution::EnergyDistribution
b_distribution;
b_distribution.resize(2);
b_distribution[0].first = 1.0;
b_distribution[0].second = 3.0;
b_distribution[1].first = 2.0;
b_distribution[1].second = 4.0;
// Create the fake stream
std::vector<double> fake_stream( 4 );
fake_stream[0] = 0.75;
fake_stream[1] = 0.75;
fake_stream[2] = 0.5;
fake_stream[3] = 0.1;
Utility::RandomNumberGenerator::setFakeStream( fake_stream );
double restriction_energy = 0.05;
MonteCarlo::AceLaw11NuclearScatteringEnergyDistribution distribution(
a_distribution,
b_distribution,
restriction_energy );
TEST_COMPARE(distribution.sampleEnergy(1.5) ,==,
Utility::WattDistribution::sample( 1.5,
1.5,
3.5,
restriction_energy ));
}
//---------------------------------------------------------------------------//
// Custom main function
//---------------------------------------------------------------------------//
int main( int argc, char** argv )
{
Teuchos::CommandLineProcessor& clp = Teuchos::UnitTestRepository::getCLP();
// Initialize the random number generator
Utility::RandomNumberGenerator::createStreams();
Teuchos::GlobalMPISession mpiSession( &argc, &argv );
return Teuchos::UnitTestRepository::runUnitTestsFromMain( argc, argv );
}
//---------------------------------------------------------------------------//
// tstAceLaw11NuclearScatteringDistribution.cpp
//---------------------------------------------------------------------------//
| 33.666667 | 116 | 0.534811 | lkersting |
66bb25af7ec30d134182e4e14368aa4fccf40ea0 | 4,249 | cpp | C++ | VectorTest/Vec3SSE.cpp | albinopapa/VectorTest | bf520ca561a70ef90c3820a797ce60f669693219 | [
"MIT"
] | null | null | null | VectorTest/Vec3SSE.cpp | albinopapa/VectorTest | bf520ca561a70ef90c3820a797ce60f669693219 | [
"MIT"
] | null | null | null | VectorTest/Vec3SSE.cpp | albinopapa/VectorTest | bf520ca561a70ef90c3820a797ce60f669693219 | [
"MIT"
] | null | null | null | #include "Vec3SSE.h"
using namespace SSE_Utils::Float4_Utils;
Vec3SSE::Vec3SSE()
:
v(ZeroPS)
{}
Vec3SSE::Vec3SSE(float S)
:
v(_mm_set1_ps(S)) // Set all elements to S (S, S, S, S)
{
// Zero out the last element as it won't be used (v, v, v, 0.0f)
//FLOAT4 t = _mm_shuffle_ps(v, _mm_setzero_ps(), _MM_SHUFFLE(0, 0, 2, 1));
FLOAT4 t = Shuffle<Axy | Bxy>(ZeroPS, v);
v = Shuffle<Axy | Bxz>(v, t);
}
Vec3SSE::Vec3SSE(float X, float Y, float Z)
:
v(_mm_set_ps(0.0f, Z, Y, X)) // SSE registers are setup backward
{}
Vec3SSE::Vec3SSE(const FLOAT4 &V)
:
v(V)
{}
Vec3SSE::Vec3SSE(const Vector3 &V)
:
v(_mm_set_ps(0.0f, V.z, V.y, V.x))
{}
Vec3SSE::Vec3SSE(const Vec3SSE &V)
:
v(V.v)
{}
Vec3SSE Vec3SSE::operator&(const Vec3SSE &V)const
{
return{ v & V.v };
}
Vec3SSE Vec3SSE::operator|(const Vec3SSE &V)const
{
return v | V.v;
}
Vec3SSE Vec3SSE::AndNot(const Vec3SSE &V)
{
return{ SSE_Utils::Float4_Utils::AndNot(v, V.v) };
}
Vec3SSE Vec3SSE::operator-()const
{
return{ -v };
}
Vec3SSE Vec3SSE::operator+(const Vec3SSE &V)const
{
return v + V.v;
}
Vec3SSE Vec3SSE::operator-(const Vec3SSE &V)const
{
return v - V.v;
}
Vec3SSE Vec3SSE::operator*(const float S)const
{
return v * S;
}
Vec3SSE Vec3SSE::operator*(const Vec3SSE &V)const
{
return v * V.v;
}
Vec3SSE Vec3SSE::operator/(const float S)const
{
return v / S;
}
Vec3SSE Vec3SSE::operator/(const Vec3SSE &V)const
{
return v / V.v;
}
Vec3SSE & Vec3SSE::operator+=(const Vec3SSE &V)
{
v += V.v;
return (*this);
}
Vec3SSE & Vec3SSE::operator-=(const Vec3SSE &V)
{
v -= V.v;
return (*this);
}
Vec3SSE & Vec3SSE::operator*=(const Vec3SSE &V)
{
v *= V.v;
return (*this);
}
Vec3SSE & Vec3SSE::operator/=(const Vec3SSE &V)
{
v /= V.v;
v = v & LoadFloat4(xyzMask);
return (*this);
}
Vec3SSE Vec3SSE::MultiplyAdd(const Vec3SSE &V0, const Vec3SSE &V1)
{
return V1.v + (v * V0.v);
}
Vec3SSE Vec3SSE::Dot(const Vec3SSE &V)const
{
/*
The dot product of a vector3 is X0*X1 + Y0*Y1 + Z0*Z1
In SSE we can vertically multiply:
X0 Y0 Z0
* X1 Y1 Z1
------------------
Xr Yr Zr
In order to add the results together we have to shuffle the elements
YrXrZr
then add them together
Xr Yr Zr
+ Yr Xr Zr
------------------
XYr YXr ZZr
This means X and Y have the same values but Z has been doubled, so we
have to shuffle in the Zr from the previous operation and add it's value
to the XYrYXr sum and copy XYr to the Zr position so that all 3 (X, Y and Z)
all have the same result
XYr YXr Zr
+ Zr Zr XYr
------------------
XYZr YXZr ZXYr
*/
FLOAT4 t0 = v * V.v;
FLOAT4 t1 = Shuffle<Ayx | Bzw>(t0, t0);
t0 += t1;
t0 = Shuffle<Axy | Bzw>(t0, t1);
t1 = Shuffle<Azz | Bxw>(t0, t0);
t0 += t1;
return t0;
}
Vec3SSE Vec3SSE::Cross(const Vec3SSE &V)const
{
FLOAT4 u0 = Shuffle<Ayz | Bxw>(v);
FLOAT4 u1 = Shuffle<Azx | Byw>(v);
FLOAT4 v0 = Shuffle<Ayz | Bxw>(V.v);
FLOAT4 v1 = Shuffle<Azx | Byw>(V.v);
FLOAT4 result = (u0 * v1) - (u1 * v0);
return result;
}
Vec3SSE Vec3SSE::Length()const
{
return{ SqrRoot(Dot(*this).v) };
}
Vec3SSE Vec3SSE::LengthSquare()const
{
return Dot(*this);
}
Vec3SSE Vec3SSE::InverseLength()const
{
FLOAT4 t0 = RecipSqrRoot(LengthSquare().v);
// Zero W component
FLOAT4 t1 = Shuffle<Axy | Bxx>(t0, ZeroPS);
t0 = Shuffle<Axy | Bxz>(t0, t1);
return t0;
}
Vec3SSE Vec3SSE::Normalize()
{
return ((*this) * InverseLength());
}
Vec3SSE Vec3SSE::SplatX()const
{
return Shuffle<XXXX>(v);
}
Vec3SSE Vec3SSE::SplatY()const
{
return Shuffle<YYYY>(v);
}
Vec3SSE Vec3SSE::SplatZ()const
{
return Shuffle<ZZZZ>(v);
}
Vector3 Vec3SSE::StoreFloat()const
{
Vector3 temp;
temp.x = X();
temp.y = Y();
temp.z = Z();
return temp;
}
Vector3 Vec3SSE::StoreInt()const
{
Vector3 temp;
temp.b = _mm_cvt_ss2si(v);
temp.g = _mm_cvt_ss2si(Shuffle<Ayx>(v));
temp.r = _mm_cvt_ss2si(Shuffle<Azx>(v));
return temp;
}
Vector3 Vec3SSE::StoreIntCast()
{
Vector3 temp;
Vector4 t;
_mm_store_si128((PDQWORD)&t, _mm_castps_si128(v));
temp.ix = t.iX;
temp.iy = t.iY;
temp.iz = t.iZ;
return temp;
}
float Vec3SSE::X()const
{
return _mm_cvtss_f32(v);
}
float Vec3SSE::Y()const
{
Vec3SSE t = SplatY();
return _mm_cvtss_f32(t.v);
}
float Vec3SSE::Z()const
{
Vec3SSE t = SplatZ();
return _mm_cvtss_f32(t.v);
} | 18.393939 | 77 | 0.646976 | albinopapa |
66bbac435f7a256099554ba9ec37f3814fb5bdef | 547 | cpp | C++ | docs/examples/Bitmap_getAddr32.cpp | mohad12211/skia | 042a53aa094715e031ebad4da072524ace316744 | [
"BSD-3-Clause"
] | 6,304 | 2015-01-05T23:45:12.000Z | 2022-03-31T09:48:13.000Z | docs/examples/Bitmap_getAddr32.cpp | mohad12211/skia | 042a53aa094715e031ebad4da072524ace316744 | [
"BSD-3-Clause"
] | 67 | 2016-04-18T13:30:02.000Z | 2022-03-31T23:06:55.000Z | docs/examples/Bitmap_getAddr32.cpp | mohad12211/skia | 042a53aa094715e031ebad4da072524ace316744 | [
"BSD-3-Clause"
] | 1,231 | 2015-01-05T03:17:39.000Z | 2022-03-31T22:54:58.000Z | // Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "tools/fiddle/examples.h"
// HASH=837a2bcc9fb9ce617a3420956cefc64a
REG_FIDDLE(Bitmap_getAddr32, 256, 256, true, 3) {
void draw(SkCanvas* canvas) {
uint32_t* row0 = source.getAddr32(0, 0);
uint32_t* row1 = source.getAddr32(0, 1);
size_t interval = (row1 - row0) * source.bytesPerPixel();
SkDebugf("addr interval %c= rowBytes\n", interval == source.rowBytes() ? '=' : '!');
}
} // END FIDDLE
| 42.076923 | 100 | 0.696527 | mohad12211 |
66bc9546b85d0c4f77b87c79cf4bce72b7965ec1 | 234 | c++ | C++ | 10.1.character.c++ | Sambitcr-7/DSA-C- | f3c80f54fa6160a99f39a934f330cdf40711de50 | [
"Apache-2.0"
] | null | null | null | 10.1.character.c++ | Sambitcr-7/DSA-C- | f3c80f54fa6160a99f39a934f330cdf40711de50 | [
"Apache-2.0"
] | null | null | null | 10.1.character.c++ | Sambitcr-7/DSA-C- | f3c80f54fa6160a99f39a934f330cdf40711de50 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
char arr[100] = "apple";
int i=0;
while(arr[i]!='\0')
{
cout<<arr[i]<<endl;
i++;
}
return 0;
}
| 9.75 | 29 | 0.380342 | Sambitcr-7 |
66c438e51bf580136bf8a0c9ec54ee9d9a0180e3 | 1,192 | cpp | C++ | Codeforces/GYM/UTPC Contest 10-29-21 Div. 2 (Beginner)/E.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 3 | 2020-11-01T06:31:30.000Z | 2022-02-21T20:37:51.000Z | Codeforces/GYM/UTPC Contest 10-29-21 Div. 2 (Beginner)/E.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | null | null | null | Codeforces/GYM/UTPC Contest 10-29-21 Div. 2 (Beginner)/E.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 1 | 2021-05-05T18:56:31.000Z | 2021-05-05T18:56:31.000Z | /**
* author: MaGnsi0
* created: 21.11.2021 15:54:14
**/
#include <bits/stdc++.h>
using namespace std;
void dfs(vector<vector<int>>& adj, int& x, int& maxd, int v = 0, int curd = 0, int par = -1) {
if (curd > maxd) {
x = v;
maxd = curd;
}
for (auto& u : adj[v]) {
if (u == par) {
continue;
}
dfs(adj, x, maxd, u, curd + 1, v);
}
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int n;
cin >> n;
vector<vector<int>> adj1(n);
for (int i = 0; i < n - 1; ++i) {
int u, v;
cin >> u >> v;
u--, v--;
adj1[u].push_back(v);
adj1[v].push_back(u);
}
int x1 = 0, x2 = 0, maxd1;
maxd1 = 0;
dfs(adj1, x1, maxd1);
maxd1 = 0;
dfs(adj1, x2, maxd1, x1);
int m;
cin >> m;
vector<vector<int>> adj2(m);
for (int i = 0; i < m - 1; ++i) {
int u, v;
cin >> u >> v;
u--, v--;
adj2[u].push_back(v);
adj2[v].push_back(u);
}
int x3 = 0, x4 = 0, maxd2;
maxd2 = 0;
dfs(adj2, x3, maxd2);
maxd2 = 0;
dfs(adj2, x4, maxd2, x3);
cout << maxd1 + maxd2 + 2;
}
| 21.285714 | 94 | 0.439597 | MaGnsio |
66cb64a7e7ab92f4f426ffa12b5634eee9cf3242 | 4,161 | cpp | C++ | test/Filesystem.test.cpp | Brett208/nas2d-core | f9506540f32d34f3c60bc83b87b34460d582ae81 | [
"Zlib"
] | null | null | null | test/Filesystem.test.cpp | Brett208/nas2d-core | f9506540f32d34f3c60bc83b87b34460d582ae81 | [
"Zlib"
] | null | null | null | test/Filesystem.test.cpp | Brett208/nas2d-core | f9506540f32d34f3c60bc83b87b34460d582ae81 | [
"Zlib"
] | null | null | null | #include "NAS2D/Filesystem.h"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
TEST(Filesystem, ConstructDestruct) {
EXPECT_NO_THROW(NAS2D::Filesystem fs("", "NAS2DUnitTests", "LairWorks"));
}
class FilesystemTest : public ::testing::Test {
protected:
static constexpr auto AppName = "NAS2DUnitTests";
static constexpr auto OrganizationName = "LairWorks";
FilesystemTest() :
fs("", AppName, OrganizationName)
{
fs.mount(fs.basePath());
fs.mount("data/");
fs.mountReadWrite(fs.prefPath());
}
NAS2D::Filesystem fs;
};
TEST_F(FilesystemTest, basePath) {
// Result is a directory, and should end with a directory separator
EXPECT_THAT(fs.basePath(), testing::EndsWith(fs.dirSeparator()));
}
TEST_F(FilesystemTest, prefPath) {
// Result is a directory, and should end with a directory separator
EXPECT_THAT(fs.prefPath(), testing::EndsWith(fs.dirSeparator()));
EXPECT_THAT(fs.prefPath(), testing::HasSubstr(AppName));
}
TEST_F(FilesystemTest, extension) {
EXPECT_EQ(".txt", fs.extension("subdir/file.txt"));
EXPECT_EQ(".txt", fs.extension("file.txt"));
EXPECT_EQ(".reallyLongExtensionName", fs.extension("file.reallyLongExtensionName"));
EXPECT_EQ(".a", fs.extension("file.a"));
EXPECT_EQ(".file", fs.extension(".file"));
EXPECT_EQ(".", fs.extension("file."));
EXPECT_EQ("", fs.extension("file"));
}
TEST_F(FilesystemTest, workingPath) {
EXPECT_EQ("data/", fs.workingPath("data/file.extension"));
EXPECT_EQ("data/subfolder/", fs.workingPath("data/subfolder/file.extension"));
EXPECT_EQ("anotherFolder/", fs.workingPath("anotherFolder/file.extension"));
EXPECT_EQ("", fs.workingPath("file.extension"));
}
TEST_F(FilesystemTest, searchPath) {
auto pathList = fs.searchPath();
EXPECT_EQ(3u, pathList.size());
EXPECT_THAT(pathList, Contains(testing::HasSubstr("NAS2DUnitTests")));
EXPECT_THAT(pathList, Contains(testing::HasSubstr("data/")));
}
TEST_F(FilesystemTest, directoryList) {
auto pathList = fs.directoryList("");
EXPECT_LE(1u, pathList.size());
EXPECT_THAT(pathList, Contains(testing::StrEq("file.txt")));
}
TEST_F(FilesystemTest, exists) {
EXPECT_TRUE(fs.exists("file.txt"));
}
TEST_F(FilesystemTest, open) {
const auto file = fs.open("file.txt");
EXPECT_EQ("Test data\n", file.bytes());
}
// Test a few related methods. Some don't test well standalone.
TEST_F(FilesystemTest, writeReadDeleteExists) {
const std::string testFilename = "TestFile.txt";
const std::string testData = "Test file contents";
const auto file = NAS2D::File(testData, testFilename);
EXPECT_NO_THROW(fs.write(file));
EXPECT_TRUE(fs.exists(testFilename));
// Try to overwrite file, with and without permission
EXPECT_NO_THROW(fs.write(file));
EXPECT_THROW(fs.write(file, false), std::runtime_error);
const auto fileRead = fs.open(testFilename);
EXPECT_EQ(testData, fileRead.bytes());
EXPECT_NO_THROW(fs.del(testFilename));
EXPECT_FALSE(fs.exists(testFilename));
EXPECT_THROW(fs.del(testFilename), std::runtime_error);
}
TEST_F(FilesystemTest, isDirectoryMakeDirectory) {
const std::string fileName = "file.txt";
const std::string folderName = "subfolder/";
EXPECT_TRUE(fs.exists(fileName));
EXPECT_FALSE(fs.isDirectory(fileName));
EXPECT_NO_THROW(fs.makeDirectory(folderName));
EXPECT_TRUE(fs.exists(folderName));
EXPECT_TRUE(fs.isDirectory(folderName));
fs.del(folderName);
EXPECT_FALSE(fs.exists(folderName));
EXPECT_FALSE(fs.isDirectory(folderName));
}
TEST_F(FilesystemTest, mountUnmount) {
const std::string extraMount = "data/extraData/";
const std::string extraFile = "extraFile.txt";
EXPECT_FALSE(fs.exists(extraFile));
EXPECT_NO_THROW(fs.mount(extraMount));
EXPECT_THAT(fs.searchPath(), Contains(testing::HasSubstr(extraMount)));
EXPECT_TRUE(fs.exists(extraFile));
EXPECT_NO_THROW(fs.unmount(extraMount));
EXPECT_FALSE(fs.exists(extraFile));
EXPECT_THROW(fs.mount("nonExistentPath/"), std::runtime_error);
}
TEST_F(FilesystemTest, dirSeparator) {
// Varies by platform, so we can't know the exact value ("/", "\", ":")
// New platforms may choose a new unique value
// Some platforms may not even have a hierarchal filesystem ("")
EXPECT_NO_THROW(fs.dirSeparator());
}
| 30.595588 | 85 | 0.738765 | Brett208 |
66cd26240c0319321dde87beff637e079f6e42fa | 1,416 | cpp | C++ | module-platform/rt1051/src/RT1051Platform.cpp | buk7456/MuditaOS | 06ef1e131b27b0f397cc615c96d51bede7050423 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-platform/rt1051/src/RT1051Platform.cpp | buk7456/MuditaOS | 06ef1e131b27b0f397cc615c96d51bede7050423 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-platform/rt1051/src/RT1051Platform.cpp | buk7456/MuditaOS | 06ef1e131b27b0f397cc615c96d51bede7050423 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2022, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#include <platform/rt1051/RT1051Platform.hpp>
#include "BlockDeviceFactory.hpp"
#include <bsp/bsp.hpp>
#include <purefs/vfs_subsystem.hpp>
#include <exception>
#include <Logger.hpp>
using platform::rt1051::BlockDeviceFactory;
using platform::rt1051::RT1051Platform;
RT1051Platform::RT1051Platform()
{
bsp::board_init();
bsp::register_exit_functions(Log::Logger::destroyInstance);
}
void RT1051Platform::init()
{
initFilesystem();
::platform::Platform::initCommonUserFolders();
}
void RT1051Platform::initFilesystem()
{
if (usesFilesystem) {
throw std::runtime_error("Filesystem already initialized");
}
auto blockDeviceFactory = std::make_unique<BlockDeviceFactory>();
vfs = purefs::subsystem::initialize(std::move(blockDeviceFactory));
if (int err = purefs::subsystem::mount_defaults(); err != 0) {
throw std::runtime_error("Failed to initiate filesystem: " + std::to_string(err));
}
usesFilesystem = true;
}
void platform::rt1051::RT1051Platform::deinit()
{
if (usesFilesystem) {
if (int err = purefs::subsystem::unmount_all(); err != 0) {
throw std::runtime_error("Failed to unmount all: " + std::to_string(err));
}
usesFilesystem = false;
}
}
| 27.230769 | 91 | 0.681497 | buk7456 |
66cd5e1884982ac8ef79ca8479e8f2384f267403 | 13,977 | hpp | C++ | glm/detail/type_vec5.hpp | gchunev/Dice4D | f96db406204fdca0155d26db856b66a2afd4e664 | [
"MIT"
] | 1 | 2019-05-22T08:53:46.000Z | 2019-05-22T08:53:46.000Z | glm/detail/type_vec5.hpp | gchunev/Dice4D | f96db406204fdca0155d26db856b66a2afd4e664 | [
"MIT"
] | null | null | null | glm/detail/type_vec5.hpp | gchunev/Dice4D | f96db406204fdca0155d26db856b66a2afd4e664 | [
"MIT"
] | null | null | null | /// @ref core
/// @file glm/detail/type_vec5.hpp
#pragma once
#include "qualifier.hpp"
#include <cstddef>
namespace glm
{
template<typename T, qualifier Q>
struct vec<5, T, Q>
{
// -- Implementation detail --
typedef T value_type;
typedef vec<5, T, Q> type;
typedef vec<5, bool, Q> bool_type;
// -- Data --
# if GLM_SILENT_WARNINGS == GLM_ENABLE
# if GLM_COMPILER & GLM_COMPILER_GCC
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wpedantic"
# elif GLM_COMPILER & GLM_COMPILER_CLANG
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wgnu-anonymous-struct"
# pragma clang diagnostic ignored "-Wnested-anon-types"
# elif GLM_COMPILER & GLM_COMPILER_VC
# pragma warning(push)
# pragma warning(disable: 4201) // nonstandard extension used : nameless struct/union
# if GLM_CONFIG_ALIGNED_GENTYPES == GLM_ENABLE
# pragma warning(disable: 4324) // structure was padded due to alignment specifier
# endif
# endif
# endif
# if GLM_CONFIG_XYZW_ONLY
T x, y, z, w, v;
# elif GLM_CONFIG_ANONYMOUS_STRUCT == GLM_ENABLE
union
{
struct{ T x, y, z, w, v; };
struct{ T r, g, b, a, d; };
struct{ T s, t, p, q, k; };
typename detail::storage<5, T, detail::is_aligned<Q>::value>::type data;
};
# else
union { T x, y, z, w, v; };
union { T r, g, b, a, d; };
union { T s, t, p, q, k; };
# endif//GLM_LANG
# if GLM_SILENT_WARNINGS == GLM_ENABLE
# if GLM_COMPILER & GLM_COMPILER_CLANG
# pragma clang diagnostic pop
# elif GLM_COMPILER & GLM_COMPILER_GCC
# pragma GCC diagnostic pop
# elif GLM_COMPILER & GLM_COMPILER_VC
# pragma warning(pop)
# endif
# endif
// -- Component accesses --
/// Return the count of components of the vector
typedef length_t length_type;
GLM_FUNC_DECL static GLM_CONSTEXPR length_type length(){return 5;}
GLM_FUNC_DECL GLM_CONSTEXPR T & operator[](length_type i);
GLM_FUNC_DECL GLM_CONSTEXPR T const& operator[](length_type i) const;
// -- Implicit basic constructors --
GLM_FUNC_DECL GLM_CONSTEXPR vec() GLM_DEFAULT;
GLM_FUNC_DECL GLM_CONSTEXPR vec(vec const& v) GLM_DEFAULT;
template<qualifier P>
GLM_FUNC_DECL GLM_CONSTEXPR vec(vec<5, T, P> const& v);
// -- Explicit basic constructors --
GLM_FUNC_DECL GLM_CONSTEXPR explicit vec(T scalar);
GLM_FUNC_DECL GLM_CONSTEXPR vec(T a, T b, T c, T d, T e);
// -- Conversion scalar constructors --
template<typename U, qualifier P>
GLM_FUNC_DECL GLM_CONSTEXPR explicit vec(vec<1, U, P> const& v);
// -- Conversion vector constructors --
template<typename A, typename B, qualifier P>
GLM_FUNC_DECL GLM_CONSTEXPR vec(vec<4, A, P> const& _xyzw, B _v);
/// Explicit conversions
template<typename U, qualifier P>
GLM_FUNC_DECL GLM_CONSTEXPR GLM_EXPLICIT vec(vec<5, U, P> const& v);
// -- Unary arithmetic operators --
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q>& operator=(vec<5, T, Q> const& v) GLM_DEFAULT;
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator=(vec<5, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator+=(U scalar);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator+=(vec<1, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator+=(vec<5, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator-=(U scalar);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator-=(vec<1, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator-=(vec<5, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator*=(U scalar);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator*=(vec<1, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator*=(vec<5, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator/=(U scalar);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator/=(vec<1, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator/=(vec<5, U, Q> const& v);
// -- Increment and decrement operators --
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator++();
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator--();
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator++(int);
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator--(int);
// -- Unary bit operators --
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator%=(U scalar);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator%=(vec<1, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator%=(vec<5, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator&=(U scalar);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator&=(vec<1, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator&=(vec<5, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator|=(U scalar);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator|=(vec<1, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator|=(vec<5, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator^=(U scalar);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator^=(vec<1, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator^=(vec<5, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator<<=(U scalar);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator<<=(vec<1, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator<<=(vec<5, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator>>=(U scalar);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator>>=(vec<1, U, Q> const& v);
template<typename U>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> & operator>>=(vec<5, U, Q> const& v);
};
// -- Unary operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator+(vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator-(vec<5, T, Q> const& v);
// -- Binary operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator+(vec<5, T, Q> const& v, T scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator+(vec<5, T, Q> const& v, vec<1, T, Q> const& scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator+(T scalar, vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator+(vec<1, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator+(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator-(vec<5, T, Q> const& v, T scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator-(vec<5, T, Q> const& v1, vec<1, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator-(T scalar, vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator-(vec<1, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator-(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator*(vec<5, T, Q> const& v, T scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator*(vec<5, T, Q> const& v1, vec<1, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator*(T scalar, vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator*(vec<1, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator*(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator/(vec<5, T, Q> const& v, T scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator/(vec<5, T, Q> const& v1, vec<1, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator/(T scalar, vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator/(vec<1, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator/(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator%(vec<5, T, Q> const& v, T scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator%(vec<5, T, Q> const& v1, vec<1, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator%(T scalar, vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator%(vec<1, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator%(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator&(vec<5, T, Q> const& v1, T scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator&(vec<5, T, Q> const& v1, vec<1, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator&(T scalar, vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator&(vec<1, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator&(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator|(vec<5, T, Q> const& v, T scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator|(vec<5, T, Q> const& v1, vec<1, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator|(T scalar, vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator|(vec<1, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator|(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator^(vec<5, T, Q> const& v, T scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator^(vec<5, T, Q> const& v1, vec<1, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator^(T scalar, vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator^(vec<1, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator^(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator<<(vec<5, T, Q> const& v, T scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator<<(vec<5, T, Q> const& v1, vec<1, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator<<(T scalar, vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator<<(vec<1, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator<<(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator>>(vec<5, T, Q> const& v, T scalar);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator>>(vec<5, T, Q> const& v1, vec<1, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator>>(T scalar, vec<5, T, Q> const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator>>(vec<1, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator>>(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, T, Q> operator~(vec<5, T, Q> const& v);
// -- Boolean operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR bool operator==(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<typename T, qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR bool operator!=(vec<5, T, Q> const& v1, vec<5, T, Q> const& v2);
template<qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, bool, Q> operator&&(vec<5, bool, Q> const& v1, vec<5, bool, Q> const& v2);
template<qualifier Q>
GLM_FUNC_DECL GLM_CONSTEXPR vec<5, bool, Q> operator||(vec<5, bool, Q> const& v1, vec<5, bool, Q> const& v2);
}//namespace glm
#ifndef GLM_EXTERNAL_TEMPLATE
#include "type_vec5.inl"
#endif//GLM_EXTERNAL_TEMPLATE
| 38.717452 | 110 | 0.686628 | gchunev |
66cfd0d171eeeb1358dba701d9c51814d629158d | 2,469 | cpp | C++ | stringext.cpp | AlpsMonaco/BinInCpp | feffcda6ae63b81946aefbaa88dbb1559c22217f | [
"MIT"
] | null | null | null | stringext.cpp | AlpsMonaco/BinInCpp | feffcda6ae63b81946aefbaa88dbb1559c22217f | [
"MIT"
] | null | null | null | stringext.cpp | AlpsMonaco/BinInCpp | feffcda6ae63b81946aefbaa88dbb1559c22217f | [
"MIT"
] | null | null | null | #include "stringext.h"
namespace stringext
{
void ReplaceAll(std::string &s, const std::string &from, const std::string &to)
{
size_t index = 0;
while ((index = s.find(from, index)) != std::string::npos)
{
s.replace(index, from.length(), to);
index += to.length();
}
}
void ReplaceAll(std::string &s, const char *from, const char *to) { ReplaceAll(s, std::string(from), std::string(to)); }
std::vector<std::string> Split(const std::string &s, const std::string &sep)
{
size_t begin = 0;
size_t end = 0;
std::vector<std::string> v;
while ((end = s.find(sep, begin)) != std::string::npos)
{
v.push_back(s.substr(begin, end - begin));
begin = end + sep.length();
}
if (s.length() > begin)
v.push_back(s.substr(begin, s.length() - begin));
return v;
}
std::vector<std::string> Split(const std::string &s, const char *sep) { return Split(s, std::string(sep)); }
const std::string SpaceCharacters = " \t\r\n";
void TrimSpace(std::string &s)
{
TrimSpaceLeft(s);
TrimSpaceRight(s);
}
void TrimSpaceLeft(std::string &s)
{
size_t size = 0;
for (auto it = s.begin(); it < s.end(); it++)
{
if (SpaceCharacters.find(*it) != std::string::npos)
size++;
else
break;
}
s.replace(0, size, "");
}
void TrimSpaceRight(std::string &s)
{
size_t size = 0;
for (auto it = s.rbegin(); it < s.rend(); it++)
{
if (SpaceCharacters.find(*it) != std::string::npos)
size++;
else
break;
}
s.replace(s.length() - size, size, "");
}
std::string Join(const std::vector<std::string> &stringVector, const std::string &sep)
{
if (stringVector.size() == 0)
return "";
std::string result;
for (std::vector<std::string>::const_iterator it = stringVector.begin(); it < stringVector.end() - 1; it++)
result += *it + sep;
result += *(stringVector.end() - 1);
return result;
}
std::string Join(const std::vector<std::string> &stringVector, const char *sep)
{
if (stringVector.size() == 0)
return "";
std::string result;
for (std::vector<std::string>::const_iterator it = stringVector.begin(); it < stringVector.end() - 1; it++)
result += *it + sep;
result += *(stringVector.end() - 1);
return result;
}
void ToUpper(std::string &s)
{
for (std::string::iterator it = s.begin(); it < s.end(); it++)
*it = ::toupper(*it);
}
void ToLower(std::string &s)
{
for (std::string::iterator it = s.begin(); it < s.end(); it++)
*it = ::tolower(*it);
}
}
| 24.69 | 121 | 0.603888 | AlpsMonaco |
66d2e2e4b36375ec233ca1ff385b825f3712d3c7 | 704 | cpp | C++ | matu137.cpp | NewtonVan/Fxxk_Y0u_m47u | d303c7f13c074b5462ac8390a9ff94e546099fac | [
"MIT"
] | 1 | 2020-09-26T16:47:16.000Z | 2020-09-26T16:47:16.000Z | matu137.cpp | NewtonVan/Fxxk_Y0u_m47u | d303c7f13c074b5462ac8390a9ff94e546099fac | [
"MIT"
] | null | null | null | matu137.cpp | NewtonVan/Fxxk_Y0u_m47u | d303c7f13c074b5462ac8390a9ff94e546099fac | [
"MIT"
] | 1 | 2020-09-26T16:47:40.000Z | 2020-09-26T16:47:40.000Z | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
class Ctriangle{
double a, b, c;
public:
Ctriangle(double aa, double bb, double cc) : a(aa), b(bb), c(cc){}
Ctriangle(){}
void display();
double GetArea();
double GetPerimeter();
};
void Ctriangle::display()
{
printf("Ctriangle:a=%.0f,b=%.0f,c=%.0f\n", a, b, c);
}
double Ctriangle::GetPerimeter()
{
return a+b+c;
}
double Ctriangle::GetArea()
{
double p= (a+b+c)/2;
return sqrt(p*(p-a)*(p-b)*(p-c));
}
int main(){
double a,b,c;
cin>>a>>b>>c;
Ctriangle T(a,b,c);
T.display();
cout<<"Perimeter:"<<T.GetPerimeter()<<endl;
cout<<"Area:"<<T.GetArea()<<endl;
return 0;
}
| 17.170732 | 67 | 0.629261 | NewtonVan |
202d43b10ae1b8103a0820ce6478817f52ba4094 | 1,261 | cpp | C++ | cuda/CudaPartition.cpp | jdinkla/parallel2015_gpucomputing | 15654399897d891637bb466bcca0e5aa73c22fce | [
"MIT"
] | 1 | 2020-03-13T18:40:07.000Z | 2020-03-13T18:40:07.000Z | cuda/CudaPartition.cpp | jdinkla/parallel2015_gpucomputing | 15654399897d891637bb466bcca0e5aa73c22fce | [
"MIT"
] | 1 | 2019-06-09T14:33:31.000Z | 2019-06-18T20:35:30.000Z | cuda/CudaPartition.cpp | jdinkla/parallel2015_gpucomputing | 15654399897d891637bb466bcca0e5aa73c22fce | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2015 by Joern Dinkla, www.dinkla.com, All rights reserved.
*
* See the LICENSE file in the root directory.
*/
#include "CudaPartition.h"
using namespace std;
vector<CudaPartition> calc_partitions(GPUs& gpus, const Extent2& extent)
{
vector<CudaPartition> partitions;
const int num_gpus = gpus.get_number_of_gpus();
const int width = extent.get_width();
const int height = extent.get_height();
partition_t ps1 = partition(0, height - 1, num_gpus);
partition_t ps2 = partition(0, height - 1, num_gpus, 1);
partitions.clear();
int i = 0;
for (auto& gpu : gpus)
{
int y_low, y_hi, y_len;
y_low = ps2[i].first;
y_hi = ps2[i].second;
y_len = y_hi - y_low + 1;
Extent2 local_extent_with_overlap(width, y_len);
Pos2 offset_with_overlap(0, y_low);
y_low = ps1[i].first;
y_hi = ps1[i].second;
y_len = y_hi - y_low + 1;
Extent2 local_extent_without_overlap(width, y_len);
Pos2 offset_without_overlap(0, y_low);
framework f{ gpu };
data d{ XExtent2(extent, local_extent_with_overlap, offset_with_overlap, local_extent_without_overlap, offset_without_overlap) };
CudaPartition p{ i, f, d };
partitions.push_back(p);
i++;
}
return partitions;
}
| 23.792453 | 132 | 0.680412 | jdinkla |
20340d83f323bb09267d40a675a18c7c2f7c80d2 | 9,849 | cpp | C++ | windows_agent/TestCollect/SoftwareCollector.cpp | syslist/Syslist | 1b8c1051a6423a98bdc09d55904f2de63b3fe95c | [
"MIT"
] | 7 | 2016-08-07T01:11:30.000Z | 2021-01-27T11:03:02.000Z | windows_agent/TestCollect/SoftwareCollector.cpp | syslist/Syslist | 1b8c1051a6423a98bdc09d55904f2de63b3fe95c | [
"MIT"
] | 1 | 2018-07-02T14:01:04.000Z | 2018-07-02T14:01:04.000Z | windows_agent/TestCollect/SoftwareCollector.cpp | syslist/Syslist | 1b8c1051a6423a98bdc09d55904f2de63b3fe95c | [
"MIT"
] | 6 | 2016-12-01T02:11:39.000Z | 2022-03-26T03:31:27.000Z | #include "stdafx.h"
#include "SoftwareCollector.h"
#include "KeyDecode.h"
#include <sstream>
char SW_INFO_PATH[] = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
char SW_MS_OFFICE_PATH[] = "Software\\Microsoft\\Office";
long SW_INFO_PATH_LEN = sizeof (SW_INFO_PATH);
char* SWCL_TAG = "SoftwareList";
char* SWC_TAG = "Program";
static RegObjValueEntry ProcessorItems[] = {
RegObjValueEntry("DisplayName"),
RegObjValueEntry("DisplayVersion"),
RegObjValueEntry("Publisher"),
RegObjValueEntry("VersionMajor"),
RegObjValueEntry("VersionMinor"),
(NULL)
};
static std::map<std::string,std::string> MSOffice10PlusMap;
static std::map<std::string,std::string> MSOffice10PlusMapID;
static std::map<int,std::string> MSOfficePre10Map;
long PopulateOfficeMap()
{
AutoRegKey EnumKey;
long Status;
#ifdef INSTRUMENTED
MessageBox (NULL, "Office Zero", "Report", MB_OK);
#endif
Status = RegOpenKeyEx (HKEY_LOCAL_MACHINE, SW_MS_OFFICE_PATH, 0, KEY_READ, &EnumKey);
W32_RETURN_ON_ERROR(Status);
#ifdef INSTRUMENTED
MessageBox (NULL, "Office Alpha", "Report", MB_OK);
#endif
DWORD ItemCount = 0;
Status = RegQueryInfoKey(EnumKey, // HKEY
NULL, // lpClass
NULL, // lpcbClass
NULL, // lpReserved
&ItemCount, //lpcSubKeys
NULL, // lpcbMaxSubKeyLen
NULL, // lpcbMaxClassLen
NULL, // lpcValues
NULL, // lpcbMaxValueNameLen
NULL, // lpcbMaxValueLen
NULL, // lpcbSecurityDescriptor
NULL); // lpftLastWriteTime
W32_RETURN_ON_ERROR(Status);
#ifdef INSTRUMENTED
MessageBox (NULL, "Office Beta", "Report", MB_OK);
#endif
long EnumIndex;
char EnumSubKeyNameBuf[256];
DWORD EnumSubKeyNameLen;
for (EnumIndex = 0; EnumIndex < ItemCount; EnumIndex ++) {
EnumSubKeyNameLen = 256;
Status = RegEnumKeyExA(EnumKey, EnumIndex, EnumSubKeyNameBuf, &EnumSubKeyNameLen, NULL, NULL, NULL, NULL);
if (Status == ERROR_NO_MORE_ITEMS)
break;
else {
W32_RETURN_ON_ERROR(Status);
}
#ifdef INSTRUMENTED_DEEP
MessageBox (NULL, "Office Gamma", "Report", MB_OK);
#endif
// Skip it this entry if it was not a version number
if (!isdigit(EnumSubKeyNameBuf[0])) {
continue;
}
int VersionNum;
int ScanCount = 0;
ScanCount = sscanf (EnumSubKeyNameBuf,"%d", &VersionNum);
if (ScanCount != 1) {
continue;
}
AutoRegKey EnumSubKey;
std::ostringstream RegInfoSubPath;
RegInfoSubPath << SW_MS_OFFICE_PATH << "\\" << EnumSubKeyNameBuf << "\\" << "Registration";
// Pre version 10 cuts straight to the chase with a sub key called ProductID
if (VersionNum < 10) {
RegInfoSubPath << "\\" << "ProductID";
}
Status = RegOpenKeyEx (HKEY_LOCAL_MACHINE, RegInfoSubPath.str().c_str(), 0, KEY_READ, &EnumSubKey);
if (Status != ERROR_SUCCESS) {
continue;
}
#ifdef INSTRUMENTED_DEEP
MessageBox (NULL, "Office Delta", "Report", MB_OK);
#endif
if (VersionNum < 10) {
// Old Style Prog ID extraction - The registration
// key has the information we need - simply extract
// it and add to the pre version 10 table - We index
// off of the version number later to match it up
char ProdID[256];
unsigned long ItemSize = 256;
DWORD ItemType = REG_SZ;
#ifdef INSTRUMENTED_DEEP
MessageBox (NULL, "Office EpsilonAlpha", "Report", MB_OK);
#endif
Status = RegQueryValueEx(
EnumSubKey, // handle to key to query
NULL, // address of name of value to query
NULL, // reserved
&ItemType, // address of buffer for value type
(unsigned char *) ProdID, // address of data buffer
&ItemSize // address of data buffer size
);
if (Status != ERROR_SUCCESS) {
continue;
}
#ifdef INSTRUMENTED_DEEP
MessageBox (NULL, "Office EpsilonBeta", "Report", MB_OK);
#endif
MSOfficePre10Map[VersionNum] = std::string(ProdID);
}
else {
// New Style Prog ID extraction - The registration
// key has the information in a series of GUID
// indexed sub keys, Those GUID keys have a ProductID
// value that has what we need - we index off of the
// GUID later to match it up
unsigned long RegCount = 0;
Status = RegQueryInfoKey(EnumSubKey, // HKEY
NULL, // lpClass
NULL, // lpcbClass
NULL, // lpReserved
&RegCount, //lpcSubKeys
NULL, // lpcbMaxSubKeyLen
NULL, // lpcbMaxClassLen
NULL, // lpcValues
NULL, // lpcbMaxValueNameLen
NULL, // lpcbMaxValueLen
NULL, // lpcbSecurityDescriptor
NULL); // lpftLastWriteTime
if (Status != ERROR_SUCCESS) {
continue;
}
// Iterate over the GUID keys to extract the ProductID keys
for (long SubEnumIndex = 0; SubEnumIndex < RegCount; SubEnumIndex ++) {
EnumSubKeyNameLen = 256;
char ProdGUID[256];
#ifdef INSTRUMENTED_DEEP
MessageBox (NULL, "Office IotaAlpha", "Report", MB_OK);
#endif
Status = RegEnumKeyExA(EnumSubKey, SubEnumIndex, ProdGUID, &EnumSubKeyNameLen, NULL, NULL, NULL, NULL);
if (Status == ERROR_NO_MORE_ITEMS) {
break;
}
else if (Status != ERROR_SUCCESS){
continue;
}
AutoRegKey ProdIDKey;
#ifdef INSTRUMENTED_DEEP
MessageBox (NULL, "Office IotaBeta", "Report", MB_OK);
#endif
Status = RegOpenKeyEx(EnumSubKey, ProdGUID, 0, KEY_READ, &ProdIDKey);
if (Status != ERROR_SUCCESS) {
continue;
}
char ProdID[256];
unsigned long ItemSize = 256;
DWORD ItemType = REG_SZ;
#ifdef INSTRUMENTED_DEEP
MessageBox (NULL, "Office IotaDelta", "Report", MB_OK);
#endif
Status = RegQueryValueEx(
ProdIDKey, // handle to key to query
"ProductID", // address of name of value to query
NULL, // reserved
&ItemType, // address of buffer for value type
(unsigned char *) ProdID, // address of data buffer
&ItemSize // address of data buffer size
);
if (Status == ERROR_SUCCESS) {
MSOffice10PlusMap[std::string(ProdGUID)] = std::string(ProdID);
}
ItemSize = 256;
ItemType = REG_BINARY;
Status = RegQueryValueEx(
ProdIDKey, // handle to key to query
"DigitalProductID", // address of name of value to query
NULL, // reserved
&ItemType, // address of buffer for value type
(unsigned char *) ProdID, // address of data buffer
&ItemSize // address of data buffer size
);
if (Status == ERROR_SUCCESS) {
char decodeKey[kDecodeKeyLen + 1];
if (DecodeMSKeyReg(decodeKey, ProdID) == ERROR_SUCCESS) {
MSOffice10PlusMapID[std::string(ProdGUID)] = std::string(decodeKey);
}
}
}
}
}
#ifdef INSTRUMENTED
MessageBox (NULL, "Office EXIT!", "Report", MB_OK);
#endif
return ERROR_SUCCESS;
}
long SoftwareCollector::CollectSingleProgram (HKEY SubKey, char * SubKeyName, NVDataItem * TargetData, bool * KeepItem)
{
const char* DispName = NULL;
TargetData->GetValueByName("DisplayName", & DispName);
if (DispName == NULL) {
*KeepItem = false;
return ERROR_SUCCESS;
}
if (strstr(DispName, "Microsoft Office") != NULL) {
const char * VersionString = NULL;
TargetData->GetValueByName ("DisplayVersion", & VersionString);
if (VersionString == NULL)
return ERROR_SUCCESS;
int ScanCount = 0;
int VersionNum = 0;
ScanCount = sscanf(VersionString,"%d",& VersionNum);
if (ScanCount != 1)
return ERROR_SUCCESS;
if (VersionNum < 10) {
std::map<int, std::string>::iterator VersionItem;
VersionItem = MSOfficePre10Map.find(VersionNum);
if (VersionItem == MSOfficePre10Map.end())
return ERROR_SUCCESS;
TargetData->AddNVItem("SerialNumber", VersionItem->second.c_str());
}
else {
std::map<std::string, std::string>::iterator VersionItem;
VersionItem = MSOffice10PlusMap.find(std::string(SubKeyName));
if (VersionItem != MSOffice10PlusMap.end()) {
TargetData->AddNVItem("SerialNumber", VersionItem->second.c_str());
}
VersionItem = MSOffice10PlusMapID.find(std::string(SubKeyName));
if (VersionItem != MSOffice10PlusMapID.end()) {
TargetData->AddNVItem("ProductKey", VersionItem->second.c_str());
}
}
return ERROR_SUCCESS;
}
const char * MfrName = NULL;
TargetData->GetValueByName ("Publisher", & MfrName);
if (MfrName != NULL && strstr(MfrName, "Adobe") != NULL) {
long Status;
DWORD ItemType = REG_SZ;
char SerialFromKey[256] = {0};
unsigned long ItemSize = 256;
Status = RegQueryValueEx(
SubKey,
"SERIAL",
NULL,
&ItemType,
(unsigned char *) SerialFromKey,
&ItemSize);
if (Status != ERROR_SUCCESS) {
return ERROR_SUCCESS;
}
TargetData->AddNVItem("SerialNumber", SerialFromKey);
}
return ERROR_SUCCESS;
}
long SoftwareCollector::Collect(NVDataItem **ReturnItem)
{
#ifdef INSTRUMENTED
MessageBox (NULL, "Software STARTING!", "Report", MB_OK);
#endif
auto_ptr<NVDataItem> DataItems (new NVDataItem(SWCL_TAG));
long Status;
#ifdef INSTRUMENTED
MessageBox(NULL, "Starting Office Detection", "Report", MB_OK);
#endif
Status = PopulateOfficeMap();
#ifdef INSTRUMENTED
MessageBox(NULL, "Finished Office Starting Main!", "Report", MB_OK);
#endif
Status = RegEnumerateSubKeys(HKEY_LOCAL_MACHINE, SW_INFO_PATH, SWC_TAG, DataItems.get(), ProcessorItems, CollectSingleProgram, NULL);
W32_RETURN_ON_ERROR(Status);
*ReturnItem = DataItems.release();
#ifdef INSTRUMENTED
MessageBox(NULL, "Software Complete!", "Report", MB_OK);
#endif
return ERROR_SUCCESS;
} | 28.301724 | 135 | 0.648797 | syslist |
2034af4a4cb1026e0b9018e9279b9b6ccf462610 | 2,168 | cpp | C++ | Code/Source/Graphics/IBuffer.cpp | christinazavou/Thea | f68293c4a4f5ddc3abda18e2e0b679bcf5163e93 | [
"BSD-3-Clause"
] | null | null | null | Code/Source/Graphics/IBuffer.cpp | christinazavou/Thea | f68293c4a4f5ddc3abda18e2e0b679bcf5163e93 | [
"BSD-3-Clause"
] | null | null | null | Code/Source/Graphics/IBuffer.cpp | christinazavou/Thea | f68293c4a4f5ddc3abda18e2e0b679bcf5163e93 | [
"BSD-3-Clause"
] | null | null | null | //============================================================================
//
// This file is part of the Thea toolkit.
//
// This software is distributed under the BSD license, as detailed in the
// accompanying LICENSE.txt file. Portions are derived from other works:
// their respective licenses and copyright information are reproduced in
// LICENSE.txt and/or in the relevant source files.
//
// Author: Siddhartha Chaudhuri
// First version: 2009
//
//============================================================================
#include "../MatVec.hpp"
#include "../Colors.hpp"
namespace Thea {
// We want to be able to interpret a buffer of (say) Vector3's as a tightly packed list of scalars. This isn't really necessary
// for the interface of IBuffer, but it makes things simpler and more efficient for the end user, so we'll make this a global
// requirement.
static_assert(sizeof(Vector2) == 2 * sizeof(Real), "IBuffer: Vector2 has padding, can't be tightly packed in a buffer");
static_assert(sizeof(Vector3) == 3 * sizeof(Real), "IBuffer: Vector3 has padding, can't be tightly packed in a buffer");
static_assert(sizeof(Vector4) == 4 * sizeof(Real), "IBuffer: Vector4 has padding, can't be tightly packed in a buffer");
static_assert(sizeof(ColorL) == 1 * sizeof(Real), "IBuffer: ColorL has padding, can't be tightly packed in a buffer");
static_assert(sizeof(ColorL8) == 1 * sizeof(uint8), "IBuffer: ColorL8 has padding, can't be tightly packed in a buffer");
static_assert(sizeof(ColorL16) == 1 * sizeof(uint16), "IBuffer: ColorL16 has padding, can't be tightly packed in a buffer");
static_assert(sizeof(ColorRgb) == 3 * sizeof(Real), "IBuffer: ColorRgb has padding, can't be tightly packed in a buffer");
static_assert(sizeof(ColorRgb8) == 3 * sizeof(uint8), "IBuffer: ColorRgb8 has padding, can't be tightly packed in a buffer");
static_assert(sizeof(ColorRgba) == 4 * sizeof(Real), "IBuffer: ColorRgba has padding, can't be tightly packed in a buffer");
static_assert(sizeof(ColorRgba8) == 4 * sizeof(uint8), "IBuffer: ColorRgba8 has padding, can't be tightly packed in a buffer");
} // namespace Thea
| 61.942857 | 128 | 0.673893 | christinazavou |
203532959ca2a192bf9409770eb25396ad402125 | 1,599 | cpp | C++ | window.cpp | lewez/zombie-game | fdfefc312aaac4848a025c150e0862ca37a71fca | [
"MIT"
] | 1 | 2019-04-26T12:57:05.000Z | 2019-04-26T12:57:05.000Z | window.cpp | lewez/zombie-game | fdfefc312aaac4848a025c150e0862ca37a71fca | [
"MIT"
] | null | null | null | window.cpp | lewez/zombie-game | fdfefc312aaac4848a025c150e0862ca37a71fca | [
"MIT"
] | null | null | null | /* MIT License
Copyright (c) 2019 Lewis Clark
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 "window.h"
game::Window::~Window() {
Destroy();
}
game::Window::Window(SDL_Window* sdlwin) :
m_sdlwin(sdlwin) {
}
game::Renderer* game::Window::CreateRenderer(std::uint32_t flags) {
SDL_Renderer* sdlren = SDL_CreateRenderer(m_sdlwin, -1, flags);
if (!sdlren) {
return nullptr;
}
m_renderers.push_back(std::make_unique<Renderer>(sdlren));
return m_renderers.back().get();
}
void game::Window::Destroy() {
for (const auto& ren : m_renderers) {
ren->Destroy();
}
SDL_DestroyWindow(m_sdlwin);
}
| 29.611111 | 78 | 0.762977 | lewez |
2038570c3414f4bccef2da6105fff771dbe0df27 | 3,083 | cpp | C++ | p2p/xxx/peer_storage.cpp | akhavr/beam | 99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62 | [
"Apache-2.0"
] | null | null | null | p2p/xxx/peer_storage.cpp | akhavr/beam | 99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62 | [
"Apache-2.0"
] | null | null | null | p2p/xxx/peer_storage.cpp | akhavr/beam | 99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 The Beam Team
//
// 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 "peer_storage.h"
#include <errno.h>
namespace beam {
using namespace io;
static constexpr size_t ITEM_SIZE = sizeof(PeerInfo);
PeerStorage::~PeerStorage() {
close();
}
Result PeerStorage::open(const std::string& fileName) {
if (_file) close();
_file = fopen(fileName.c_str(), "a+b");
ErrorCode errorCode = EC_OK;
if (!_file) {
#ifndef _WIN32
errorCode = ErrorCode(-errno);
#else
errorCode = EC_EACCES; //TODO GetLastError and map into io::Error or whatever
#endif
}
return make_result(errorCode);
}
static bool seek_end(FILE* f, long& offset) {
if (fseek(f, 0, SEEK_END) != 0) return false;
offset = ftell(f);
return true;
}
static bool seek_to(FILE* f, long offset) {
return fseek(f, offset, SEEK_SET) == 0;
}
Result PeerStorage::load_peers(const LoadCallback& cb) {
ErrorCode ec = EC_EBADF;
if (!_file) {
return make_unexpected(ec);
}
long length=0;
if (!(seek_end(_file, length) && seek_to(_file, 0))) {
return make_unexpected(ec);
}
if (length % ITEM_SIZE != 0) {
return make_unexpected(EC_FILE_CORRUPTED);
}
size_t nPeers = length / ITEM_SIZE;
PeerInfo peer;
for (size_t i=0; i<nPeers; ++i) {
if (ITEM_SIZE != fread(&peer, 1, ITEM_SIZE, _file)) {
return make_unexpected(EC_EOF);
}
_index[peer.sessionId] = ITEM_SIZE * i;
cb(peer);
}
return Ok();
}
Result PeerStorage::forget_old_peers(uint32_t howLong) {
// TODO compact db
return Ok();
}
Result PeerStorage::update_peer(const PeerInfo& peer) {
ErrorCode ec = EC_EBADF;
if (!_file) {
return make_unexpected(ec);
}
auto it = _index.find(peer.sessionId);
long offset=0;
if (it == _index.end()) {
if (!seek_end(_file, offset)) {
return make_unexpected(ec);
}
_index[peer.sessionId] = offset;
} else {
offset = _index[peer.sessionId];
if (!seek_to(_file, offset)) {
return make_unexpected(ec);
}
}
if (ITEM_SIZE != fwrite(&peer, 1, ITEM_SIZE, _file)) {
_index.erase(peer.sessionId);
return make_unexpected(ec);
}
return Ok();
}
void PeerStorage::close() {
if (_file) {
fclose(_file);
_file = 0;
_index.clear();
}
}
} //namespace
| 24.862903 | 86 | 0.600389 | akhavr |
20388f158cc23ef911a497dc1b64adcf0711815a | 8,863 | cxx | C++ | main/configmgr/source/broadcaster.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/configmgr/source/broadcaster.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/configmgr/source/broadcaster.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
#include "precompiled_configmgr.hxx"
#include "sal/config.h"
#include "com/sun/star/beans/XPropertiesChangeListener.hpp"
#include "com/sun/star/beans/XPropertyChangeListener.hpp"
#include "com/sun/star/container/XContainerListener.hpp"
#include "com/sun/star/lang/DisposedException.hpp"
#include "com/sun/star/lang/WrappedTargetRuntimeException.hpp"
#include "com/sun/star/lang/XEventListener.hpp"
#include "com/sun/star/uno/Any.hxx"
#include "com/sun/star/uno/Exception.hpp"
#include "com/sun/star/uno/Reference.hxx"
#include "com/sun/star/uno/XInterface.hpp"
#include "com/sun/star/util/XChangesListener.hpp"
#include "cppuhelper/exc_hlp.hxx"
#include "osl/diagnose.hxx"
#include "rtl/string.h"
#include "rtl/ustrbuf.hxx"
#include "rtl/ustring.h"
#include "rtl/ustring.hxx"
#include "broadcaster.hxx"
namespace configmgr {
namespace {
namespace css = com::sun::star;
void appendMessage(
rtl::OUStringBuffer & buffer, css::uno::Exception const & exception)
{
buffer.appendAscii(RTL_CONSTASCII_STRINGPARAM("; "));
buffer.append(exception.Message);
}
}
void Broadcaster::addDisposeNotification(
css::uno::Reference< css::lang::XEventListener > const & listener,
css::lang::EventObject const & event)
{
disposeNotifications_.push_back(DisposeNotification(listener, event));
}
void Broadcaster::addContainerElementReplacedNotification(
css::uno::Reference< css::container::XContainerListener > const & listener,
css::container::ContainerEvent const & event)
{
containerElementReplacedNotifications_.push_back(
ContainerNotification(listener, event));
}
void Broadcaster::addContainerElementInsertedNotification(
css::uno::Reference< css::container::XContainerListener > const & listener,
css::container::ContainerEvent const & event)
{
containerElementInsertedNotifications_.push_back(
ContainerNotification(listener, event));
}
void Broadcaster::addContainerElementRemovedNotification(
css::uno::Reference< css::container::XContainerListener > const & listener,
css::container::ContainerEvent const & event)
{
containerElementRemovedNotifications_.push_back(
ContainerNotification(listener, event));
}
void Broadcaster::addPropertyChangeNotification(
css::uno::Reference< css::beans::XPropertyChangeListener > const & listener,
css::beans::PropertyChangeEvent const & event)
{
propertyChangeNotifications_.push_back(
PropertyChangeNotification(listener, event));
}
void Broadcaster::addPropertiesChangeNotification(
css::uno::Reference< css::beans::XPropertiesChangeListener > const &
listener,
css::uno::Sequence< css::beans::PropertyChangeEvent > const & event)
{
propertiesChangeNotifications_.push_back(
PropertiesChangeNotification(listener, event));
}
void Broadcaster::addChangesNotification(
css::uno::Reference< css::util::XChangesListener > const & listener,
css::util::ChangesEvent const & event)
{
changesNotifications_.push_back(ChangesNotification(listener, event));
}
void Broadcaster::send() {
css::uno::Any exception;
rtl::OUStringBuffer messages;
for (DisposeNotifications::iterator i(disposeNotifications_.begin());
i != disposeNotifications_.end(); ++i) {
try {
i->listener->disposing(i->event);
} catch (css::lang::DisposedException &) {
} catch (css::uno::Exception & e) {
exception = cppu::getCaughtException();
appendMessage(messages, e);
}
}
for (ContainerNotifications::iterator i(
containerElementInsertedNotifications_.begin());
i != containerElementInsertedNotifications_.end(); ++i)
{
try {
i->listener->elementInserted(i->event);
} catch (css::lang::DisposedException &) {
} catch (css::uno::Exception & e) {
exception = cppu::getCaughtException();
appendMessage(messages, e);
}
}
for (ContainerNotifications::iterator i(
containerElementRemovedNotifications_.begin());
i != containerElementRemovedNotifications_.end(); ++i)
{
try {
i->listener->elementRemoved(i->event);
} catch (css::lang::DisposedException &) {
} catch (css::uno::Exception & e) {
exception = cppu::getCaughtException();
appendMessage(messages, e);
}
}
for (ContainerNotifications::iterator i(
containerElementReplacedNotifications_.begin());
i != containerElementReplacedNotifications_.end(); ++i)
{
try {
i->listener->elementReplaced(i->event);
} catch (css::lang::DisposedException &) {
} catch (css::uno::Exception & e) {
exception = cppu::getCaughtException();
appendMessage(messages, e);
}
}
for (PropertyChangeNotifications::iterator i(
propertyChangeNotifications_.begin());
i != propertyChangeNotifications_.end(); ++i)
{
try {
i->listener->propertyChange(i->event);
} catch (css::lang::DisposedException &) {
} catch (css::uno::Exception & e) {
exception = cppu::getCaughtException();
appendMessage(messages, e);
}
}
for (PropertiesChangeNotifications::iterator i(
propertiesChangeNotifications_.begin());
i != propertiesChangeNotifications_.end(); ++i)
{
try {
i->listener->propertiesChange(i->event);
} catch (css::lang::DisposedException &) {
} catch (css::uno::Exception & e) {
exception = cppu::getCaughtException();
appendMessage(messages, e);
}
}
for (ChangesNotifications::iterator i(changesNotifications_.begin());
i != changesNotifications_.end(); ++i) {
try {
i->listener->changesOccurred(i->event);
} catch (css::lang::DisposedException &) {
} catch (css::uno::Exception & e) {
exception = cppu::getCaughtException();
appendMessage(messages, e);
}
}
if (exception.hasValue()) {
throw css::lang::WrappedTargetRuntimeException(
(rtl::OUString(
RTL_CONSTASCII_USTRINGPARAM(
"configmgr exceptions during listener notification")) +
messages.makeStringAndClear()),
css::uno::Reference< css::uno::XInterface >(),
exception);
}
}
Broadcaster::DisposeNotification::DisposeNotification(
css::uno::Reference< css::lang::XEventListener > const & theListener,
css::lang::EventObject const & theEvent):
listener(theListener), event(theEvent)
{
OSL_ASSERT(theListener.is());
}
Broadcaster::ContainerNotification::ContainerNotification(
css::uno::Reference< css::container::XContainerListener > const &
theListener,
css::container::ContainerEvent const & theEvent):
listener(theListener), event(theEvent)
{
OSL_ASSERT(theListener.is());
}
Broadcaster::PropertyChangeNotification::PropertyChangeNotification(
css::uno::Reference< css::beans::XPropertyChangeListener > const &
theListener,
css::beans::PropertyChangeEvent const & theEvent):
listener(theListener), event(theEvent)
{
OSL_ASSERT(theListener.is());
}
Broadcaster::PropertiesChangeNotification::PropertiesChangeNotification(
css::uno::Reference< css::beans::XPropertiesChangeListener > const &
theListener,
css::uno::Sequence< css::beans::PropertyChangeEvent > const & theEvent):
listener(theListener), event(theEvent)
{
OSL_ASSERT(theListener.is());
}
Broadcaster::ChangesNotification::ChangesNotification(
css::uno::Reference< css::util::XChangesListener > const & theListener,
css::util::ChangesEvent const & theEvent):
listener(theListener), event(theEvent)
{
OSL_ASSERT(theListener.is());
}
}
| 34.756863 | 80 | 0.66851 | Grosskopf |
203a1e29d6c664f030bff9cd2c44a3894a036e38 | 193 | hpp | C++ | libs/numeric/mtl/examples/gdbinit_example.hpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 24 | 2019-03-26T15:25:45.000Z | 2022-03-26T10:00:45.000Z | libs/numeric/mtl/examples/gdbinit_example.hpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 2 | 2020-04-17T12:35:32.000Z | 2021-03-03T15:46:25.000Z | libs/numeric/mtl/examples/gdbinit_example.hpp | lit-uriy/mtl4-mirror | 37cf7c2847165d3537cbc3400cb5fde6f80e3d8b | [
"MTLL"
] | 10 | 2019-12-01T13:40:30.000Z | 2022-01-14T08:39:54.000Z | python
import sys
# STL support and alike here
sys.path.insert(0, '/home/username/tools/gdb_printers/python')
from mtl.printers import register_mtl_printers
register_mtl_printers (None)
end
| 17.545455 | 62 | 0.80829 | lit-uriy |
20434f68d04e0b4c5475ed4d5fa19016a7e936ce | 16,608 | cc | C++ | cc/layer_tree_host_unittest_occlusion.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-03-10T13:08:49.000Z | 2018-03-10T13:08:49.000Z | cc/layer_tree_host_unittest_occlusion.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | cc/layer_tree_host_unittest_occlusion.cc | GnorTech/chromium | e1c7731d5bd099ca5544fcf8eda3867d4ce5bab5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:19:31.000Z | 2020-11-04T07:19:31.000Z | // Copyright 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.
#include "cc/layer_tree_host.h"
#include "cc/layer.h"
#include "cc/test/layer_tree_test_common.h"
#include "cc/test/occlusion_tracker_test_common.h"
namespace cc {
namespace {
class TestLayer : public Layer {
public:
static scoped_refptr<TestLayer> Create() {
return make_scoped_refptr(new TestLayer());
}
virtual void update(
ResourceUpdateQueue& update_queue,
const OcclusionTracker* occlusion,
RenderingStats* stats) OVERRIDE {
if (!occlusion)
return;
// Gain access to internals of the OcclusionTracker.
const TestOcclusionTracker* test_occlusion =
static_cast<const TestOcclusionTracker*>(occlusion);
occlusion_ = UnionRegions(
test_occlusion->occlusionFromInsideTarget(),
test_occlusion->occlusionFromOutsideTarget());
}
const Region& occlusion() const { return occlusion_; }
const Region& expected_occlusion() const { return expected_occlusion_; }
void set_expected_occlusion(const Region& occlusion) {
expected_occlusion_ = occlusion;
}
private:
TestLayer() : Layer() {
setIsDrawable(true);
}
virtual ~TestLayer() { }
Region occlusion_;
Region expected_occlusion_;
};
class LayerTreeHostOcclusionTest : public ThreadedTest {
public:
LayerTreeHostOcclusionTest()
: root_(TestLayer::Create()),
child_(TestLayer::Create()),
child2_(TestLayer::Create()),
grand_child_(TestLayer::Create()),
mask_(TestLayer::Create()) {
}
virtual void beginTest() OVERRIDE {
postSetNeedsCommitToMainThread();
}
virtual void didCommit() OVERRIDE {
TestLayer* root = static_cast<TestLayer*>(m_layerTreeHost->rootLayer());
VerifyOcclusion(root);
endTest();
}
virtual void afterTest() OVERRIDE {}
void VerifyOcclusion(TestLayer* layer) const {
EXPECT_EQ(layer->expected_occlusion().ToString(),
layer->occlusion().ToString());
for (size_t i = 0; i < layer->children().size(); ++i) {
TestLayer* child = static_cast<TestLayer*>(layer->children()[i].get());
VerifyOcclusion(child);
}
}
void SetLayerPropertiesForTesting(
TestLayer* layer, TestLayer* parent, const gfx::Transform& transform,
const gfx::PointF& position, const gfx::Size& bounds, bool opaque) const {
layer->removeAllChildren();
if (parent)
parent->addChild(layer);
layer->setTransform(transform);
layer->setPosition(position);
layer->setBounds(bounds);
layer->setContentsOpaque(opaque);
layer->setAnchorPoint(gfx::PointF());
}
protected:
scoped_refptr<TestLayer> root_;
scoped_refptr<TestLayer> child_;
scoped_refptr<TestLayer> child2_;
scoped_refptr<TestLayer> grand_child_;
scoped_refptr<TestLayer> mask_;
gfx::Transform identity_matrix_;
};
class LayerTreeHostOcclusionTestOcclusionSurfaceClipping :
public LayerTreeHostOcclusionTest {
public:
virtual void setupTree() OVERRIDE {
// The child layer is a surface and the grandChild is opaque, but clipped to
// the child and root
SetLayerPropertiesForTesting(
root_.get(), NULL, identity_matrix_,
gfx::PointF(0.f, 0.f), gfx::Size(200, 200), true);
SetLayerPropertiesForTesting(
child_.get(), root_.get(), identity_matrix_,
gfx::PointF(10.f, 10.f), gfx::Size(500, 500), false);
SetLayerPropertiesForTesting(
grand_child_.get(), child_.get(), identity_matrix_,
gfx::PointF(-10.f, -10.f), gfx::Size(20, 500), true);
child_->setMasksToBounds(true);
child_->setForceRenderSurface(true);
child_->set_expected_occlusion(gfx::Rect(0, 0, 10, 190));
root_->set_expected_occlusion(gfx::Rect(10, 10, 10, 190));
m_layerTreeHost->setRootLayer(root_);
ThreadedTest::setupTree();
}
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostOcclusionTestOcclusionSurfaceClipping)
class LayerTreeHostOcclusionTestOcclusionSurfaceClippingOpaque :
public LayerTreeHostOcclusionTest {
public:
virtual void setupTree() OVERRIDE {
// If the child layer is opaque, then it adds to the occlusion seen by the
// root_.
SetLayerPropertiesForTesting(
root_.get(), NULL, identity_matrix_,
gfx::PointF(0.f, 0.f), gfx::Size(200, 200), true);
SetLayerPropertiesForTesting(
child_.get(), root_.get(), identity_matrix_,
gfx::PointF(10.f, 10.f), gfx::Size(500, 500), true);
SetLayerPropertiesForTesting(
grand_child_.get(), child_.get(), identity_matrix_,
gfx::PointF(-10.f, -10.f), gfx::Size(20, 500), true);
child_->setMasksToBounds(true);
child_->setForceRenderSurface(true);
child_->set_expected_occlusion(gfx::Rect(0, 0, 10, 190));
root_->set_expected_occlusion(gfx::Rect(10, 10, 190, 190));
m_layerTreeHost->setRootLayer(root_);
ThreadedTest::setupTree();
}
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostOcclusionTestOcclusionSurfaceClippingOpaque);
class LayerTreeHostOcclusionTestOcclusionTwoChildren :
public LayerTreeHostOcclusionTest {
public:
virtual void setupTree() OVERRIDE {
// Add a second child to the root layer and the regions should merge
SetLayerPropertiesForTesting(
root_.get(), NULL, identity_matrix_,
gfx::PointF(0.f, 0.f), gfx::Size(200, 200), true);
SetLayerPropertiesForTesting(
child_.get(), root_.get(), identity_matrix_,
gfx::PointF(10.f, 10.f), gfx::Size(500, 500), false);
SetLayerPropertiesForTesting(
grand_child_.get(), child_.get(), identity_matrix_,
gfx::PointF(-10.f, -10.f), gfx::Size(20, 500), true);
SetLayerPropertiesForTesting(
child2_.get(), root_.get(), identity_matrix_,
gfx::PointF(20.f, 10.f), gfx::Size(10, 500), true);
child_->setMasksToBounds(true);
child_->setForceRenderSurface(true);
grand_child_->set_expected_occlusion(gfx::Rect(10, 0, 10, 190));
child_->set_expected_occlusion(gfx::Rect(0, 0, 20, 190));
root_->set_expected_occlusion(gfx::Rect(10, 10, 20, 190));
m_layerTreeHost->setRootLayer(root_);
ThreadedTest::setupTree();
}
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostOcclusionTestOcclusionTwoChildren)
class LayerTreeHostOcclusionTestOcclusionMask :
public LayerTreeHostOcclusionTest {
public:
virtual void setupTree() OVERRIDE {
// If the child layer has a mask on it, then it shouldn't contribute to
// occlusion on stuff below it.
SetLayerPropertiesForTesting(
root_.get(), NULL, identity_matrix_,
gfx::PointF(0.f, 0.f), gfx::Size(200, 200), true);
SetLayerPropertiesForTesting(
child2_.get(), root_.get(), identity_matrix_,
gfx::PointF(10.f, 10.f), gfx::Size(500, 500), true);
SetLayerPropertiesForTesting(
child_.get(), root_.get(), identity_matrix_,
gfx::PointF(20.f, 20.f), gfx::Size(500, 500), true);
SetLayerPropertiesForTesting(
grand_child_.get(), child_.get(), identity_matrix_,
gfx::PointF(-10.f, -10.f), gfx::Size(500, 500), true);
child_->setMasksToBounds(true);
child_->setForceRenderSurface(true);
child_->setMaskLayer(mask_.get());
child_->set_expected_occlusion(gfx::Rect(0, 0, 180, 180));
root_->set_expected_occlusion(gfx::Rect(10, 10, 190, 190));
m_layerTreeHost->setRootLayer(root_);
ThreadedTest::setupTree();
}
};
SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostOcclusionTestOcclusionMask)
class LayerTreeHostOcclusionTestOcclusionMaskBelowOcclusion :
public LayerTreeHostOcclusionTest {
public:
virtual void setupTree() OVERRIDE {
// If the child layer with a mask is below child2, then child2 should
// contribute to occlusion on everything, and child shouldn't contribute
// to the root_.
SetLayerPropertiesForTesting(
root_.get(), NULL, identity_matrix_,
gfx::PointF(0.f, 0.f), gfx::Size(200, 200), true);
SetLayerPropertiesForTesting(
child_.get(), root_.get(), identity_matrix_,
gfx::PointF(10.f, 10.f), gfx::Size(500, 500), true);
SetLayerPropertiesForTesting(
grand_child_.get(), child_.get(), identity_matrix_,
gfx::PointF(-10.f, -10.f), gfx::Size(20, 500), true);
SetLayerPropertiesForTesting(
child2_.get(), root_.get(), identity_matrix_,
gfx::PointF(20.f, 10.f), gfx::Size(10, 500), true);
child_->setMasksToBounds(true);
child_->setForceRenderSurface(true);
child_->setMaskLayer(mask_.get());
grand_child_->set_expected_occlusion(gfx::Rect(10, 0, 10, 190));
child_->set_expected_occlusion(gfx::Rect(0, 0, 20, 190));
root_->set_expected_occlusion(gfx::Rect(20, 10, 10, 190));
m_layerTreeHost->setRootLayer(root_);
ThreadedTest::setupTree();
}
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostOcclusionTestOcclusionMaskBelowOcclusion)
class LayerTreeHostOcclusionTestOcclusionOpacity :
public LayerTreeHostOcclusionTest {
public:
virtual void setupTree() OVERRIDE {
// If the child layer has a non-opaque opacity, then it shouldn't
// contribute to occlusion on stuff below it
SetLayerPropertiesForTesting(
root_.get(), NULL, identity_matrix_,
gfx::PointF(0.f, 0.f), gfx::Size(200, 200), true);
SetLayerPropertiesForTesting(
child2_.get(), root_.get(), identity_matrix_,
gfx::PointF(20.f, 10.f), gfx::Size(10, 500), true);
SetLayerPropertiesForTesting(
child_.get(), root_.get(), identity_matrix_,
gfx::PointF(10.f, 10.f), gfx::Size(500, 500), true);
SetLayerPropertiesForTesting(
grand_child_.get(), child_.get(), identity_matrix_,
gfx::PointF(-10.f, -10.f), gfx::Size(20, 500), true);
child_->setMasksToBounds(true);
child_->setForceRenderSurface(true);
child_->setOpacity(0.5f);
child_->set_expected_occlusion(gfx::Rect(0, 0, 10, 190));
root_->set_expected_occlusion(gfx::Rect(20, 10, 10, 190));
m_layerTreeHost->setRootLayer(root_);
ThreadedTest::setupTree();
}
};
SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostOcclusionTestOcclusionOpacity)
class LayerTreeHostOcclusionTestOcclusionOpacityBelowOcclusion :
public LayerTreeHostOcclusionTest {
public:
virtual void setupTree() OVERRIDE {
// If the child layer with non-opaque opacity is below child2, then
// child2 should contribute to occlusion on everything, and child shouldn't
// contribute to the root_.
SetLayerPropertiesForTesting(
root_.get(), NULL, identity_matrix_,
gfx::PointF(0.f, 0.f), gfx::Size(200, 200), true);
SetLayerPropertiesForTesting(
child_.get(), root_.get(), identity_matrix_,
gfx::PointF(10.f, 10.f), gfx::Size(500, 500), true);
SetLayerPropertiesForTesting(
grand_child_.get(), child_.get(), identity_matrix_,
gfx::PointF(-10.f, -10.f), gfx::Size(20, 500), true);
SetLayerPropertiesForTesting(
child2_.get(), root_.get(), identity_matrix_,
gfx::PointF(20.f, 10.f), gfx::Size(10, 500), true);
child_->setMasksToBounds(true);
child_->setForceRenderSurface(true);
child_->setOpacity(0.5f);
grand_child_->set_expected_occlusion(gfx::Rect(10, 0, 10, 190));
child_->set_expected_occlusion(gfx::Rect(0, 0, 20, 190));
root_->set_expected_occlusion(gfx::Rect(20, 10, 10, 190));
m_layerTreeHost->setRootLayer(root_);
ThreadedTest::setupTree();
}
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostOcclusionTestOcclusionOpacityBelowOcclusion)
class LayerTreeHostOcclusionTestOcclusionOpacityFilter :
public LayerTreeHostOcclusionTest {
public:
virtual void setupTree() OVERRIDE {
gfx::Transform childTransform;
childTransform.Translate(250.0, 250.0);
childTransform.Rotate(90.0);
childTransform.Translate(-250.0, -250.0);
WebKit::WebFilterOperations filters;
filters.append(WebKit::WebFilterOperation::createOpacityFilter(0.5));
// If the child layer has a filter that changes alpha values, and is below
// child2, then child2 should contribute to occlusion on everything,
// and child shouldn't contribute to the root
SetLayerPropertiesForTesting(
root_.get(), NULL, identity_matrix_,
gfx::PointF(0.f, 0.f), gfx::Size(200, 200), true);
SetLayerPropertiesForTesting(
child_.get(), root_.get(), childTransform,
gfx::PointF(30.f, 30.f), gfx::Size(500, 500), true);
SetLayerPropertiesForTesting(
grand_child_.get(), child_.get(), identity_matrix_,
gfx::PointF(10.f, 10.f), gfx::Size(500, 500), true);
SetLayerPropertiesForTesting(
child2_.get(), root_.get(), identity_matrix_,
gfx::PointF(10.f, 70.f), gfx::Size(500, 500), true);
child_->setMasksToBounds(true);
child_->setFilters(filters);
grand_child_->set_expected_occlusion(gfx::Rect(40, 330, 130, 190));
child_->set_expected_occlusion(UnionRegions(
gfx::Rect(10, 330, 160, 170), gfx::Rect(40, 500, 130, 20)));
root_->set_expected_occlusion(gfx::Rect(10, 70, 190, 130));
m_layerTreeHost->setRootLayer(root_);
ThreadedTest::setupTree();
}
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostOcclusionTestOcclusionOpacityFilter)
class LayerTreeHostOcclusionTestOcclusionBlurFilter :
public LayerTreeHostOcclusionTest {
public:
virtual void setupTree() OVERRIDE {
gfx::Transform childTransform;
childTransform.Translate(250.0, 250.0);
childTransform.Rotate(90.0);
childTransform.Translate(-250.0, -250.0);
WebKit::WebFilterOperations filters;
filters.append(WebKit::WebFilterOperation::createBlurFilter(10));
// If the child layer has a filter that moves pixels/changes alpha, and is
// below child2, then child should not inherit occlusion from outside its
// subtree, and should not contribute to the root
SetLayerPropertiesForTesting(
root_.get(), NULL, identity_matrix_,
gfx::PointF(0.f, 0.f), gfx::Size(200, 200), true);
SetLayerPropertiesForTesting(
child_.get(), root_.get(), childTransform,
gfx::PointF(30.f, 30.f), gfx::Size(500, 500), true);
SetLayerPropertiesForTesting(
grand_child_.get(), child_.get(), identity_matrix_,
gfx::PointF(10.f, 10.f), gfx::Size(500, 500), true);
SetLayerPropertiesForTesting(
child2_.get(), root_.get(), identity_matrix_,
gfx::PointF(10.f, 70.f), gfx::Size(500, 500), true);
child_->setMasksToBounds(true);
child_->setFilters(filters);
child_->set_expected_occlusion(gfx::Rect(10, 330, 160, 170));
root_->set_expected_occlusion(gfx::Rect(10, 70, 190, 130));
m_layerTreeHost->setRootLayer(root_);
ThreadedTest::setupTree();
}
};
SINGLE_AND_MULTI_THREAD_TEST_F(
LayerTreeHostOcclusionTestOcclusionBlurFilter)
class LayerTreeHostOcclusionTestManySurfaces :
public LayerTreeHostOcclusionTest {
public:
virtual void setupTree() OVERRIDE {
// We create enough RenderSurfaces that it will trigger Vector reallocation
// while computing occlusion.
std::vector<scoped_refptr<TestLayer> > layers;
int num_surfaces = 200;
int root_width = 400;
int root_height = 400;
for (int i = 0; i < num_surfaces; ++i) {
layers.push_back(TestLayer::Create());
if (!i) {
SetLayerPropertiesForTesting(
layers.back().get(), NULL, identity_matrix_,
gfx::PointF(0.f, 0.f),
gfx::Size(root_width, root_height), true);
layers.back()->createRenderSurface();
} else {
SetLayerPropertiesForTesting(
layers.back().get(), layers[layers.size() - 2].get(),
identity_matrix_,
gfx::PointF(1.f, 1.f),
gfx::Size(root_width-i, root_height-i), true);
layers.back()->setForceRenderSurface(true);
}
}
for (int i = 1; i < num_surfaces; ++i) {
scoped_refptr<TestLayer> child = TestLayer::Create();
SetLayerPropertiesForTesting(
child.get(), layers[i].get(), identity_matrix_,
gfx::PointF(0.f, 0.f), gfx::Size(root_width, root_height), false);
}
for (int i = 0; i < num_surfaces-1; ++i) {
gfx::Rect expected_occlusion(1, 1, root_width-i-1, root_height-i-1);
layers[i]->set_expected_occlusion(expected_occlusion);
}
m_layerTreeHost->setRootLayer(layers[0].get());
ThreadedTest::setupTree();
}
};
SINGLE_AND_MULTI_THREAD_TEST_F(LayerTreeHostOcclusionTestManySurfaces)
} // namespace
} // namespace cc
| 34.81761 | 80 | 0.689788 | GnorTech |
2044e9c642160319e9658cb48ad579f1efad6561 | 6,323 | cpp | C++ | Frameworks/Helmet/Core/src/Plugin/Environment.cpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | 2 | 2018-02-07T01:19:37.000Z | 2018-02-09T14:27:48.000Z | Frameworks/Helmet/Core/src/Plugin/Environment.cpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | null | null | null | Frameworks/Helmet/Core/src/Plugin/Environment.cpp | hatboysoftware/helmet | 97f26d134742fdb732abc6177bb2adaeb67b3187 | [
"Zlib"
] | null | null | null | //-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
// Helmet Software Framework
//
// Copyright (C) 2018 Hat Boy Software, Inc.
//
// @author Matthew Alan Gray - <mgray@hatboysoftware.com>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
#include "Environment.hpp"
#include <boost/log/trivial.hpp>
#include <boost/property_tree/json_parser.hpp>
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
namespace Helmet {
namespace Core {
namespace Plugin {
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
Environment::Environment()
: m_configuration()
, m_sessionInfo()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
Environment::~Environment()
{
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
Environment::loadConfiguration(const boost::filesystem::path& _path)
{
if (boost::filesystem::exists(_path))
{
std::ifstream fileStream;
fileStream.open(_path.string(), std::ios_base::in | std::ios_base::binary);
if (loadConfiguration(fileStream))
{
BOOST_LOG_TRIVIAL(info) << "Loaded configuration from " << _path;
return true;
}
}
BOOST_LOG_TRIVIAL(error) << "Configuration file " << _path << " does not exist.";
return false;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
Environment::loadConfiguration(std::istream& _input)
{
try
{
std::stringstream json;
json << _input.rdbuf();
read_json(json, m_configuration);
return true;
}
catch (std::exception& _ex)
{
BOOST_LOG_TRIVIAL(error) << "Environment::loadConfiguration() : " << _ex.what();
}
return false;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
Environment::saveConfiguration(const boost::filesystem::path& _path)
{
std::ofstream fileStream;
fileStream.open(_path.string(), std::ios_base::out | std::ios_base::trunc);
if (saveConfiguration(fileStream))
{
BOOST_LOG_TRIVIAL(info) << "Saved configuration to " << _path;
return true;
}
BOOST_LOG_TRIVIAL(error) << "Error saving configuration to " << _path;
return false;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
Environment::saveConfiguration(std::ostream& _output)
{
try
{
write_json(_output, m_configuration);
return true;
}
catch (std::exception& _ex)
{
BOOST_LOG_TRIVIAL(error) << "Environment::saveConfiguration() : " << _ex.what();
}
return false;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
Environment::writeConfigurationField(const std::string& _key, const std::string& _value)
{
m_configuration.put(_key, _value);
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
Environment::loadSessionInfo(const boost::filesystem::path& _path)
{
if (boost::filesystem::exists(_path))
{
std::ifstream fileStream;
fileStream.open(_path.string(), std::ios_base::in | std::ios_base::binary);
if (loadSessionInfo(fileStream))
{
BOOST_LOG_TRIVIAL(info) << "Loaded session info from " << _path;
return true;
}
}
BOOST_LOG_TRIVIAL(error) << "Session info file " << _path << " does not exist.";
return false;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
Environment::loadSessionInfo(std::istream& _input)
{
try
{
std::stringstream json;
json << _input.rdbuf();
read_json(json, m_sessionInfo);
return true;
}
catch (std::exception& _ex)
{
BOOST_LOG_TRIVIAL(error) << "Environment::loadSessionInfo() : " << _ex.what();
}
return false;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
Environment::saveSessionInfo(const boost::filesystem::path& _path)
{
std::ofstream fileStream;
fileStream.open(_path.string(), std::ios_base::out | std::ios_base::trunc);
if (saveSessionInfo(fileStream))
{
BOOST_LOG_TRIVIAL(info) << "Saved session info to " << _path;
return true;
}
BOOST_LOG_TRIVIAL(error) << "Error saving session info to " << _path;
return false;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
bool
Environment::saveSessionInfo(std::ostream& _output)
{
try
{
write_json(_output, m_sessionInfo);
return true;
}
catch (std::exception& _ex)
{
BOOST_LOG_TRIVIAL(error) << "Environment::saveSessionInfo() : " << _ex.what();
}
return false;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
void
Environment::writeSessionInfoField(const std::string& _key, const std::string& _value)
{
m_sessionInfo.put(_key, _value);
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
template<class Ptree>
inline Ptree &empty_ptree()
{
static Ptree pt;
return pt;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
boost::property_tree::ptree&
Environment::operator[](const std::string& _key)
{
if (m_configuration.get_child_optional(_key).is_initialized())
{
return m_configuration.get_child(_key);
}
else
if (m_sessionInfo.get_child_optional(_key).is_initialized())
{
return m_sessionInfo.get_child(_key);
}
return empty_ptree<boost::property_tree::ptree>();
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
boost::property_tree::ptree&
Environment::getConfiguration()
{
return m_configuration;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
boost::property_tree::ptree&
Environment::getSession()
{
return m_sessionInfo;
}
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
} // namespace Plugin
} // namespace Core
} // namespace Helmet
//-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
| 27.732456 | 88 | 0.47177 | hatboysoftware |
20454b4a1188ce6f0f195b84a5ec271f929c65d9 | 366 | hpp | C++ | src/Ast/LessThanCondition.hpp | JCube001/pl0 | a6ce723ffc7f639ab64d1a06946990fb6ec295d5 | [
"MIT"
] | null | null | null | src/Ast/LessThanCondition.hpp | JCube001/pl0 | a6ce723ffc7f639ab64d1a06946990fb6ec295d5 | [
"MIT"
] | null | null | null | src/Ast/LessThanCondition.hpp | JCube001/pl0 | a6ce723ffc7f639ab64d1a06946990fb6ec295d5 | [
"MIT"
] | null | null | null | #ifndef PL0_AST_LESS_THAN_CONDITION_HPP
#define PL0_AST_LESS_THAN_CONDITION_HPP
#include "Ast/BinaryCondition.hpp"
namespace PL0 {
namespace Ast {
struct LessThanCondition final : public BinaryCondition
{
void accept(Visitor& visitor) override
{ visitor.visit(*this); }
};
} // namespace Ast
} // namespace PL0
#endif // PL0_AST_LESS_THAN_CONDITION_HPP
| 19.263158 | 55 | 0.773224 | JCube001 |
204a893f0e0c67829072d10a9fbc2d3baa2e1675 | 3,588 | hpp | C++ | include/chopper/build/read_data_file_and_set_high_level_bins.hpp | Felix-Droop/Chopper | 5cc214103b2d088ae400bec0fde8973e03dd3095 | [
"BSD-3-Clause"
] | null | null | null | include/chopper/build/read_data_file_and_set_high_level_bins.hpp | Felix-Droop/Chopper | 5cc214103b2d088ae400bec0fde8973e03dd3095 | [
"BSD-3-Clause"
] | null | null | null | include/chopper/build/read_data_file_and_set_high_level_bins.hpp | Felix-Droop/Chopper | 5cc214103b2d088ae400bec0fde8973e03dd3095 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <cstdlib>
#include <set>
#include <string>
#include <vector>
#include <seqan3/std/charconv>
#include <chopper/build/build_config.hpp>
#include <chopper/build/build_data.hpp>
#include <chopper/detail_bin_prefixes.hpp>
#include <chopper/detail_parse_chopper_pack_line.hpp>
#include <chopper/detail_starts_with.hpp>
auto read_data_file_and_set_high_level_bins(build_config const & config)
{
build_data header;
std::vector<chopper_pack_record> records{};
std::unordered_map<std::string, chopper_pack_record> low_level_records{};
std::ifstream binning_file{config.binning_filename};
if (!binning_file.good() || !binning_file.is_open())
throw std::logic_error{"Could not open file " + config.binning_filename + " for reading"};
std::string current_line;
while (std::getline(binning_file, current_line) && current_line[0] == '#')
{
if (current_line.substr(1, hibf_prefix.size()) == hibf_prefix)
{
assert(current_line.substr(hibf_prefix.size() + 2, 11) == "max_bin_id:");
header.hibf_max_bin_id = current_line.substr(hibf_prefix.size() + 13,
current_line.size() - hibf_prefix.size() - 13);
}
else if (current_line.substr(1, merged_bin_prefix.size()) == merged_bin_prefix)
{
std::string const name(current_line.begin() + 1,
std::find(current_line.begin() + merged_bin_prefix.size() + 2,
current_line.end(),
' '));
assert(current_line.substr(name.size() + 2, 11) == "max_bin_id:");
std::string const bin_idx_str = current_line.substr(name.size() + 13, current_line.size() - name.size() - 13);
size_t const bin_idx = std::atoi(bin_idx_str.c_str());
header.merged_bin_map[name] = bin_idx;
}
}
size_t record_idx{};
do
{
auto && record = parse_chopper_pack_line(current_line);
if (starts_with(record.bin_name, merged_bin_prefix))
{
// cache low level records in map first to accumulate them
std::string const prefix(record.bin_name.begin(),
std::find(record.bin_name.begin() + merged_bin_prefix.size() + 1,
record.bin_name.end(),
'_'));
auto & merged_bin_record = low_level_records[prefix];
merged_bin_record.filenames.insert(merged_bin_record.filenames.end(),
record.filenames.begin(),
record.filenames.end());
merged_bin_record.bins += record.bins;
}
else
{
// add split record
records.push_back(record);
if (record.bin_name == header.hibf_max_bin_id)
record_idx = records.size() - 1;
}
} while (std::getline(binning_file, current_line));
for (auto & [bin_name, rec] : low_level_records)
{
rec.bin_name = bin_name;
records.push_back(rec);
if (rec.bin_name.substr(0, header.hibf_max_bin_id.size()) == header.hibf_max_bin_id)
record_idx = records.size() - 1;
}
header.hibf_max_record = &records[record_idx]; // only take a pointer now s.t. it is not invalidated by push_backs
return std::make_pair(std::move(header), std::move(records));
};
| 39 | 122 | 0.578595 | Felix-Droop |
204cb8a0ba405dd7cac79a70cacfa2fd5a22993a | 1,329 | hpp | C++ | include/literator/internal/filter_iterator_base.hpp | jason2506/literator | 452e5d1416bed80093d989c49cb27c3b665c4bba | [
"BSL-1.0"
] | null | null | null | include/literator/internal/filter_iterator_base.hpp | jason2506/literator | 452e5d1416bed80093d989c49cb27c3b665c4bba | [
"BSL-1.0"
] | null | null | null | include/literator/internal/filter_iterator_base.hpp | jason2506/literator | 452e5d1416bed80093d989c49cb27c3b665c4bba | [
"BSL-1.0"
] | null | null | null | // (c) Copyright David Abrahams 2002.
// (c) Copyright Jeremy Siek 2002.
// (c) Copyright Thomas Witt 2002.
// (c) Copyright Chi-En Wu 2016.
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef LITERATOR_INTERNAL_FILTER_ITERATOR_BASE_HPP_
#define LITERATOR_INTERNAL_FILTER_ITERATOR_BASE_HPP_
#include <iterator>
#include <type_traits>
#include "../iterator_adaptor.hpp"
namespace literator {
// forward declaration
template <typename Predicate, typename Iterator>
class filter_iterator;
namespace internal {
/************************************************
* Declaration: class filter_iterator_base<P, I>
************************************************/
template <typename Predicate, typename Iterator>
using filter_iterator_base = iterator_adaptor<
filter_iterator<Predicate, Iterator>,
Iterator,
use_default,
typename std::conditional<
std::is_convertible<
typename std::iterator_traits<Iterator>::iterator_category,
std::random_access_iterator_tag
>::value,
std::bidirectional_iterator_tag,
use_default
>::type
>;
} // namespace internal
} // namespace literator
#endif // LITERATOR_INTERNAL_FILTER_ITERATOR_BASE_HPP_
| 26.58 | 71 | 0.684725 | jason2506 |
204e41cd089df96cb3a85ace70de165b3d007716 | 447 | cpp | C++ | msvcTemplate/vc2010/VC2010DuiLibWizard/Templates/2052/MainFrame.cpp | wenyongfan/DuiLib_DuiEditor | 087b0de316b7816a366a278e2439aef7cbc5ed26 | [
"BSD-2-Clause"
] | 72 | 2020-02-25T03:59:19.000Z | 2022-03-27T23:20:46.000Z | msvcTemplate/vc2010/VC2010DuiLibWizard/Templates/2052/MainFrame.cpp | wenyongfan/DuiLib_DuiEditor | 087b0de316b7816a366a278e2439aef7cbc5ed26 | [
"BSD-2-Clause"
] | 3 | 2021-03-17T14:42:54.000Z | 2022-02-13T09:03:37.000Z | msvcTemplate/vc2010/VC2010DuiLibWizard/Templates/2052/MainFrame.cpp | wenyongfan/DuiLib_DuiEditor | 087b0de316b7816a366a278e2439aef7cbc5ed26 | [
"BSD-2-Clause"
] | 31 | 2020-03-15T01:57:50.000Z | 2022-03-19T11:10:29.000Z | #include "StdAfx.h"
#include "MainFrame.h"
CMainFrame::CMainFrame(void)
{
}
CMainFrame::~CMainFrame(void)
{
}
void CMainFrame::InitWindow()
{
}
bool CMainFrame::OnCustomMessage(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
return false;
}
bool CMainFrame::OnMenuCommand(const MenuCmd *cmd)
{
return false;
}
bool CMainFrame::OnMenuUpdateCommandUI(CMenuCmdUI *cmdUI)
{
return false;
}
void CMainFrame::OnNotifyClick(TNotifyUI& msg)
{
} | 11.763158 | 73 | 0.733781 | wenyongfan |
204eb679e842f9be8e90207999d270514f8bc630 | 259 | hpp | C++ | src/vm/include/nk/vm/interp.hpp | nickl-lang/nickl | bc68fb85b81eea770907ad1dbe8f680178fa9937 | [
"BSD-3-Clause"
] | 1 | 2022-02-09T10:56:50.000Z | 2022-02-09T10:56:50.000Z | src/vm/include/nk/vm/interp.hpp | nickl-lang/nickl | bc68fb85b81eea770907ad1dbe8f680178fa9937 | [
"BSD-3-Clause"
] | null | null | null | src/vm/include/nk/vm/interp.hpp | nickl-lang/nickl | bc68fb85b81eea770907ad1dbe8f680178fa9937 | [
"BSD-3-Clause"
] | null | null | null | #ifndef HEADER_GUARD_NK_VM_INTERP
#define HEADER_GUARD_NK_VM_INTERP
#include "nk/vm/bc.hpp"
namespace nk {
namespace vm {
void interp_invoke(type_t self, value_t ret, value_t args);
} // namespace vm
} // namespace nk
#endif // HEADER_GUARD_NK_VM_INTERP
| 17.266667 | 59 | 0.772201 | nickl-lang |
204faf8cc4fd0bf00282909c9527af49a36dae68 | 577 | cpp | C++ | creating of nodes.cpp | Pratikrocks/linked--lists | 7832fed689ba25008b6136da2c7ea17b759fb6e7 | [
"MIT"
] | null | null | null | creating of nodes.cpp | Pratikrocks/linked--lists | 7832fed689ba25008b6136da2c7ea17b759fb6e7 | [
"MIT"
] | null | null | null | creating of nodes.cpp | Pratikrocks/linked--lists | 7832fed689ba25008b6136da2c7ea17b759fb6e7 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
void print(struct node*n)
{
while(n!=NULL)
{
cout<<n->data<<" ";
n=n->next;
}
}
int main()
{
struct node*head=NULL;
struct node*first=NULL;
struct node*second=NULL;
head=(struct node*)malloc(sizeof(struct node));
first=(struct node*)malloc(sizeof(struct node));
second=(struct node*)malloc(sizeof(struct node));
head->data=1;
head->next=first;
first->data=2;
first->next=second;
second->data=3;
second->next=NULL;
print(head);
}
| 16.485714 | 51 | 0.632582 | Pratikrocks |
20535677b711087ee4427ac9aa0624cc0e911a94 | 223 | cpp | C++ | allofw-openvr.node/src/allofw_openvr.cpp | donghaoren/AllofwModule | 4367327cda0605aad53469294ed8751f8befbdc3 | [
"Unlicense"
] | 3 | 2016-05-04T23:23:48.000Z | 2021-08-03T21:48:07.000Z | allofw-openvr.node/src/allofw_openvr.cpp | donghaoren/AllofwModule | 4367327cda0605aad53469294ed8751f8befbdc3 | [
"Unlicense"
] | null | null | null | allofw-openvr.node/src/allofw_openvr.cpp | donghaoren/AllofwModule | 4367327cda0605aad53469294ed8751f8befbdc3 | [
"Unlicense"
] | 2 | 2016-01-31T04:06:51.000Z | 2016-09-30T16:38:36.000Z | #include <node.h>
#include <nan.h>
#include "node_omnistereo.h"
using namespace v8;
NAN_MODULE_INIT(NODE_init) {
Nan::HandleScope();
NODE_OpenVROmniStereo_init(target);
}
NODE_MODULE(allofw_openvr, NODE_init);
| 14.866667 | 39 | 0.73991 | donghaoren |
2059ce04d8c486bd5fa006fa15bae2c79f7b0733 | 887 | cpp | C++ | Algorithms/0654.Maximum_Binary_Tree.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0654.Maximum_Binary_Tree.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0654.Maximum_Binary_Tree.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution {
public:
int n;
vector<int> ar;
TreeNode* f(int l , int r) {
if(l > r)
return NULL;
else if(l == r)
return new TreeNode(ar[l]);
int best = l;
for( int i = l+1 ; i <= r ; i++ )
if(ar[i] > ar[best])
best = i;
TreeNode* res = new TreeNode(ar[best]);
res->left = f(l,best-1);
res->right = f(best+1,r);
return res;
}
TreeNode* constructMaximumBinaryTree(vector<int>& ar) {
this->ar = ar;
n = ar.size();
return f(0,n-1);
}
}; | 26.878788 | 90 | 0.499436 | metehkaya |
205c63011276c504199caa68bb444b85b1dbb6f4 | 1,728 | cpp | C++ | Graphics/Drawing/scale.cpp | YemSalat/jetcat | 6fffb814759bb7e46a9967e2c6226df3a1a0eb91 | [
"MIT"
] | 1 | 2016-04-20T13:47:20.000Z | 2016-04-20T13:47:20.000Z | Graphics/Drawing/scale.cpp | YemSalat/jetcat | 6fffb814759bb7e46a9967e2c6226df3a1a0eb91 | [
"MIT"
] | null | null | null | Graphics/Drawing/scale.cpp | YemSalat/jetcat | 6fffb814759bb7e46a9967e2c6226df3a1a0eb91 | [
"MIT"
] | null | null | null | /********************************************************************************/
/* Portable Graphics Library for Embedded Systems * (C) Componentality Oy, 2015 */
/* Initial design and development: Konstantin A. Khait */
/* Support, comments and questions: dev@componentality.com */
/********************************************************************************/
/* Definitions of the surface which upscales or downscales image being output */
/* to it. Lets simply scale image without changing of the painting algorithms */
/* and approaches. */
/********************************************************************************/
#include "scale.h"
#define round_d(x) ((int) (x))
#define round_u(x) ((int) ((double) (x) + 0.9999))
using namespace Componentality::Graphics;
// Set individual pixel's color
void ScaledSurface::plot(const size_t x, const size_t y, const Color& color)
{
int _x = round_d(mXScaleFactor * x);
int _y = round_d(mYScaleFactor * y);
for (int i = _x; (round_u(i / mXScaleFactor) == x) && (i >= 0); i--)
{
for (int j = _y; (round_u(j / mYScaleFactor) == y) && (j >= 0); j--)
{
mMasterSurface.plot(i, j, color);
}
}
}
// Get individual pixel's color
Color ScaledSurface::peek(const size_t x, const size_t y)
{
double _x = mXScaleFactor * x;
double _y = mYScaleFactor * y;
return mMasterSurface.peek((size_t)_x, (size_t)_y);
}
// Get width
size_t ScaledSurface::getWidth() const
{
return (size_t)(mMasterSurface.getWidth() * mXScaleFactor);
}
// Get height
size_t ScaledSurface::getHeight() const
{
return (size_t)(mMasterSurface.getHeight() * mYScaleFactor);
}
| 33.230769 | 82 | 0.548032 | YemSalat |
205c891c1bd6ff5bdd8940cb2e0c9c229f9be53a | 1,113 | cpp | C++ | Chapter_5_Mathematics/Probability/kattis_anthony.cpp | BrandonTang89/CP4_Code | 5114471f439978dd11f6f2cbf6af20ca654593da | [
"MIT"
] | 2 | 2021-12-29T04:12:59.000Z | 2022-03-30T09:32:19.000Z | Chapter_5_Mathematics/Probability/kattis_anthony.cpp | BrandonTang89/CP4_Code | 5114471f439978dd11f6f2cbf6af20ca654593da | [
"MIT"
] | null | null | null | Chapter_5_Mathematics/Probability/kattis_anthony.cpp | BrandonTang89/CP4_Code | 5114471f439978dd11f6f2cbf6af20ca654593da | [
"MIT"
] | 1 | 2022-03-01T06:12:46.000Z | 2022-03-01T06:12:46.000Z | /**Kattis - anthony
* A relatively simple probability problem. The neat trick here is that we don't need to use
* both c_left and a_left as DP parameters since a_left + c_left = n - game so we can recover
* it from a_left and game.
*
* Time: O(a*(a+c)), Space: O(a*(a+c))
*/
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,fma")
#pragma GCC optimize("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
typedef long double ld;
int n, a, c;
ld memo[2005][1005];
ld round_prob[2005];
ld prob_win(int game, int a_left){
if (a_left == 0) return 0;
int c_left = n - game - a_left;
if (c_left == 0) return 1;
ld &ans = memo[game][a_left];
if (ans != -1) return ans;
ans = round_prob[game] * prob_win(game + 1, a_left) + (1 - round_prob[game]) * prob_win(game + 1, a_left - 1);
return ans;
}
int main(){
scanf("%d %d", &a, &c);
n = a + c; // n games are played
for (int i = 0; i < n; i++) scanf("%Le", &round_prob[i]);
memset(memo, -1, sizeof memo);
printf("%Lf\n", prob_win(0, a));
return 0;
} | 29.289474 | 114 | 0.617251 | BrandonTang89 |
205ed1e8175ec3c7902a7bdf40b42c9a315e7ec6 | 5,718 | ipp | C++ | contracts/libc++/upstream/test/support/archetypes.ipp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | contracts/libc++/upstream/test/support/archetypes.ipp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null | contracts/libc++/upstream/test/support/archetypes.ipp | cubetrain/CubeTrain | b930a3e88e941225c2c54219267f743c790e388f | [
"MIT"
] | null | null | null |
#ifndef DEFINE_BASE
#define DEFINE_BASE(Name) ::ArchetypeBases::NullBase
#endif
#ifndef DEFINE_EXPLICIT
#define DEFINE_EXPLICIT
#endif
#ifndef DEFINE_CONSTEXPR
#ifdef TEST_WORKAROUND_EDG_EXPLICIT_CONSTEXPR
#define DEFINE_CONSTEXPR
#else // TEST_WORKAROUND_EDG_EXPLICIT_CONSTEXPR
#define DEFINE_CONSTEXPR constexpr
#endif // TEST_WORKAROUND_EDG_EXPLICIT_CONSTEXPR
#endif
#ifndef DEFINE_ASSIGN_CONSTEXPR
#if TEST_STD_VER >= 14
#define DEFINE_ASSIGN_CONSTEXPR DEFINE_CONSTEXPR
#else
#define DEFINE_ASSIGN_CONSTEXPR
#endif
#endif
#ifndef DEFINE_CTOR
#define DEFINE_CTOR = default
#endif
#ifndef DEFINE_DEFAULT_CTOR
#define DEFINE_DEFAULT_CTOR DEFINE_CTOR
#endif
#ifndef DEFINE_ASSIGN
#define DEFINE_ASSIGN = default
#endif
#ifndef DEFINE_DTOR
#define DEFINE_DTOR(Name)
#endif
struct AllCtors : DEFINE_BASE(AllCtors) {
using Base = DEFINE_BASE(AllCtors);
using Base::Base;
using Base::operator=;
DEFINE_EXPLICIT DEFINE_CONSTEXPR AllCtors() DEFINE_DEFAULT_CTOR;
DEFINE_EXPLICIT DEFINE_CONSTEXPR AllCtors(AllCtors const&) DEFINE_CTOR;
DEFINE_EXPLICIT DEFINE_CONSTEXPR AllCtors(AllCtors &&) DEFINE_CTOR;
DEFINE_ASSIGN_CONSTEXPR AllCtors& operator=(AllCtors const&) DEFINE_ASSIGN;
DEFINE_ASSIGN_CONSTEXPR AllCtors& operator=(AllCtors &&) DEFINE_ASSIGN;
DEFINE_DTOR(AllCtors)
};
struct NoCtors : DEFINE_BASE(NoCtors) {
using Base = DEFINE_BASE(NoCtors);
DEFINE_EXPLICIT NoCtors() = delete;
DEFINE_EXPLICIT NoCtors(NoCtors const&) = delete;
NoCtors& operator=(NoCtors const&) = delete;
DEFINE_DTOR(NoCtors)
};
struct NoDefault : DEFINE_BASE(NoDefault) {
using Base = DEFINE_BASE(NoDefault);
using Base::Base;
DEFINE_EXPLICIT DEFINE_CONSTEXPR NoDefault() = delete;
DEFINE_DTOR(NoDefault)
};
struct DefaultOnly : DEFINE_BASE(DefaultOnly) {
using Base = DEFINE_BASE(DefaultOnly);
using Base::Base;
DEFINE_EXPLICIT DEFINE_CONSTEXPR DefaultOnly() DEFINE_DEFAULT_CTOR;
DefaultOnly(DefaultOnly const&) = delete;
DefaultOnly& operator=(DefaultOnly const&) = delete;
DEFINE_DTOR(DefaultOnly)
};
struct Copyable : DEFINE_BASE(Copyable) {
using Base = DEFINE_BASE(Copyable);
using Base::Base;
DEFINE_EXPLICIT DEFINE_CONSTEXPR Copyable() DEFINE_DEFAULT_CTOR;
DEFINE_EXPLICIT DEFINE_CONSTEXPR Copyable(Copyable const &) DEFINE_CTOR;
Copyable &operator=(Copyable const &) DEFINE_ASSIGN;
DEFINE_DTOR(Copyable)
};
struct CopyOnly : DEFINE_BASE(CopyOnly) {
using Base = DEFINE_BASE(CopyOnly);
using Base::Base;
DEFINE_EXPLICIT DEFINE_CONSTEXPR CopyOnly() DEFINE_DEFAULT_CTOR;
DEFINE_EXPLICIT DEFINE_CONSTEXPR CopyOnly(CopyOnly const &) DEFINE_CTOR;
DEFINE_EXPLICIT DEFINE_CONSTEXPR CopyOnly(CopyOnly &&) = delete;
CopyOnly &operator=(CopyOnly const &) DEFINE_ASSIGN;
CopyOnly &operator=(CopyOnly &&) = delete;
DEFINE_DTOR(CopyOnly)
};
struct NonCopyable : DEFINE_BASE(NonCopyable) {
using Base = DEFINE_BASE(NonCopyable);
using Base::Base;
DEFINE_EXPLICIT DEFINE_CONSTEXPR NonCopyable() DEFINE_DEFAULT_CTOR;
DEFINE_EXPLICIT DEFINE_CONSTEXPR NonCopyable(NonCopyable const &) = delete;
NonCopyable &operator=(NonCopyable const &) = delete;
DEFINE_DTOR(NonCopyable)
};
struct MoveOnly : DEFINE_BASE(MoveOnly) {
using Base = DEFINE_BASE(MoveOnly);
using Base::Base;
DEFINE_EXPLICIT DEFINE_CONSTEXPR MoveOnly() DEFINE_DEFAULT_CTOR;
DEFINE_EXPLICIT DEFINE_CONSTEXPR MoveOnly(MoveOnly &&) DEFINE_CTOR;
MoveOnly &operator=(MoveOnly &&) DEFINE_ASSIGN;
DEFINE_DTOR(MoveOnly)
};
struct CopyAssignable : DEFINE_BASE(CopyAssignable) {
using Base = DEFINE_BASE(CopyAssignable);
using Base::Base;
DEFINE_EXPLICIT DEFINE_CONSTEXPR CopyAssignable() = delete;
CopyAssignable& operator=(CopyAssignable const&) DEFINE_ASSIGN;
DEFINE_DTOR(CopyAssignable)
};
struct CopyAssignOnly : DEFINE_BASE(CopyAssignOnly) {
using Base = DEFINE_BASE(CopyAssignOnly);
using Base::Base;
DEFINE_EXPLICIT DEFINE_CONSTEXPR CopyAssignOnly() = delete;
CopyAssignOnly& operator=(CopyAssignOnly const&) DEFINE_ASSIGN;
CopyAssignOnly& operator=(CopyAssignOnly &&) = delete;
DEFINE_DTOR(CopyAssignOnly)
};
struct MoveAssignOnly : DEFINE_BASE(MoveAssignOnly) {
using Base = DEFINE_BASE(MoveAssignOnly);
using Base::Base;
DEFINE_EXPLICIT DEFINE_CONSTEXPR MoveAssignOnly() = delete;
MoveAssignOnly& operator=(MoveAssignOnly const&) = delete;
MoveAssignOnly& operator=(MoveAssignOnly &&) DEFINE_ASSIGN;
DEFINE_DTOR(MoveAssignOnly)
};
struct ConvertingType : DEFINE_BASE(ConvertingType) {
using Base = DEFINE_BASE(ConvertingType);
using Base::Base;
DEFINE_EXPLICIT DEFINE_CONSTEXPR ConvertingType() DEFINE_DEFAULT_CTOR;
DEFINE_EXPLICIT DEFINE_CONSTEXPR ConvertingType(ConvertingType const&) DEFINE_CTOR;
DEFINE_EXPLICIT DEFINE_CONSTEXPR ConvertingType(ConvertingType &&) DEFINE_CTOR;
ConvertingType& operator=(ConvertingType const&) DEFINE_ASSIGN;
ConvertingType& operator=(ConvertingType &&) DEFINE_ASSIGN;
template <class ...Args>
DEFINE_EXPLICIT DEFINE_CONSTEXPR ConvertingType(Args&&...) {}
template <class Arg>
ConvertingType& operator=(Arg&&) { return *this; }
DEFINE_DTOR(ConvertingType)
};
template <template <class...> class List>
using ApplyTypes = List<
AllCtors,
NoCtors,
NoDefault,
DefaultOnly,
Copyable,
CopyOnly,
NonCopyable,
MoveOnly,
CopyAssignable,
CopyAssignOnly,
MoveAssignOnly,
ConvertingType
>;
#undef DEFINE_BASE
#undef DEFINE_EXPLICIT
#undef DEFINE_CONSTEXPR
#undef DEFINE_ASSIGN_CONSTEXPR
#undef DEFINE_CTOR
#undef DEFINE_DEFAULT_CTOR
#undef DEFINE_ASSIGN
#undef DEFINE_DTOR
| 32.862069 | 86 | 0.764953 | cubetrain |
205f2e1b4ac818c618cb2cabdb762fca7fbb673c | 14,763 | cpp | C++ | Test.cpp | Sarah-han/War-game-a-b | 7ac91779b294f12fc9616836166a9efde9d711f2 | [
"MIT"
] | null | null | null | Test.cpp | Sarah-han/War-game-a-b | 7ac91779b294f12fc9616836166a9efde9d711f2 | [
"MIT"
] | null | null | null | Test.cpp | Sarah-han/War-game-a-b | 7ac91779b294f12fc9616836166a9efde9d711f2 | [
"MIT"
] | null | null | null | #include "doctest.h"
#include <stdbool.h>
#include "Board.hpp"
#include "FootCommander.hpp"
#include "FootSoldier.hpp"
#include "Paramedic.hpp"
#include "ParamedicCommander.hpp"
#include "Sniper.hpp"
#include "SniperCommander.hpp"
#include "Soldier.hpp"
using namespace WarGame;
TEST_CASE("Snipers And Paramedics") {
Board board(6,6);
//-----Player 1 soldiers-------//
CHECK(!board.has_soldiers(1));
board[{0,0}] = new Paramedic(1);
CHECK(typeid(board[{0,0}]) == typeid(Paramedic)); //Checks whether placement has occurred
CHECK(board.has_soldiers(1));
board[{0,1}] = new ParamedicCommander(1);
CHECK(typeid(board[{0,1}]) == typeid(ParamedicCommander)); //Checks whether placement has occurred
board[{0,2}] = new Sniper(1);
CHECK(typeid(board[{0,2}]) == typeid(Sniper)); //Checks whether placement has occurred
board[{0,3}] = new SniperCommander(1);
CHECK(typeid(board[{0,3}]) == typeid(SniperCommander)); //Checks whether placement has occurred
board[{0,4}] = new Paramedic(1);
CHECK(typeid(board[{0,4}]) == typeid(Paramedic)); //Checks whether placement has occurred
board[{0,5}] = new Sniper(1);
CHECK(typeid(board[{0,5}]) == typeid(Sniper)); //Checks whether placement has occurred
CHECK(board.has_soldiers(1));
//-----Player 2 soldiers-------//
CHECK(!board.has_soldiers(2));
board[{5,5}] = new Paramedic(2);
CHECK(typeid(board[{5,5}]) == typeid(Paramedic)); //Checks whether placement has occurred
CHECK(board.has_soldiers(2));
board[{5,4}] = new ParamedicCommander(2);
CHECK(typeid(board[{5,4}]) == typeid(ParamedicCommander)); //Checks whether placement has occurred
board[{5,3}] = new Sniper(2);
CHECK(typeid(board[{5,3}]) == typeid(Sniper)); //Checks whether placement has occurred
board[{5,2}] = new SniperCommander(2);
CHECK(typeid(board[{5,2}]) == typeid(SniperCommander)); //Checks whether placement has occurred
board[{5,1}] = new Paramedic(2);
CHECK(typeid(board[{5,1}]) == typeid(Paramedic)); //Checks whether placement has occurred
board[{5,0}] = new Sniper(2);
CHECK(typeid(board[{5,0}]) == typeid(Sniper)); //Checks whether placement has occurred
CHECK(board.has_soldiers(2));
//-----------moves---------------------------------------------------------
CHECK_NOTHROW(board.move(1, {0,3}, Board::MoveDIR::Up)); // move to {1,3} and shoot; damage 10
CHECK(board[{0,3}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {1,3}]) == typeid(SniperCommander)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(2, {5,2}, Board::MoveDIR::Down)); // move to {4,2} and shoot; damage 10
CHECK(board[{5,2}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {4,2}]) == typeid(SniperCommander));
CHECK_NOTHROW(board.move(1, {0,5}, Board::MoveDIR::Up)); // move to {1,5} and shoot; damage 10
CHECK(board[{0,5}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {1,5}]) == typeid(Sniper)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(2, {5,0}, Board::MoveDIR::Down)); // move to {4,0} and shoot; damage 10
CHECK(board[{5,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {4,0}]) == typeid(Sniper));
CHECK_NOTHROW(board.move(1, {1,3}, Board::MoveDIR::Up)); // move to {2,3} and shoot; damage 10
CHECK(board[{1,3}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {2,3}]) == typeid(SniperCommander)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(2, {5,3}, Board::MoveDIR::Down)); // move to {4,3} and shoot; damage 10
CHECK(board[{5,3}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {4,3}]) == typeid(Sniper));
CHECK_NOTHROW(board.move(1, {0,4}, Board::MoveDIR::Up)); // move to {1,4} and shoot; damage 10
CHECK(board[{0,4}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {1,4}]) == typeid(Paramedic)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(2, {4,3}, Board::MoveDIR::Down)); // move to {3,3} and shoot; damage 10
CHECK(board[{4,3}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {3,3}]) == typeid(Sniper));
CHECK_NOTHROW(board.move(1, {0,2}, Board::MoveDIR::Up)); // move to {1,2} and shoot; damage 10
CHECK(board[{0,2}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {1,2}]) == typeid(Sniper)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(2, {5,1}, Board::MoveDIR::Down)); // move to {4,1} and shoot; damage 10
CHECK(board[{5,1}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {4,1}]) == typeid(Paramedic));
}
TEST_CASE("Foot soldiers simple game") {
Board board (8,1);
CHECK(!board.has_soldiers(1));
board[{0,0}] = new FootSoldier(1);
CHECK(board.has_soldiers(1));
CHECK(!board.has_soldiers(2));
board[{7,0}] = new FootSoldier(2);
CHECK(board.has_soldiers(2));
CHECK_NOTHROW(board.move(1, {0,0}, Board::MoveDIR::Up)); // move to {1,0} and shoot; damage 10
CHECK(board[{0,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {1,0}]) == typeid(FootSoldier)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW( board.move(1, {1,0}, Board::MoveDIR::Down)); // move back to {0,0} and shoot; damage 10
CHECK(board[{1,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {0,0}]) == typeid(FootSoldier)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(1, {0,0}, Board::MoveDIR::Up)); // move to {1,0} and shoot; damage 10
CHECK(board[{0,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {1,0}]) == typeid(FootSoldier)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(1, {1,0}, Board::MoveDIR::Down)); // move back to {0,0} and shoot; damage 10
CHECK(board[{1,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {0,0}]) == typeid(FootSoldier)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(1, {0,0}, Board::MoveDIR::Up)); // move to {1,0} and shoot; damage 10
CHECK(board[{0,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {1,0}]) == typeid(FootSoldier)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(1, {1,0}, Board::MoveDIR::Down)); // move back to {0,0} and shoot; damage 10
CHECK(board[{1,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{0,0}]) == typeid(FootSoldier)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(1, {0,0}, Board::MoveDIR::Up)); // move to {1,0} and shoot; damage 10
CHECK(board[{0,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {1,0}]) == typeid(FootSoldier)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(1, {1,0}, Board::MoveDIR::Down)); // move back to {0,0} and shoot; damage 10
CHECK(board[{1,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{0,0}]) == typeid(FootSoldier)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(1, {0,0}, Board::MoveDIR::Up)); // move to {1,0} and shoot; damage 10
CHECK(board[{0,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[ {1,0}]) == typeid(FootSoldier)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK_NOTHROW(board.move(1, {1,0}, Board::MoveDIR::Down)); // move back to {0,0} and shoot; damage 10
CHECK(board[{1,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{0,0}]) == typeid(FootSoldier)); //Checks whether the new location has the right soldier type,i.e the soldier has actually moved
CHECK(!board.has_soldiers(2));
CHECK(board.has_soldiers(1));
}
TEST_CASE("Foot soldiers simple game2") {
Board board (4,4);
CHECK(!board.has_soldiers(1));
board[{0,0}] = new FootSoldier(1);
CHECK(typeid(board[{0,0}]) == typeid(FootSoldier)); //Checks whether placement has occurred
CHECK(board.has_soldiers(1));
board[{0,3}] = new FootCommander(1);
CHECK(typeid(board[{0,3}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK(board.has_soldiers(1));
CHECK(!board.has_soldiers(2));
board[{3,0}] = new FootSoldier(2);
CHECK(typeid(board[{3,0}]) == typeid(FootSoldier)); //Checks whether placement has occurred
board[{3,1}] = new Paramedic(2);
CHECK(typeid(board[{3,1}]) == typeid(Paramedic)); //Checks whether placement has occurred
board[{3,3}] = new FootCommander(2);
CHECK(typeid(board[{3,3}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK(board.has_soldiers(2));
CHECK_NOTHROW(board.move(1, {0,3}, Board::MoveDIR::Up)); // move to {1,3} and shoot; damage 10 and damage 20
CHECK(board[{0,3}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{1,3}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK_NOTHROW(board.move(2, {3,3}, Board::MoveDIR::Left)); // move to {3,2} and shoot; damage 10 and damage 20
CHECK(board[{3,3}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{3,2}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK_NOTHROW(board.move(1, {0,0}, Board::MoveDIR::Right)); // move to {0,1} and shoot; damage 10
CHECK(board[{0,0}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{0,1}]) == typeid(FootSoldier)); //Checks whether placement has occurred
CHECK_NOTHROW( board.move(2, {3,1}, Board::MoveDIR::Down)); // move back to {2,0} and shoot; damage 10
CHECK(board[{3,1}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{2,1}]) == typeid(Paramedic)); //Checks whether placement has occurred
CHECK_NOTHROW( board.move(1, {1,3}, Board::MoveDIR::Up)); // move to {1,0} and shoot; damage 10
CHECK(board[{1,3}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{2,3}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK_NOTHROW( board.move(2, {3,2}, Board::MoveDIR::Down)); // move to {1,0} and shoot; damage 10
CHECK(board[{3,2}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{2,2}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK_NOTHROW( board.move(2, {2,2}, Board::MoveDIR::Up)); // move to {1,0} and shoot; damage 10
CHECK(board[{2,2}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{3,2}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK_NOTHROW( board.move(2, {3,2}, Board::MoveDIR::Down)); // move to {1,0} and shoot; damage 10
CHECK(board[{3,2}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{2,2}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK_NOTHROW( board.move(2, {2,2}, Board::MoveDIR::Up)); // move to {1,0} and shoot; damage 10
CHECK(board[{2,2}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{3,2}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK_NOTHROW( board.move(2, {3,2}, Board::MoveDIR::Down)); // move to {1,0} and shoot; damage 10
CHECK(board[{3,2}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{2,2}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK_NOTHROW( board.move(2, {2,2}, Board::MoveDIR::Up)); // move to {1,0} and shoot; damage 10
CHECK(board[{2,2}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{3,2}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK_NOTHROW( board.move(2, {3,2}, Board::MoveDIR::Down)); // move to {1,0} and shoot; damage 10
CHECK(board[{3,2}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{2,2}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK_NOTHROW( board.move(2, {2,2}, Board::MoveDIR::Up)); // move to {1,0} and shoot; damage 10
CHECK(board[{2,2}]== nullptr); //Checks whether the soldier is moving and is no longer in his starting position
CHECK(typeid(board[{3,2}]) == typeid(FootCommander)); //Checks whether placement has occurred
CHECK(!board.has_soldiers(2));
CHECK(board.has_soldiers(1));
} | 66.800905 | 156 | 0.681095 | Sarah-han |
20619a8f37ec5b930d378502f1fe0deeed17cb8c | 33,375 | cpp | C++ | testing/tests/test_bb.cpp | ddugovic/ToppleChess | 79e27f74023ea72463dfdbc6c6760705677dec1a | [
"MIT"
] | null | null | null | testing/tests/test_bb.cpp | ddugovic/ToppleChess | 79e27f74023ea72463dfdbc6c6760705677dec1a | [
"MIT"
] | null | null | null | testing/tests/test_bb.cpp | ddugovic/ToppleChess | 79e27f74023ea72463dfdbc6c6760705677dec1a | [
"MIT"
] | null | null | null | //
// Created by Vincent on 27/09/2017.
//
#include "../catch.hpp"
#include "../util.h"
TEST_CASE("Bitboard engine") {
SECTION("Table initialisation") {
REQUIRE_NOTHROW(init_tables());
}
SECTION("General operations") {
SECTION("Single bit") {
REQUIRE(single_bit(E4) == U64(1) << E4);
REQUIRE(single_bit(A1) == U64(1) << A1);
REQUIRE(single_bit(H8) == U64(1) << H8);
REQUIRE(single_bit(A8) == U64(1) << A8);
REQUIRE(single_bit(H1) == U64(1) << H1);
REQUIRE(single_bit(G2) == U64(1) << G2);
}
SECTION("popLSB") {
U64 bb = c_u64({0, 0, 0, 0, 0, 0, 1, 0,
0, 1, 0, 1, 0, 0, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 1, 1, 1, 0, 0, 0});
REQUIRE(pop_bit(bb) == C1);
REQUIRE(pop_bit(bb) == D1);
REQUIRE(pop_bit(bb) == E1);
REQUIRE(pop_bit(bb) == F2);
REQUIRE(pop_bit(bb) == F4);
REQUIRE(pop_bit(bb) == A5);
REQUIRE(pop_bit(bb) == F6);
REQUIRE(pop_bit(bb) == B7);
REQUIRE(pop_bit(bb) == D7);
REQUIRE(pop_bit(bb) == H7);
REQUIRE(pop_bit(bb) == G8);
REQUIRE(bb == 0);
}
/*
SECTION("popMSB") {
U64 bb = c_u64({0, 0, 0, 0, 0, 0, 1, 0,
0, 1, 0, 1, 0, 0, 0, 1,
0, 0, 0, 0, 0, 1, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 1, 1, 1, 0, 0, 0});
REQUIRE(pop_bit(BLACK, bb) == G8);
REQUIRE(pop_bit(BLACK, bb) == H7);
REQUIRE(pop_bit(BLACK, bb) == D7);
REQUIRE(pop_bit(BLACK, bb) == B7);
REQUIRE(pop_bit(BLACK, bb) == F6);
REQUIRE(pop_bit(BLACK, bb) == A5);
REQUIRE(pop_bit(BLACK, bb) == F4);
REQUIRE(pop_bit(BLACK, bb) == F2);
REQUIRE(pop_bit(BLACK, bb) == E1);
REQUIRE(pop_bit(BLACK, bb) == D1);
REQUIRE(pop_bit(BLACK, bb) == C1);
REQUIRE(bb == 0);
}
*/
SECTION("Square index lookup") {
REQUIRE(square_index(0, 0) == A1);
REQUIRE(square_index(2, 2) == C3);
REQUIRE(square_index(7, 7) == H8);
REQUIRE(square_index(3, 2) == D3);
REQUIRE(square_index(4, 6) == E7);
}
SECTION("String conversion") {
SECTION("From string") {
REQUIRE(to_sq('e', '4') == E4);
REQUIRE(to_sq('f', '8') == F8);
REQUIRE(to_sq('a', '1') == A1);
REQUIRE(to_sq('g', '2') == G2);
REQUIRE(to_sq('h', '8') == H8);
REQUIRE_THROWS(to_sq('!', 'k'));
REQUIRE_THROWS(to_sq('i', '4'));
REQUIRE_THROWS(to_sq('b', '0'));
REQUIRE_THROWS(to_sq('c', '9'));
}
SECTION("To string") {
REQUIRE(from_sq(A4) == "a4");
REQUIRE(from_sq(B8) == "b8");
REQUIRE(from_sq(C5) == "c5");
REQUIRE(from_sq(H8) == "h8");
REQUIRE(from_sq(D4) == "d4");
}
}
SECTION("Alignment") {
REQUIRE(aligned(A1, B2));
REQUIRE(aligned(A1, B1));
REQUIRE(aligned(A1, A2));
REQUIRE(!aligned(E4, B5));
REQUIRE(aligned(B2, G7));
REQUIRE(!aligned(A1, C2));
REQUIRE(aligned(A1, B2, F6));
REQUIRE(aligned(A1, D1, G1));
REQUIRE(aligned(B2, B6, B4));
REQUIRE(!aligned(E4, B5));
REQUIRE(!aligned(B2, D5, G7));
REQUIRE(!aligned(A1, C2));
}
SECTION("Population count") {
REQUIRE(pop_count(0b0001100100100011000100100111000000000000000000010000000000000000) == 12);
REQUIRE(pop_count(0b0000000000000000000000000000000000000000000000000000000000000000) == 0);
REQUIRE(pop_count(0b1111111111111111111111111111111111111111111111111111111111111111) == 64);
REQUIRE(pop_count(0b1000100111100011111100110111000000000110001000011111000000010010) == 27);
}
}
SECTION("Bitboard move generation") {
Square square;
U64 expected;
SECTION("Pawn tables") {
square = A2;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(bb_normal_moves::pawn_moves_x1[WHITE][square] == expected);
square = A7;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(bb_normal_moves::pawn_moves_x1[BLACK][square] == expected);
}
SECTION("King") {
square = E5;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 0, 0,
0, 0, 0, 1, 0, 1, 0, 0,
0, 0, 0, 1, 1, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KING>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KING>(WHITE, square, 0) == expected);
square = A1;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KING>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KING>(WHITE, square, 0) == expected);
square = H8;
expected = c_u64({0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KING>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KING>(WHITE, square, 0) == expected);
square = D8;
expected = c_u64({0, 0, 1, 0, 1, 0, 0, 0,
0, 0, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KING>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KING>(WHITE, square, 0) == expected);
square = E1;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 1, 0, 0,
0, 0, 0, 1, 0, 1, 0, 0});
REQUIRE(find_moves<KING>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KING>(WHITE, square, 0) == expected);
square = H3;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KING>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KING>(WHITE, square, 0) == expected);
square = A7;
expected = c_u64({1, 1, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0,
1, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KING>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KING>(WHITE, square, 0) == expected);
}
SECTION("Knight") {
square = E5;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 1, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0,
0, 0, 0, 1, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KNIGHT>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KNIGHT>(WHITE, square, 0) == expected);
square = A1;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KNIGHT>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KNIGHT>(WHITE, square, 0) == expected);
square = H8;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KNIGHT>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KNIGHT>(WHITE, square, 0) == expected);
square = G4;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KNIGHT>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KNIGHT>(WHITE, square, 0) == expected);
square = E1;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 1, 0, 0,
0, 0, 1, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KNIGHT>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KNIGHT>(WHITE, square, 0) == expected);
square = H3;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0});
REQUIRE(find_moves<KNIGHT>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KNIGHT>(WHITE, square, 0) == expected);
square = A7;
expected = c_u64({0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<KNIGHT>(BLACK, square, 0) == expected);
REQUIRE(find_moves<KNIGHT>(WHITE, square, 0) == expected);
}
SECTION("Pawn") {
U64 occupied;
SECTION("Normal moves") {
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0}); // C4
REQUIRE(find_moves<PAWN>(BLACK, C5, 0) == expected);
REQUIRE(find_moves<PAWN>(WHITE, C3, 0) == expected);
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0}); // D5
REQUIRE(find_moves<PAWN>(BLACK, D6, 0) == expected);
REQUIRE(find_moves<PAWN>(WHITE, D4, 0) == expected);
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0}); // C4
REQUIRE(find_moves<PAWN>(WHITE, A5, 0) == expected);
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0}); // C4
REQUIRE(find_moves<PAWN>(BLACK, G3, 0) == expected);
}
SECTION("Double moves") {
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(BLACK, G2, 0) != expected);
REQUIRE(find_moves<PAWN>(WHITE, G2, 0) == expected);
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(BLACK, C7, 0) == expected);
REQUIRE(find_moves<PAWN>(WHITE, C7, 0) != expected);
}
SECTION("Square in front occupied") {
occupied = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(WHITE, B4, occupied) == expected);
REQUIRE(find_moves<PAWN>(BLACK, B6, occupied) == expected);
REQUIRE(find_moves<PAWN>(WHITE, D6, occupied) == expected);
REQUIRE(find_moves<PAWN>(BLACK, E6, occupied) == expected);
REQUIRE(find_moves<PAWN>(WHITE, E4, occupied) == expected);
REQUIRE(find_moves<PAWN>(BLACK, F7, occupied) == expected);
REQUIRE(find_moves<PAWN>(WHITE, F5, occupied) == expected);
REQUIRE(find_moves<PAWN>(BLACK, F4, occupied) == expected);
REQUIRE(find_moves<PAWN>(WHITE, F2, occupied) == expected);
REQUIRE(find_moves<PAWN>(BLACK, H6, occupied) == expected);
REQUIRE(find_moves<PAWN>(WHITE, H4, occupied) == expected);
// Blocking the second square of the double move
occupied = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(BLACK, E7, occupied) == expected);
// Blocking the second square of the double move
occupied = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1,
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(WHITE, B2, occupied) == expected);
}
SECTION("Normal moves with captures") {
occupied = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 1, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 1, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(BLACK, D6, occupied) == expected);
REQUIRE(find_moves<PAWN>(WHITE, D4, occupied) == expected);
occupied = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 1, 0, 0, 1, 0,
0, 0, 0, 0, 1, 0, 1, 0,
0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(BLACK, H6, occupied) == expected);
REQUIRE(find_moves<PAWN>(WHITE, H4, occupied) == expected);
}
SECTION("Mixed situations") {
occupied = c_u64({0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 1, 0, 0, 0, 0,
0, 0, 1, 0, 0, 1, 0, 0,
0, 1, 0, 0, 1, 0, 1, 1,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
1, 1, 1, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0});
square = B7;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 1, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(BLACK, square, occupied) == expected);
square = D7;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(BLACK, square, occupied) == expected);
square = E3;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(WHITE, square, occupied) == expected);
square = G4;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<PAWN>(WHITE, square, occupied) == expected);
}
}
SECTION("Bishop") {
U64 occupied = c_u64({0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 1, 0, 0, 0, 0,
0, 0, 1, 0, 0, 1, 0, 0,
0, 1, 0, 0, 1, 0, 1, 1,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
1, 1, 1, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0});
square = E4;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 1, 0, 0, 0, 1, 0,
0, 0, 0, 1, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 1, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<BISHOP>(WHITE, square, occupied) == expected);
REQUIRE(find_moves<BISHOP>(BLACK, square, occupied) == expected);
square = C1;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 1, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<BISHOP>(WHITE, square, occupied) == expected);
REQUIRE(find_moves<BISHOP>(BLACK, square, occupied) == expected);
square = D3;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 1, 0,
0, 1, 0, 0, 0, 1, 0, 0,
0, 0, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0});
REQUIRE(find_moves<BISHOP>(WHITE, square, occupied) == expected);
REQUIRE(find_moves<BISHOP>(BLACK, square, occupied) == expected);
square = D8;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 1, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<BISHOP>(WHITE, square, occupied) == expected);
REQUIRE(find_moves<BISHOP>(BLACK, square, occupied) == expected);
}
SECTION("Rook") {
U64 occupied = c_u64({0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 1, 1, 0, 0, 0, 0,
0, 0, 1, 0, 0, 1, 0, 0,
0, 1, 0, 0, 1, 0, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0,
1, 1, 1, 0, 0, 0, 1, 1,
0, 0, 0, 0, 0, 0, 0, 0});
square = E4;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
1, 1, 1, 1, 0, 1, 1, 1,
0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, 1, 0, 0, 0});
REQUIRE(find_moves<ROOK>(WHITE, square, occupied) == expected);
REQUIRE(find_moves<ROOK>(BLACK, square, occupied) == expected);
square = C1;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 1, 0, 0, 0, 0, 0,
1, 1, 0, 1, 1, 1, 1, 1});
REQUIRE(find_moves<ROOK>(WHITE, square, occupied) == expected);
REQUIRE(find_moves<ROOK>(BLACK, square, occupied) == expected);
square = D3;
expected = c_u64({0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
1, 1, 1, 0, 1, 1, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0});
REQUIRE(find_moves<ROOK>(WHITE, square, occupied) == expected);
REQUIRE(find_moves<ROOK>(BLACK, square, occupied) == expected);
square = D8;
expected = c_u64({1, 1, 1, 0, 1, 0, 0, 0,
0, 0, 0, 1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0});
REQUIRE(find_moves<ROOK>(WHITE, square, occupied) == expected);
REQUIRE(find_moves<ROOK>(BLACK, square, occupied) == expected);
}
}
SECTION("Utility") {
REQUIRE(E4 + rel_offset(WHITE, D_N) == E5);
REQUIRE(E5 + rel_offset(BLACK, D_N) == E4);
REQUIRE(E4 + rel_offset(WHITE, D_NE) == F5);
REQUIRE(E4 + rel_offset(WHITE, D_NW) == D5);
REQUIRE(E5 + rel_offset(BLACK, D_NE) == D4);
REQUIRE(E5 + rel_offset(BLACK, D_NW) == F4);
}
} | 45.470027 | 105 | 0.292584 | ddugovic |
20655d6ec142d8aabab826e5c12e0809b6338ef7 | 17,930 | c++ | C++ | src/Note.c++ | dsvi/NotesTree | e9f932027281f8eb2e53dcd250d99bc48caeeabf | [
"Zlib"
] | null | null | null | src/Note.c++ | dsvi/NotesTree | e9f932027281f8eb2e53dcd250d99bc48caeeabf | [
"Zlib"
] | null | null | null | src/Note.c++ | dsvi/NotesTree | e9f932027281f8eb2e53dcd250d99bc48caeeabf | [
"Zlib"
] | null | null | null | #include "Note.h"
using namespace std;
using namespace boost::filesystem;
const char Note::delimChar;
Note::Note()
{
}
Note::~Note()
{
}
bool Note::hasAttach()
{
if (parent_)
return exists(attachDir());
return false;
}
QString Note::decodeFromFilename(const boost::filesystem::path &filename)
{
QString ret;
QString fn(filename.c_str());
ret.reserve(fn.size());
for (auto c = fn.begin(); c != fn.end(); ++c){
if (*c == delimChar){
QString num;
for (int i = 2; --i >= 0;){
if (++c == fn.end()){
throw Exception(QCoreApplication::translate(
"Filesystem", "Wrong num after delimiter %1 in file name: %2").arg(delimChar).arg(fn));
}
num += *c;
}
bool ok;
int code = num.toInt(&ok, 16);
if (!ok){
throw Exception(QCoreApplication::translate(
"Filesystem", "Wrong num after delimiter %1 in file name: %2").arg(delimChar).arg(fn));
}
ret += QChar(code);
}
else{
ret += *c;
}
}
return ret;
}
boost::filesystem::path Note::encodeToFilename(const QString &name)
{
QString ret;
ret.reserve(name.size());
for (auto i = name.begin(); i != name.end(); ++i){
auto c = *i;
if (c == delimChar || c == L'/' || c == L'\\' || (i == name.begin() && c == L'.')){
ret += delimChar;
QString num;
num.setNum(c.unicode(), 16);
ASSERT(num.length() <= 2);
if (num.length() < 2)
ret += L'0';
ret += num;
}
else{
ret += c;
}
}
return path(ret.toUtf8());
}
void Note::addFromSubnotesDir(const boost::filesystem::path &path)
{
if (name_.isNull())
name_ = decodeFromFilename(path.filename());
std::unordered_map<QString, directory_entry> dirs;
for (auto&& x : directory_iterator(path))
if (x.status().type() == file_type::directory_file && x.path().filename().native()[0] != '.')
dirs.insert({x.path().filename().c_str(), x});
for (directory_entry& fi : directory_iterator(path)){
if (fi.status().type() == file_type::directory_file)
continue;
QString name = fi.path().filename().c_str();
if (!name.endsWith(Note::textExt))
continue;
auto subNote = make_shared<Note>();
subNote->createFromNoteTextFile(fi.path());
addNote(subNote);
class path subDir = subNote->subNotesDir();
if (exists(subDir))
subNote->addFromSubnotesDir(subDir);
dirs.erase(toQS(encodeToFilename(subNote->name_)));
dirs.erase(toQS(encodeToFilename(subNote->name_ + attachExt)));
dirs.erase(toQS(encodeToFilename(subNote->name_ + embedExt)));
}
for (auto dir = dirs.begin(); dir != dirs.end(); ){
const boost::filesystem::path &dirPath = dir->second.path();
if (
toQS(dirPath.filename()).endsWith(attachExt) ||
toQS(dirPath.filename()).endsWith(embedExt)
){
++dir;
continue;
}
auto subNote = make_shared<Note>();
subNote->name_ = decodeFromFilename(dirPath.filename());
addNote(subNote);
subNote->addFromSubnotesDir(dirPath);
dirs.erase(toQS(encodeToFilename(subNote->name_ + attachExt)));
dirs.erase(toQS(encodeToFilename(subNote->name_ + embedExt)));
dir = dirs.erase(dir);
}
// just in case we happened to have a note name ending on attachExt etc
// kinda stupid part
for (auto &dir : dirs){
const boost::filesystem::path &dirPath = dir.second.path();
auto subNote = make_shared<Note>();
subNote->name_ = decodeFromFilename(dirPath.filename());
addNote(subNote);
subNote->addFromSubnotesDir(dirPath);
}
}
void Note::createFromNoteTextFile(const path &fi)
{
path name = fi.filename();
ASSERT(name.extension() == Note::textExt);
name = name.stem();
name_ = decodeFromFilename(name);
}
void Note::createHierarchyFromRoot(const path &p)
{
try{
ASSERT(parent_ == nullptr);
emit clear();
subNotes_.clear();
name_ = toQS(p);
if (!exists(p))
throw RecoverableException(QCoreApplication::translate("Filesystem", "directory '%1' doesnt exist").arg(name_));
addFromSubnotesDir(p);
}
catch(...){
subNotes_.clear();
name_.clear();
warning("Can't load notes.");
}
}
void Note::move(const boost::filesystem::path &newPath, const boost::filesystem::path &newFileName)
{
ASSERT(is_directory(newPath));
auto ren = [&](const path &oldPath, const char *ext){
if (exists(oldPath)){
path newPathname = newPath / newFileName;
if (ext)
newPathname += ext;
rename(oldPath, newPathname);
}
};
ren(textPathname(), textExt);
ren(subNotesDir(), nullptr);
ren(attachDir(), attachExt);
ren(embedDir(), embedExt);
}
void Note::adopt_(const std::shared_ptr<Note> &n)
{
if (n.get() == this)
throw Exception(tr("Can't add as subnote to self. (%1)").arg(name_));
ensureSubDirExist();
n->move(subNotesDir(), encodeToFilename(n->name_));
addNote(n->removeFromParent());
}
void Note::cleanUpFileSystem()
{
if ( parent_ == nullptr ) //nothing to clean up at root
return;
auto subDir = subNotesDir();
auto textFile = textPathname();
auto attach = attachDir();
auto embed = embedDir();
if (exists(subDir) && boost::filesystem::is_empty(subDir) && exists(textFile))
remove(subDir);
if (exists(textFile) && boost::filesystem::is_empty(textFile) && exists(subDir))
remove(textFile);
if (exists(attach) && boost::filesystem::is_empty(attach))
remove(attach);
if (exists(embed) && boost::filesystem::is_empty(embed))
remove(embed);
}
void Note::ensureSubDirExist()
{
auto subDir = subNotesDir();
if (exists(subDir))
return;
create_directory(subDir);
}
void Note::warning(QString &&msg)
{
try{
throw_with_nested(RecoverableException(std::move(msg)));
}
catch(...){
app->reportError(std::current_exception());
}
}
void Note::error(QString &&msg)
{
try{
throw_with_nested(Exception(std::move(msg)));
}
catch(...){
error();
}
}
void Note::error()
{
auto e = std::current_exception();
if (!isRecoverable(e)){
Note *r = root();
r->subNotes_.clear(); // zombify!
r->name_.clear();
}
app->error(e);
}
Note* Note::root()
{
Note *r = this;
for (Note *n = parent_; n != nullptr; n = n->parent_)
r = n;
return r;
}
void Note::emitAddNoteRecursively(std::shared_ptr<Note> ¬e)
{
emit noteAdded(note);
for (auto &cn : note->subNotes_)
note->emitAddNoteRecursively(cn);
}
void Note::addNote(std::shared_ptr<Note> note)
{
note->parent_ = this;
subNotes_.push_back(note);
note->cleanUpFileSystem();
emitAddNoteRecursively(note);
}
std::shared_ptr<Note> Note::removeFromParent()
{
auto myNdx = parent_->findIndexOf(this);
auto ret = parent_->subNotes_[myNdx];
auto it = parent_->subNotes_.begin() + myNdx;
parent_->subNotes_.erase(it, it+1);
parent_->cleanUpFileSystem();
emit noteRemoved();
return ret;
}
void Note::adopt(const std::vector<std::weak_ptr<Note> > &list)
{
try{
std::set<QString> uniquenessCheck;
for (auto np : list){
auto n = np.lock();
if (!n)
continue;
QString name = n->name_;
if (exist(name) || uniquenessCheck.find(name) != uniquenessCheck.end()){
auto e = RecoverableException(tr(
"Note names have to be unique in the subnotes list. '%1' is not.\n").arg(name));
if (n->hierarchyDepth() > 1)
e.append(tr("It came from '%1'.\n").arg(n->makePathName()));
throw e;
}
uniquenessCheck.insert(name);
}
for (auto n : list)
if (!n.expired())
adopt_(n.lock());
}
catch(...){
error();
}
}
void Note::createSubnote(const QString &name)
{
if (root()->isZombie())
return;
try{
if (exist(name))
throw RecoverableException(
tr("Note '%1' already exist here.\n").arg(name));
ensureSubDirExist();
auto subNote = make_shared<Note>();
subNote->parent_ = this;
subNote->name_ = name;
auto txtPath = subNote->textPathname();
if (exists(txtPath))
throw RecoverableException(
tr("Filename '%1' already exist.\n").arg(QString::fromStdWString(txtPath.wstring())));
boost::filesystem::fstream out(
subNote->textPathname(), ios_base::out | ios_base::binary);
addNote(subNote);
cleanUpFileSystem();
}
catch(...){
warning(tr("Cant create note '%1'").arg(name));
}
}
void Note::deleteRecursively(const std::vector<std::weak_ptr<Note> > &list)
{
try{
vector<Note*> notes;
for (auto &n : list ){
if (!n.expired())
notes.push_back(n.lock().get());
}
std::sort(notes.begin(), notes.end(),[](const auto a, const auto b){
return a->hierarchyDepth() > b->hierarchyDepth();
});
for (auto n : notes)
n->deleteSelfRecursively();
}
catch(...){
error();
}
}
void Note::deleteSelfRecursively()
{
ASSERT(parent_ != nullptr); //not root
try{
remove_all(subNotesDir());
remove_all(attachDir());
remove_all(embedDir());
remove(textPathname());
removeFromParent();
parent_->cleanUpFileSystem();
}
catch(...){
throw Exception(tr("Can't delete note '%1':").arg(name_));
}
}
static const char * UrlRegexps[3] = {
"<(?:img|source)[^>]+src\\s*=\\s*\"([^\"]+)\"",
"<(?:img|source)[^>]+src\\s*=\\s*'([^']+)'",
"<(?:img|source)[^>]+src\\s*=\\s*[^'\"](\\S+)"
};
static
QString changeUrls(QString html, std::function<QString(const QString &)> mapper){
for (auto r : UrlRegexps){
QString newHtml;
int from = 0;
int to;
QRegExp reg(r);
int pos = 0;
while (true){
pos = reg.indexIn(html, pos);
if (pos < 0)
break;
// qDebug()<< reg.cap(0);
// qDebug()<< reg.cap(1);
pos += reg.cap(0).size();
auto cap = reg.cap(1);
QString newUrl = mapper(cap);
if (newUrl == cap)
continue;
to = reg.pos(1);
newHtml += html.midRef(from, to - from);
newHtml += newUrl;
from = to + cap.size();
}
if (from == 0)
continue;
newHtml += html.midRef(from, html.size());
html = move(newHtml);
}
return html;
}
static
set<QString> grabUrlsOfEmbeddedFiles(const QString &html)
{
set<QString> srcs;
changeUrls(html, [&](const QString &from)->QString {
srcs.insert(from);
return from;
});
return srcs;
}
path Note::generateEmbedFilename(const boost::filesystem::path &hint)
{
auto emDir = embedDir();
if (!exists(emDir))
create_directory(emDir);
auto simpleCase = emDir/hint.filename();
if (simpleCase.string().size() < 100 && !exists(simpleCase))
return simpleCase;
path ext = hint.extension();
path pref = hint.stem();
if (pref.size() > 100)
pref = path("");
if (ext.size() > 100)
ext = path("");
ui32 id = 0;
path retFilename;
do{
path fn = pref;
fn += path(to_string(id));
fn += ext;
retFilename = emDir / fn;
id++;
} while(exists(retFilename));
return retFilename;
}
static
QString urlEnc(const QString &s){
return QString(QUrl::toPercentEncoding(s, "./"));
}
void Note::downloaded(const QString &originalUrl, const QByteArray &content, const QString &error)
{
try{
urlsInDownload_.erase(originalUrl);
if (!error.isNull()){
throw RecoverableException(tr(
"Can't download embedded file for '%1'\n"
"url: %2\n"
"problem: %3").arg(name_).arg(originalUrl).arg(error));
}
QString embedUrl;
{
path embed = generateEmbedFilename(toPath(QUrl::fromPercentEncoding(originalUrl.toUtf8())));
using io = std::ios_base;
boost::filesystem::fstream out(embed, io::out | io::trunc | io::binary);
out.exceptions(io::failbit | io::badbit);
out.write(content.data(), content.size());
out.close();
embedUrl = urlEnc("./" + toQS(embed.parent_path().filename() / embed.filename()));
}
urlsPatch_[originalUrl] = embedUrl;
saveTxt(applyPatch(loadTxt()));
}
catch(...){
warning(tr("Problems while getting embedded content for '%1'\n").arg(name_));
}
}
QString Note::applyPatch(const QString &html)
{
return changeUrls(html, [&](const QString& from)->QString{
auto i = urlsPatch_.find(from);
if (i == urlsPatch_.end())
return from;
return i->second;
});
}
void Note::saveTxt(const QString &txt)
{
boost::filesystem::path outFilename;
try{
outFilename = textPathname();
outFilename += newFileExt;
using io = std::ios_base;
boost::filesystem::fstream out(outFilename, io::out | io::trunc | io::binary);
out.exceptions(io::failbit | io::badbit);
auto utf8txt = txt.toUtf8();
out.write(utf8txt.data(), utf8txt.size());
out.close();
rename(outFilename, textPathname());
}
catch(...){
warning(tr("Can't save note '%1' to file '%2'\n").arg(name_).arg(toQS(outFilename)));
}
}
QString Note::loadTxt()
{
try{
auto inFilename = textPathname();
if (!exists(inFilename))
return QString();
using io = std::ios_base;
boost::filesystem::fstream in(inFilename, io::in | io::binary);
in.exceptions(io::failbit | io::badbit);
auto inSize = file_size(inFilename);
if (inSize == static_cast<uintmax_t>(-1))
throw RecoverableException(
tr("Can't determine file size. Is it really a file?"));
QByteArray ba;
ba.resize(inSize);
in.read(ba.data(), ba.size());
in.close();
return QString::fromUtf8(ba);
}
catch(...){
warning(tr("Can't load file '%1'\n").arg(toQS(textPathname())));
}
return QString();
}
void Note::startEditing()
{
stopEditing();
QString html = loadTxt();
emit noteTextRdy(html, toQS(pathToNote()));
}
void Note::save(QString html)
{
try{
html = applyPatch(html);
set<path> validEmbeds;
auto urls = grabUrlsOfEmbeddedFiles(html);
for (auto u : urls){
if (u.startsWith(".")){
path em = toPath(QUrl::fromPercentEncoding(u.toUtf8()));
validEmbeds.insert(em.filename());
continue;
}
QString filePrefix = "file://";
if (u.startsWith(filePrefix)){
QString url = u;
url.remove(0, filePrefix.size());
url = QUrl::fromPercentEncoding(url.toUtf8());
auto srcPath = toPath(url);
path dstPath = generateEmbedFilename(srcPath);
boost::system::error_code err;
create_hard_link(srcPath, dstPath, err);
if (err)
copy_file(srcPath,dstPath);
validEmbeds.insert(dstPath.filename());
auto dstUrl = urlEnc("./" + toQS(dstPath.parent_path().filename() / dstPath.filename()));
urlsPatch_[u] = dstUrl;
continue;
}
if (urlsInDownload_.find(u) != urlsInDownload_.end())
continue;
auto dlr = app->downloader();
connect(dlr, &Downloader::finished, this, &Note::downloaded, Qt::UniqueConnection);
dlr->get(u);
urlsInDownload_.insert(u);
}
// just in case we have updated the patch by copeing local file
html = applyPatch(html);
saveTxt(html);
if (exists(embedDir())){
for (auto&& ef : directory_iterator(embedDir())){ // remove unused embeds
if (validEmbeds.find(ef.path().filename()) == validEmbeds.end())
remove(ef.path());
}
}
cleanUpFileSystem();
}
catch(...){
warning(tr("Can't save note '%1'.").arg(name_));
}
}
void Note::stopEditing()
{
urlsPatch_.clear();
}
void Note::getNotePlainTxt()
{
QString html = loadTxt();
QString txt;
txt.reserve(html.size());
bool skipTillEndOfTag = false;
for (auto it = html.begin(); it != html.end(); ++it){
if (skipTillEndOfTag){
if (*it == '>')
skipTillEndOfTag = false;
continue;
}
if (*it == '<'){
skipTillEndOfTag = true;
continue;
}
txt.append(*it);
}
txt = txt.simplified();
emit notePlainTextRdy(txt);
}
void Note::attach()
{
try{
if (!parent_)
return;
auto a = attachDir();
create_directory(a);
emit attachReady(toQS(a));
}
catch(...){
warning(tr("Can't create attachment directory."));
}
}
void Note::getNoteRelatedPaths()
{
vector<QString> lst;
auto pref = QString("file://");
auto text = textPathname();
if (exists(text))
lst.emplace_back(pref + urlEnc(toQS(text)));
auto attach = attachDir();
if (exists(attach))
lst.emplace_back(pref + urlEnc(toQS(attach)));
auto embed =embedDir();
if (exists(embed))
lst.emplace_back(pref + urlEnc(toQS(embed)));
emit pathsReady(lst);
}
path Note::pathToNote() const
{
if (parent_)
return parent_->subNotesDir();
else
return path(name_.toUtf8());
}
boost::filesystem::path Note::attachDir() const
{
ASSERT(parent_ != nullptr); // root has no attach
return pathToNote() / encodeToFilename(name_+attachExt);
}
path Note::embedDir() const
{
ASSERT(parent_ != nullptr); // root has no embed
return pathToNote() / encodeToFilename(name_+embedExt);
}
boost::filesystem::path Note::subNotesDir() const
{
if (parent_ == nullptr)
return pathToNote();
return pathToNote() / encodeToFilename(name_);
}
boost::filesystem::path Note::textPathname() const
{
ASSERT(parent_ != nullptr); // root has no text
return pathToNote() / encodeToFilename(name_+textExt);
}
size_t Note::findIndexOf(const Note *n) const
{
for (size_t i = 0; i < subNotes_.size(); ++i){
if (subNotes_[i].get() == n)
return i;
}
ASSERT(false);
return subNotes_.size(); // make caller crash
}
bool Note::exist(const QString &name)
{
for (auto &sub : subNotes_)
if (sub->name_ == name)
return true;
return false;
}
QString Note::makePathName(const QString separator) const
{
std::stack<const Note*> stack;
for (const Note *n = parent_; n != nullptr; n = n->parent_)
stack.push(n);
stack.pop();
QString ret;
while (!stack.empty()){
ret += stack.top()->name_;
stack.pop();
if (!stack.empty())
ret += separator;
}
return ret;
}
int Note::hierarchyDepth() const
{
int depth = 0;
for (const Note *n = parent_; n != nullptr; n = n->parent_)
depth++;
return depth;
}
void Note::changeName(const QString &name)
{
ASSERT(parent_ != nullptr);
try{
if (name == name_)
return;
if (parent_->exist(name)){
throw RecoverableException(
QCoreApplication::translate(
"notes renaming",
"'%1' already exist there.\n").arg(name));
}
if (exists(embedDir())){
QString html = loadTxt();
QString oldUrlPrefix = urlEnc("./" + toQS(encodeToFilename(name_ + embedExt)));
auto oldPrefLen = oldUrlPrefix.size();
QString newUrlPrefix = urlEnc("./" + toQS(encodeToFilename(name + embedExt)));
html = changeUrls(html, [&](const QString& from)->QString{
if (!from.startsWith(oldUrlPrefix))
return from;
QString ret = from;
ret.remove(0, oldPrefLen).prepend(newUrlPrefix);
return ret;
});
saveTxt(html);
}
move(pathToNote(), encodeToFilename(name));
name_ = name;
emit nameChanged(name);
}
catch(...){
error();
}
}
| 24.002677 | 115 | 0.649805 | dsvi |
2069353ea4fa81075506c54b491868cdc1ece792 | 3,192 | cpp | C++ | data_structure/splay/RANK_TREE_SPLAY.cpp | searchstar2017/acmtool | 03392b8909a3d45f10c2711ca4ad9ba69f64a481 | [
"MIT"
] | null | null | null | data_structure/splay/RANK_TREE_SPLAY.cpp | searchstar2017/acmtool | 03392b8909a3d45f10c2711ca4ad9ba69f64a481 | [
"MIT"
] | null | null | null | data_structure/splay/RANK_TREE_SPLAY.cpp | searchstar2017/acmtool | 03392b8909a3d45f10c2711ca4ad9ba69f64a481 | [
"MIT"
] | null | null | null | template<typename T>
struct SPLAY {
//0 is invalid
int c[MAXN][2], fa[MAXN], cnt[MAXN], siz[MAXN], tot, root;
T keys[MAXN];
#define ls(rt) c[rt][0]
#define rs(rt) c[rt][1]
void Init() {
root = tot = 0;
}
bool Side(int rt) {
return rt == rc(fa[rt]);
}
void PushUp(int rt) {
siz[rt] = cnt[rt];
if (lc(rt))
siz[rt] += siz[lc(rt)];
if (rc(rt))
siz[rt] += siz[rc(rt)];
}
void Init(int rt, const T& key) {
lc(rt) = rc(rt) = fa[rt] = 0;
siz[rt] = cnt[rt] = 1;
keys[rt] = key;
}
void SetSon(int x, int f, int s) {
if (f) c[f][s] = x;
if (x) fa[x] = f;
}
//Will update siz[now] and siz[fa[now]]
void RotateUp(int now) {
int f = fa[now];
bool side = Side(now);
SetSon(c[now][!side], f, side);
SetSon(now, fa[f], Side(f));
SetSon(f, now, !side);
PushUp(f);
PushUp(now);
if (!fa[now])
root = now;
}
//Require that cnt[now] is up to date
void Splay(int now, int to = 0) {
if (!now) return;
for (int f = fa[now]; f != to; f = fa[now]) {
if (fa[f] != to)
RotateUp(Side(now) == Side(f) ? f : now);
RotateUp(now);
}
}
//The new node will be the root
void Insert(const T& key) {
if (!root) {
Init(root = ++tot, key);
} else {
int now = root, f;
while (1) {
if (!now) {
Init(now = ++tot, key);
fa[now] = f;
c[f][keys[f] < key] = now;
break;
} else if (keys[now] == key) {
++cnt[now];
break;
}
f = now;
now = c[now][keys[now] < key];
}
Splay(now);
}
}
//The target node will be the root
int find(const T& key) {
int now = root;
while (now && keys[now] != key)
now = c[now][keys[now] < key];
Splay(now);
return now;
}
int FindPreOrNext(int now, bool nex) const {
if (!c[now][nex]) return 0;
nex = !nex;
for (now = c[now][!nex]; c[now][nex]; now = c[now][nex]);
return now;
}
void DelRoot() {
int now = FindPreOrNext(root, false);
if (!now) {
root = rs(root);
fa[root] = 0;
} else {
Splay(now);
SetSon(rs(rs(root)), root, 1);
PushUp(root);
}
//No need to free the target node
}
void Del(const T& key) {
int now = find(key);
if (!now) return;
if (cnt[root] > 1) {
--cnt[root];
--siz[root];
} else if (!lc(root) || !rc(root)) {
root = lc(root) + rc(root);
fa[root] = 0; //Even if root == 0, it does no harm
//No need to free the target node
} else {
DelRoot();
}
}
T QueryKth(int k) {
int rt = root;
while (rt) {
if (siz[c[rt][0]] < k && siz[c[rt][0]] + cnt[rt] >= k) {
return keys[rt];
} else if (siz[c[rt][0]] >= k) {
rt = c[rt][0];
} else {
k -= siz[c[rt][0]] + cnt[rt];
rt = c[rt][1];
}
}
return -1;
}
int QuerySmaller(const T& key) {
int now = find(key);
bool flag = false;
if (!now) {
Insert(key);
flag = true;
}
int ans = lc(root) ? siz[lc(root)] : 0;
if (flag) DelRoot();
return ans;
}
T QueryPreOrNext(const T& key, bool nex) {
int now = find(key);
bool flag = false;
if (!now) {
Insert(key);
now = root;
flag = true;
}
if (!c[now][nex]) {
if (flag)
Del(key);
return -1;
}
now = FindPreOrNext(now, nex);
if (flag)
Del(key);
return now >= 0 ? keys[now] : -1;
}
};
| 19.703704 | 59 | 0.515038 | searchstar2017 |
2069a4e15b5fb0b5fe3c1a28e8f6e453111a30f4 | 1,563 | hpp | C++ | src/res/Prefab/ComponentParsing/ParseTransformComponent.hpp | awwdev/MiniSTL | 218998f6109a2a42c0017b4255bec48a235998c3 | [
"MIT"
] | 5 | 2021-02-10T19:14:32.000Z | 2021-11-19T13:29:55.000Z | src/res/Prefab/ComponentParsing/ParseTransformComponent.hpp | awwdev/MiniSTL | 218998f6109a2a42c0017b4255bec48a235998c3 | [
"MIT"
] | 41 | 2020-05-16T09:56:45.000Z | 2020-07-05T15:14:33.000Z | src/res/Prefab/ComponentParsing/ParseTransformComponent.hpp | awwdev/MiniSTL | 218998f6109a2a42c0017b4255bec48a235998c3 | [
"MIT"
] | 2 | 2021-07-21T22:21:41.000Z | 2021-09-06T19:25:11.000Z | //https://github.com/awwdev
#pragma once
#include "ecs/Components/TransformComponent.hpp"
#include "res/Prefab/ComponentParsing/ComponentMember.hpp"
namespace rpg::res {
inline auto ParseTransformComponent(ComponentMemberPairs const& pairs)
{
ecs::TransformComponent transformComponent {};
FOR_ARRAY(pairs, i)
{
auto const [key, val, componentDataEnum] = pairs[i].get_data();
switch(componentDataEnum)
{
case ComponentMemberEnum::Children:
{
/*
const auto values = ValStrToValArray<3, 100>(val);
dbg::Assert(!values.Empty(), "values are empty");
FOR_ARRAY(values, i){
auto const prefabEnum = res::PREFAB_STR_TO_ENUM.GetOptional(values[i].Data());
dbg::Assert(prefabEnum, "child prefab enum wrong");
transformComponent.children.AppendElement((ID) *prefabEnum);
}
*/
}
break;
case ComponentMemberEnum::Scale:
{
/*
const auto values = ValStrToValArray<3, 10>(val);
dbg::Assert(!values.Empty(), "values are empty");
FOR_ARRAY(values, i){
transformComponent.scale[0][i] = std::atof(values[i].Data());
}
*/
}
break;
default: dbg::Assert(false, "component data enum missing / wrong");
}
}
return transformComponent;
}
}//ns | 31.897959 | 98 | 0.535509 | awwdev |
206b9a298595565ea89c60d9dd381c847a5f16e2 | 2,309 | cpp | C++ | ComTest/main.cpp | iclosure/com422 | 7279f625ad9dd2e6c374e61608074fdaf206f326 | [
"MIT"
] | 1 | 2018-09-20T07:45:43.000Z | 2018-09-20T07:45:43.000Z | ComTest/main.cpp | iclosure/com422 | 7279f625ad9dd2e6c374e61608074fdaf206f326 | [
"MIT"
] | null | null | null | ComTest/main.cpp | iclosure/com422 | 7279f625ad9dd2e6c374e61608074fdaf206f326 | [
"MIT"
] | null | null | null | // ComTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
//#include "test_comapi_load.h"
//#include "test_comapi_speed.h"
//#include "test_comm.h"
#include "moxa/pcomm.h"
#include "serialport/serialport.h"
#pragma comment(lib, "moxa/pcomm")
#define HR_DEBUG_PRINT_PREFIX_MAX_SIZE 80 // max size of prefix string
// Global variables
static TCHAR _g_stringPrefix[HR_DEBUG_PRINT_PREFIX_MAX_SIZE] = { 0 };
BOOL __cdecl HR_PRINT_SET_PREFIX(__in LPCTSTR Prefix)
{
errno_t result = _tcscpy_s(_g_stringPrefix, HR_DEBUG_PRINT_PREFIX_MAX_SIZE, Prefix);
return (result == 0) ? TRUE : FALSE;
}
BOOL __cdecl HR_PRINT_GET_PREFIX(__out LPTSTR Prefix, __in size_t size)
{
errno_t result = _tcsncpy_s(Prefix, size, _g_stringPrefix, HR_DEBUG_PRINT_PREFIX_MAX_SIZE);
return (result == 0) ? TRUE : FALSE;
}
ULONG __cdecl HrDbgPrint(__in LPCTSTR Format, ...)
{
va_list ap;
ULONG n;
TCHAR szData[356] = { 0 };
lstrcat(szData, _g_stringPrefix);
va_start(ap, Format);
n = _vsntprintf_s(&szData[lstrlen(_g_stringPrefix)], 256, 256, Format, ap);
va_end(ap);
OutputDebugString(szData);
return n;
}
ULONG __cdecl HR_PRINT_METHOD_BEGIN(__in LPCTSTR MethodName)
{
return HrDbgPrint(_T("-> %s\n"), MethodName);
}
ULONG __cdecl HR_PRINT_METHOD_END(__in LPCTSTR MethodName)
{
return HrDbgPrint(_T("<- %s\n"), MethodName);
}
SerialPort serialPort;
INT WriteBytes = 0;
int ReadBytes = 0;
bool flag = true;
#include <Windows.h>
DWORD WINAPI ReadProc(void*)
{
char buf[1024];
while (flag)
{
ReadBytes += serialPort.read(buf, 1024);
}
return 0;
}
DWORD WINAPI WriteProc(void*)
{
char buf[1024];
while (flag)
{
WriteBytes += serialPort.write(buf, 1024);
}
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
HR_PRINT_SET_PREFIX(_T("#> TEST"));
// test serial port
//test_comm();
// test com api load
//test_comapi_load();
// test com api speed
//test_comapi_speed();
serialPort.set(115200, 8, "None", 1);
CreateThread(NULL, 0, ReadProc, NULL, 0, NULL);
CreateThread(NULL, 0, WriteProc, NULL, 0, NULL);
while (1)
{
int c = getchar();
if (c == 'p') {
printf("RX:%d, TX:%d\n", ReadBytes, WriteBytes);
}
else if (c == 'q') {
flag = false;
break;
}
}
system("pause");
return 0;
} | 18.181102 | 92 | 0.686011 | iclosure |
206c0924369f7f61fba6d7cff452682626bf316d | 2,353 | cpp | C++ | RenamerGUI/querylineedit.cpp | eighttails/bRenamer | 9cc56c356907ec54faf8ad09d84a7afcc26800ea | [
"BSD-2-Clause"
] | null | null | null | RenamerGUI/querylineedit.cpp | eighttails/bRenamer | 9cc56c356907ec54faf8ad09d84a7afcc26800ea | [
"BSD-2-Clause"
] | null | null | null | RenamerGUI/querylineedit.cpp | eighttails/bRenamer | 9cc56c356907ec54faf8ad09d84a7afcc26800ea | [
"BSD-2-Clause"
] | null | null | null | /*--------------------------------------------------------------------
Copyright (c) 2011, Tadahito Yao
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------*/
#include <QMenu>
#include <QContextMenuEvent>
#include "querylineedit.h"
#include "mainwindow.h"
#include "query.h"
QueryLineEdit::QueryLineEdit(QWidget *parent)
: QLineEdit(parent)
{
}
void QueryLineEdit::insertAssist()
{
// 正規表現の入力補助
QAction* action = qobject_cast<QAction*>(sender());
QString expression = action->data().toString();
this->insert(expression);
}
void QueryLineEdit::contextMenuEvent(QContextMenuEvent *event)
{
QSharedPointer<QMenu> menu(createStandardContextMenu());
menu->addSeparator();
QMenu* assistMenu = menu->addMenu("入力補助");
MainWindow* window = qobject_cast<MainWindow*>(this->window());
foreach(auto assistant, window->query()->queryAssistants()){
QAction* action = assistMenu->addAction(assistant->description());
action->setData(assistant->expression());
QObject::connect(action, SIGNAL(triggered()), this, SLOT(insertAssist()));
}
menu->exec(event->globalPos());
}
| 37.951613 | 94 | 0.734807 | eighttails |
206e2de35f302230e3bf45a92921663d61dcfb6d | 51,134 | cpp | C++ | Applications/SEGUE/qtcolortriangle.cpp | jcfr/RobartsVTK | d711c99b9c5b8a53afd23ee10d84f77a24565a3f | [
"MIT"
] | 5 | 2016-11-17T01:29:25.000Z | 2021-11-19T05:24:10.000Z | Applications/SEGUE/qtcolortriangle.cpp | jcfr/RobartsVTK | d711c99b9c5b8a53afd23ee10d84f77a24565a3f | [
"MIT"
] | 2 | 2017-07-20T20:32:24.000Z | 2018-03-09T21:53:15.000Z | Applications/SEGUE/qtcolortriangle.cpp | jcfr/RobartsVTK | d711c99b9c5b8a53afd23ee10d84f77a24565a3f | [
"MIT"
] | 5 | 2016-12-19T20:40:34.000Z | 2021-08-18T07:59:30.000Z | /****************************************************************************
**
** This file is part of a Qt Solutions component.
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information (qt-info@nokia.com)
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third
** Party Software they are using.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
****************************************************************************/
#include "qtcolortriangle.h"
#include <QEvent>
#include <QMap>
#include <QVarLengthArray>
#include <QConicalGradient>
#include <QFrame>
#include <QImage>
#include <QKeyEvent>
#include <QLayout>
#include <QMouseEvent>
#include <QPainter>
#include <QPainterPath>
#include <QPixmap>
#include <QResizeEvent>
#include <QToolTip>
#include <QVBoxLayout>
#include <math.h>
/*! \class QtColorTriangle
\brief The QtColorTriangle class provides a triangular color
selection widget.
This widget uses the HSV color model, and is therefore useful for
selecting colors by eye.
The triangle in the center of the widget is used for selecting
saturation and value, and the surrounding circle is used for
selecting hue.
Use setColor() and color() to set and get the current color.
\img colortriangle.png
*/
/*! \fn QtColorTriangle::colorChanged(const QColor &color)
Whenever the color triangles color changes this signal is emitted
with the new \a color.
*/
const double PI = 3.14159265358979323846264338327950288419717;
const double TWOPI = 2.0*PI;
/*
Used to store color values in the range 0..255 as doubles.
*/
struct DoubleColor
{
double r, g, b;
DoubleColor() : r(0.0), g(0.0), b(0.0) {}
DoubleColor(double red, double green, double blue) : r(red), g(green), b(blue) {}
DoubleColor(const DoubleColor &c) : r(c.r), g(c.g), b(c.b) {}
};
/*
Used to store pairs of DoubleColor and DoublePoint in one structure.
*/
struct Vertex {
DoubleColor color;
QPointF point;
Vertex(const DoubleColor &c, const QPointF &p) : color(c), point(p) {}
Vertex(const QColor &c, const QPointF &p)
: color(DoubleColor((double) c.red(), (double) c.green(),
(double) c.blue())), point(p) {}
};
/*! \internal
Swaps the Vertex at *a with the one at *b.
*/
static void swap(Vertex **a, Vertex **b)
{
Vertex *tmp = *a;
*a = *b;
*b = tmp;
}
/*!
Constructs a color triangle widget with the given \a parent.
*/
QtColorTriangle::QtColorTriangle(QWidget *parent)
: QWidget(parent), bg(sizeHint(), QImage::Format_RGB32), selMode(Idle)
{
setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
setFocusPolicy(Qt::StrongFocus);
mustGenerateBackground = true;
QColor tmp;
tmp.setHsv(76, 184, 206);
setColor(tmp);
}
/*!
Destructs the color triangle.
*/
QtColorTriangle::~QtColorTriangle()
{
}
/*!
\internal
Generates the first background image.
*/
void QtColorTriangle::polish()
{
outerRadius = (contentsRect().width() - 1) / 2;
if ((contentsRect().height() - 1) / 2 < outerRadius)
outerRadius = (contentsRect().height() - 1) / 2;
penWidth = (int) floor(outerRadius / 50.0);
ellipseSize = (int) floor(outerRadius / 12.5);
double cx = (double) contentsRect().center().x();
double cy = (double) contentsRect().center().y();
pa = QPointF(cx + (cos(a) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(a) * (outerRadius - (outerRadius / 5.0))));
pb = QPointF(cx + (cos(b) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(b) * (outerRadius - (outerRadius / 5.0))));
pc = QPointF(cx + (cos(c) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(c) * (outerRadius - (outerRadius / 5.0))));
pd = QPointF(cx + (cos(a) * (outerRadius - (outerRadius / 10.0))),
cy - (sin(a) * (outerRadius - (outerRadius / 10.0))));
// Find the current position of the selector
selectorPos = pointFromColor(curColor);
update();
}
/*! \reimp
*/
QSize QtColorTriangle::sizeHint() const
{
return QSize(100, 100);
}
/*!
Forces the triangle widget to always be square. Returns the value
\a w.
*/
int QtColorTriangle::heightForWidth(int w) const
{
return w;
}
/*!
\internal
Generates a new static background image. This function is called
initially, and in resizeEvent.
*/
void QtColorTriangle::genBackground()
{
// Find the inner radius of the hue donut.
double innerRadius = outerRadius - outerRadius / 5;
// Create an image of the same size as the contents rect.
bg = QImage(contentsRect().size(), QImage::Format_RGB32);
QPainter p(&bg);
p.setRenderHint(QPainter::Antialiasing);
p.fillRect(bg.rect(), palette().mid());
QConicalGradient gradient(bg.rect().center(), 90);
QColor color;
for (double i = 0; i <= 1.0; i += 0.1) {
#if QT_VERSION < 0x040100
color.setHsv(int(i * 360.0), 255, 255);
#else
color.setHsv(int(360.0 - (i * 360.0)), 255, 255);
#endif
gradient.setColorAt(i, color);
}
QRectF innerRadiusRect(bg.rect().center().x() - innerRadius, bg.rect().center().y() - innerRadius,
innerRadius * 2 + 1, innerRadius * 2 + 1);
QRectF outerRadiusRect(bg.rect().center().x() - outerRadius, bg.rect().center().y() - outerRadius,
outerRadius * 2 + 1, outerRadius * 2 + 1);
QPainterPath path;
path.addEllipse(innerRadiusRect);
path.addEllipse(outerRadiusRect);
p.save();
p.setClipPath(path);
p.fillRect(bg.rect(), gradient);
p.restore();
double penThickness = bg.width() / 400.0;
for (int f = 0; f <= 5760; f += 20) {
int value = int((0.5 + cos(((f - 1800) / 5760.0) * TWOPI) / 2) * 255.0);
color.setHsv(int((f / 5760.0) * 360.0), 128 + (255 - value)/2, 255 - (255 - value)/4);
p.setPen(QPen(color, penThickness));
p.drawArc(innerRadiusRect, 1440 - f, 20);
color.setHsv(int((f / 5760.0) * 360.0), 128 + value/2, 255 - value/4);
p.setPen(QPen(color, penThickness));
p.drawArc(outerRadiusRect, 2880 - 1440 - f, 20);
}
return;
}
/*!
\internal
Selects new hue or saturation/value values, depending on where the
mouse button was pressed initially.
*/
void QtColorTriangle::mouseMoveEvent(QMouseEvent *e)
{
if ((e->buttons() & Qt::LeftButton) == 0)
return;
QPointF depos((double) e->pos().x(), (double) e->pos().y());
bool newColor = false;
if (selMode == SelectingHue) {
// If selecting hue, find the new angles for the points a,b,c
// of the triangle. The following update() will then redraw
// the triangle.
a = angleAt(depos, contentsRect());
b = a + TWOPI / 3.0;
c = b + TWOPI / 3.0;
if (b > TWOPI) b -= TWOPI;
if (c > TWOPI) c -= TWOPI;
double am = a - PI/2;
if (am < 0) am += TWOPI;
curHue = 360 - (int) (((am) * 360.0) / TWOPI);
int h,s,v;
curColor.getHsv(&h, &s, &v);
if (curHue != h) {
newColor = true;
curColor.setHsv(curHue, s, v);
}
double cx = (double) contentsRect().center().x();
double cy = (double) contentsRect().center().y();
pa = QPointF(cx + (cos(a) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(a) * (outerRadius - (outerRadius / 5.0))));
pb = QPointF(cx + (cos(b) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(b) * (outerRadius - (outerRadius / 5.0))));
pc = QPointF(cx + (cos(c) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(c) * (outerRadius - (outerRadius / 5.0))));
pd = QPointF(cx + (cos(a) * (outerRadius - (outerRadius / 10.0))),
cy - (sin(a) * (outerRadius - (outerRadius / 10.0))));
selectorPos = pointFromColor(curColor);
} else {
Vertex aa(Qt::black, pa);
Vertex bb(Qt::black, pb);
Vertex cc(Qt::black, pc);
Vertex *p1 = &aa;
Vertex *p2 = &bb;
Vertex *p3 = &cc;
if (p1->point.y() > p2->point.y()) swap(&p1, &p2);
if (p1->point.y() > p3->point.y()) swap(&p1, &p3);
if (p2->point.y() > p3->point.y()) swap(&p2, &p3);
selectorPos = movePointToTriangle(depos.x(), depos.y(), aa, bb, cc);
QColor col = colorFromPoint(selectorPos);
if (col != curColor) {
// Ensure that hue does not change when selecting
// saturation and value.
int h,s,v;
col.getHsv(&h, &s, &v);
curColor.setHsv(curHue, s, v);
newColor = true;
}
}
if (newColor)
emit colorChanged(curColor);
update();
}
/*!
\internal
When the left mouse button is pressed, this function determines
what part of the color triangle the cursor is, and from that it
initiates either selecting the hue (outside the triangle's area)
or the saturation/value (inside the triangle's area).
*/
void QtColorTriangle::mousePressEvent(QMouseEvent *e)
{
// Only respond to the left mouse button.
if (e->button() != Qt::LeftButton)
return;
QPointF depos((double) e->pos().x(), (double) e->pos().y());
double rad = radiusAt(depos, contentsRect());
bool newColor = false;
// As in mouseMoveEvent, either find the a,b,c angles or the
// radian position of the selector, then order an update.
if (rad > (outerRadius - (outerRadius / 5))) {
selMode = SelectingHue;
a = angleAt(depos, contentsRect());
b = a + TWOPI / 3.0;
c = b + TWOPI / 3.0;
if (b > TWOPI) b -= TWOPI;
if (c > TWOPI) c -= TWOPI;
double am = a - PI/2;
if (am < 0) am += TWOPI;
curHue = 360 - (int) ((am * 360.0) / TWOPI);
int h,s,v;
curColor.getHsv(&h, &s, &v);
if (h != curHue) {
newColor = true;
curColor.setHsv(curHue, s, v);
}
double cx = (double) contentsRect().center().x();
double cy = (double) contentsRect().center().y();
pa = QPointF(cx + (cos(a) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(a) * (outerRadius - (outerRadius / 5.0))));
pb = QPointF(cx + (cos(b) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(b) * (outerRadius - (outerRadius / 5.0))));
pc = QPointF(cx + (cos(c) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(c) * (outerRadius - (outerRadius / 5.0))));
pd = QPointF(cx + (cos(a) * (outerRadius - (outerRadius / 10.0))),
cy - (sin(a) * (outerRadius - (outerRadius / 10.0))));
selectorPos = pointFromColor(curColor);
emit colorChanged(curColor);
} else {
selMode = SelectingSatValue;
Vertex aa(Qt::black, pa);
Vertex bb(Qt::black, pb);
Vertex cc(Qt::black, pc);
Vertex *p1 = &aa;
Vertex *p2 = &bb;
Vertex *p3 = &cc;
if (p1->point.y() > p2->point.y()) swap(&p1, &p2);
if (p1->point.y() > p3->point.y()) swap(&p1, &p3);
if (p2->point.y() > p3->point.y()) swap(&p2, &p3);
selectorPos = movePointToTriangle(depos.x(), depos.y(), aa, bb, cc);
QColor col = colorFromPoint(selectorPos);
if (col != curColor) {
curColor = col;
newColor = true;
}
}
if (newColor)
emit colorChanged(curColor);
update();
}
/*!
\internal
Stops selecting of colors with the mouse.
*/
void QtColorTriangle::mouseReleaseEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton)
selMode = Idle;
}
/*!
\internal
*/
void QtColorTriangle::keyPressEvent(QKeyEvent *e)
{
switch (e->key()) {
case Qt::Key_Left: {
--curHue;
if (curHue < 0) curHue += 360;
int h,s,v;
curColor.getHsv(&h, &s, &v);
QColor tmp;
tmp.setHsv(curHue, s, v);
setColor(tmp);
}
break;
case Qt::Key_Right: {
++curHue;
if (curHue > 359) curHue -= 360;
int h,s,v;
curColor.getHsv(&h, &s, &v);
QColor tmp;
tmp.setHsv(curHue, s, v);
setColor(tmp);
}
break;
case Qt::Key_Up: {
int h,s,v;
curColor.getHsv(&h, &s, &v);
QColor tmp;
if (e->modifiers() & Qt::ShiftModifier) {
if (s > 5) s -= 5;
else s = 0;
} else {
if (v > 5) v -= 5;
else v = 0;
}
tmp.setHsv(curHue, s, v);
setColor(tmp);
}
break;
case Qt::Key_Down: {
int h,s,v;
curColor.getHsv(&h, &s, &v);
QColor tmp;
if (e->modifiers() & Qt::ShiftModifier) {
if (s < 250) s += 5;
else s = 255;
} else {
if (v < 250) v += 5;
else v = 255;
}
tmp.setHsv(curHue, s, v);
setColor(tmp);
}
break;
};
}
/*!
\internal
Regenerates the background image and sends an update.
*/
void QtColorTriangle::resizeEvent(QResizeEvent *)
{
outerRadius = (contentsRect().width() - 1) / 2;
if ((contentsRect().height() - 1) / 2 < outerRadius)
outerRadius = (contentsRect().height() - 1) / 2;
penWidth = (int) floor(outerRadius / 50.0);
ellipseSize = (int) floor(outerRadius / 12.5);
double cx = (double) contentsRect().center().x();
double cy = (double) contentsRect().center().y();
pa = QPointF(cx + (cos(a) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(a) * (outerRadius - (outerRadius / 5.0))));
pb = QPointF(cx + (cos(b) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(b) * (outerRadius - (outerRadius / 5.0))));
pc = QPointF(cx + (cos(c) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(c) * (outerRadius - (outerRadius / 5.0))));
pd = QPointF(cx + (cos(a) * (outerRadius - (outerRadius / 10.0))),
cy - (sin(a) * (outerRadius - (outerRadius / 10.0))));
// Find the current position of the selector
selectorPos = pointFromColor(curColor);
mustGenerateBackground = true;
update();
}
/*! \reimp
First copies a background image of the hue donut and its
background color onto the frame, then draws the color triangle,
and finally the selectors.
*/
void QtColorTriangle::paintEvent(QPaintEvent *e)
{
QPainter p(this);
if (e->rect().intersects(contentsRect()))
p.setClipRegion(e->region().intersected(contentsRect()));
if (mustGenerateBackground) {
genBackground();
mustGenerateBackground = false;
}
// Blit the static generated background with the hue gradient onto
// the double buffer.
QImage buf = bg.copy();
// Draw the trigon
int h,s,v;
curColor.getHsv(&h, &s, &v);
// Find the color with only the hue, and max value and saturation
QColor hueColor;
hueColor.setHsv(curHue, 255, 255);
// Draw the triangle
drawTrigon(&buf, pa, pb, pc, hueColor);
// Slow step: convert the image to a pixmap
QPixmap pix = QPixmap::fromImage(buf);
QPainter painter(&pix);
painter.setRenderHint(QPainter::Antialiasing);
// Draw an outline of the triangle
QColor halfAlpha(0, 0, 0, 128);
painter.setPen(QPen(halfAlpha, 0));
painter.drawLine(pa, pb);
painter.drawLine(pb, pc);
painter.drawLine(pc, pa);
int ri, gi, bi;
hueColor.getRgb(&ri, &gi, &bi);
if ((ri * 30) + (gi * 59) + (bi * 11) > 12800)
painter.setPen(QPen(Qt::black, penWidth));
else
painter.setPen(QPen(Qt::white, penWidth));
painter.drawEllipse((int) (pd.x() - ellipseSize / 2.0),
(int) (pd.y() - ellipseSize / 2.0),
ellipseSize, ellipseSize);
curColor.getRgb(&ri, &gi, &bi);
// Find a color for painting the selector based on the brightness
// value of the color.
if ((ri * 30) + (gi * 59) + (bi * 11) > 12800)
painter.setPen(QPen(Qt::black, penWidth));
else
painter.setPen(QPen(Qt::white, penWidth));
// Draw the selector ellipse.
painter.drawEllipse(QRectF(selectorPos.x() - ellipseSize / 2.0,
selectorPos.y() - ellipseSize / 2.0,
ellipseSize + 0.5, ellipseSize + 0.5));
// Blit
p.drawPixmap(contentsRect().topLeft(), pix);
}
/*! \internal
Draws a trigon (polygon with three corners \a pa, \a pb and \a pc
and three edges), using \a painter.
Fills the trigon with a gradient, where the \a pa point has the
color \a color, \a pb is black and \a bc is white. Bilinear
gradient.
*/
void QtColorTriangle::drawTrigon(QImage *buf, const QPointF &pa,
const QPointF &pb, const QPointF &pc,
const QColor &color)
{
// Create three Vertex objects. A Vertex contains a double-point
// coordinate and a color.
// pa is the tip of the arrow
// pb is the black corner
// pc is the white corner
Vertex aa(color, pa);
Vertex bb(Qt::black, pb);
Vertex cc(Qt::white, pc);
// Sort. Make p1 above p2, which is above p3 (using y coordinate).
// Bubble sorting is fastest here.
Vertex *p1 = &aa;
Vertex *p2 = &bb;
Vertex *p3 = &cc;
if (p1->point.y() > p2->point.y()) swap(&p1, &p2);
if (p1->point.y() > p3->point.y()) swap(&p1, &p3);
if (p2->point.y() > p3->point.y()) swap(&p2, &p3);
// All the three y deltas are >= 0
double p1p2ydist = p2->point.y() - p1->point.y();
double p1p3ydist = p3->point.y() - p1->point.y();
double p2p3ydist = p3->point.y() - p2->point.y();
double p1p2xdist = p2->point.x() - p1->point.x();
double p1p3xdist = p3->point.x() - p1->point.x();
double p2p3xdist = p3->point.x() - p2->point.x();
// The first x delta decides wether we have a lefty or a righty
// trigon.
bool lefty = p1p2xdist < 0;
// Left and right colors and X values. The key in this map is the
// y values. Our goal is to fill these structures with all the
// information needed to do a single pass top-to-bottom,
// left-to-right drawing of the trigon.
QVarLengthArray<DoubleColor, 2000> leftColors;
QVarLengthArray<DoubleColor, 2000> rightColors;
QVarLengthArray<double, 2000> leftX;
QVarLengthArray<double, 2000> rightX;
leftColors.resize(int(floor(p3->point.y() + 1)));
rightColors.resize(int(floor(p3->point.y() + 1)));
leftX.resize(int(floor(p3->point.y() + 1)));
rightX.resize(int(floor(p3->point.y() + 1)));
// Scan longy - find all left and right colors and X-values for
// the tallest edge (p1-p3).
DoubleColor source;
DoubleColor dest;
double r, g, b;
double rdelta, gdelta, bdelta;
double x;
double xdelta;
int y1, y2;
// Initialize with known values
x = p1->point.x();
source = p1->color;
dest = p3->color;
r = source.r;
g = source.g;
b = source.b;
y1 = (int) floor(p1->point.y());
y2 = (int) floor(p3->point.y());
// Find slopes (notice that if the y dists are 0, we don't care
// about the slopes)
xdelta = p1p3ydist == 0.0 ? 0.0 : p1p3xdist / p1p3ydist;
rdelta = p1p3ydist == 0.0 ? 0.0 : (dest.r - r) / p1p3ydist;
gdelta = p1p3ydist == 0.0 ? 0.0 : (dest.g - g) / p1p3ydist;
bdelta = p1p3ydist == 0.0 ? 0.0 : (dest.b - b) / p1p3ydist;
// Calculate gradients using linear approximation
int y;
for (y = y1; y < y2; ++y) {
if (lefty) {
rightColors[y] = DoubleColor(r, g, b);
rightX[y] = x;
} else {
leftColors[y] = DoubleColor(r, g, b);
leftX[y] = x;
}
r += rdelta;
g += gdelta;
b += bdelta;
x += xdelta;
}
// Scan top shorty - find all left and right colors and x-values
// for the topmost of the two not-tallest short edges.
x = p1->point.x();
source = p1->color;
dest = p2->color;
r = source.r;
g = source.g;
b = source.b;
y1 = (int) floor(p1->point.y());
y2 = (int) floor(p2->point.y());
// Find slopes (notice that if the y dists are 0, we don't care
// about the slopes)
xdelta = p1p2ydist == 0.0 ? 0.0 : p1p2xdist / p1p2ydist;
rdelta = p1p2ydist == 0.0 ? 0.0 : (dest.r - r) / p1p2ydist;
gdelta = p1p2ydist == 0.0 ? 0.0 : (dest.g - g) / p1p2ydist;
bdelta = p1p2ydist == 0.0 ? 0.0 : (dest.b - b) / p1p2ydist;
// Calculate gradients using linear approximation
for (y = y1; y < y2; ++y) {
if (lefty) {
leftColors[y] = DoubleColor(r, g, b);
leftX[y] = x;
} else {
rightColors[y] = DoubleColor(r, g, b);
rightX[y] = x;
}
r += rdelta;
g += gdelta;
b += bdelta;
x += xdelta;
}
// Scan bottom shorty - find all left and right colors and
// x-values for the bottommost of the two not-tallest short edges.
x = p2->point.x();
source = p2->color;
dest = p3->color;
r = source.r;
g = source.g;
b = source.b;
y1 = (int) floor(p2->point.y());
y2 = (int) floor(p3->point.y());
// Find slopes (notice that if the y dists are 0, we don't care
// about the slopes)
xdelta = p2p3ydist == 0.0 ? 0.0 : p2p3xdist / p2p3ydist;
rdelta = p2p3ydist == 0.0 ? 0.0 : (dest.r - r) / p2p3ydist;
gdelta = p2p3ydist == 0.0 ? 0.0 : (dest.g - g) / p2p3ydist;
bdelta = p2p3ydist == 0.0 ? 0.0 : (dest.b - b) / p2p3ydist;
// Calculate gradients using linear approximation
for (y = y1; y < y2; ++y) {
if (lefty) {
leftColors[y] = DoubleColor(r, g, b);
leftX[y] = x;
} else {
rightColors[y] = DoubleColor(r, g, b);
rightX[y] = x;
}
r += rdelta;
g += gdelta;
b += bdelta;
x += xdelta;
}
// Inner loop. For each y in the left map of x-values, draw one
// line from left to right.
const int p3yfloor = int(floor(p3->point.y()));
for (int y = int(floor(p1->point.y())); y < p3yfloor; ++y) {
double lx = leftX[y];
double rx = rightX[y];
int lxi = (int) floor(lx);
int rxi = (int) floor(rx);
DoubleColor rc = rightColors[y];
DoubleColor lc = leftColors[y];
// if the xdist is 0, don't draw anything.
double xdist = rx - lx;
if (xdist != 0.0) {
double r = lc.r;
double g = lc.g;
double b = lc.b;
double rdelta = (rc.r - r) / xdist;
double gdelta = (rc.g - g) / xdist;
double bdelta = (rc.b - b) / xdist;
QRgb *scanline = reinterpret_cast<QRgb *>(buf->scanLine(y));
scanline += lxi;
// Inner loop 2. Draws the line from left to right.
for (int i = lxi; i < rxi; ++i) {
*scanline++ = qRgb((int) r, (int) g, (int) b);
r += rdelta;
g += gdelta;
b += bdelta;
}
}
}
}
/*! \internal
Sets the color of the triangle to \a col.
*/
void QtColorTriangle::setColor(const QColor &col)
{
if (col == curColor)
return;
curColor = col;
int h, s, v;
curColor.getHsv(&h, &s, &v);
// Never use an invalid hue to display colors
if (h != -1)
curHue = h;
a = (((360 - curHue) * TWOPI) / 360.0);
a += PI / 2.0;
if (a > TWOPI) a -= TWOPI;
b = a + TWOPI/3;
c = b + TWOPI/3;
if (b > TWOPI) b -= TWOPI;
if (c > TWOPI) c -= TWOPI;
double cx = (double) contentsRect().center().x();
double cy = (double) contentsRect().center().y();
double innerRadius = outerRadius - (outerRadius / 5.0);
double pointerRadius = outerRadius - (outerRadius / 10.0);
pa = QPointF(cx + (cos(a) * innerRadius), cy - (sin(a) * innerRadius));
pb = QPointF(cx + (cos(b) * innerRadius), cy - (sin(b) * innerRadius));
pc = QPointF(cx + (cos(c) * innerRadius), cy - (sin(c) * innerRadius));
pd = QPointF(cx + (cos(a) * pointerRadius), cy - (sin(a) * pointerRadius));
selectorPos = pointFromColor(curColor);
update();
emit colorChanged(curColor);
}
/*! \internal
Returns the current color of the triangle.
*/
QColor QtColorTriangle::color() const
{
return curColor;
}
/*!
\internal
Returns the distance from \a pos to the center of \a rect.
*/
double QtColorTriangle::radiusAt(const QPointF &pos, const QRect &rect) const
{
double mousexdist = pos.x() - (double) rect.center().x();
double mouseydist = pos.y() - (double) rect.center().y();
return sqrt(mousexdist * mousexdist + mouseydist * mouseydist);
}
/*!
\internal
With origin set to the center of \a rect, this function returns
the angle in radians between the line that starts at (0,0) and
ends at (1,0) and the line that stars at (0,0) and ends at \a pos.
*/
double QtColorTriangle::angleAt(const QPointF &pos, const QRect &rect) const
{
double mousexdist = pos.x() - (double) rect.center().x();
double mouseydist = pos.y() - (double) rect.center().y();
double mouserad = sqrt(mousexdist * mousexdist + mouseydist * mouseydist);
if (mouserad == 0.0)
return 0.0;
double angle = acos(mousexdist / mouserad);
if (mouseydist >= 0)
angle = TWOPI - angle;
return angle;
}
/*! \internal
Returns a * a.
*/
inline double qsqr(double a)
{
return a * a;
}
/*! \internal
Returns the length of the vector (x,y).
*/
inline double vlen(double x, double y)
{
return sqrt(qsqr(x) + qsqr(y));
}
/*! \internal
Returns the vector product of (x1,y1) and (x2,y2).
*/
inline double vprod(double x1, double y1, double x2, double y2)
{
return x1 * x2 + y1 * y2;
}
/*! \internal
Returns true if the point cos(p),sin(p) is on the arc between
cos(a1),sin(a1) and cos(a2),sin(a2); otherwise returns false.
*/
bool angleBetweenAngles(double p, double a1, double a2)
{
if (a1 > a2) {
a2 += TWOPI;
if (p < PI) p += TWOPI;
}
return p >= a1 && p < a2;
}
/*! \internal
A line from a to b is one of several lines in an equilateral
polygon, and they are drawn counter clockwise. This line therefore
has one side facing in and one facing out of the polygon. This
function determines wether (x,y) is on the inside or outside of
the given line, defined by the "from" coordinate (ax,ay) and the
"to" coordinate (bx,by).
The point (px,py) is the intersection between the a-b line and the
perpendicular projection of (x,y) onto that line.
Returns true if (x,y) is above the line; otherwise returns false.
If ax and bx are equal and ay and by are equal (line is a point),
this function will return true if (x,y) is equal to this point.
*/
static bool pointAbovePoint(double x, double y, double px, double py,
double ax, double ay, double bx, double by)
{
bool result = false;
if (floor(ax) > floor(bx)) {
if (floor(ay) < floor(by)) {
// line is draw upright-to-downleft
if (floor(x) < floor(px) || floor(y) < floor(py))
result = true;
} else if (floor(ay) > floor(by)) {
// line is draw downright-to-upleft
if (floor(x) > floor(px) || floor(y) < floor(py))
result = true;
} else {
// line is flat horizontal
if (y < ay) result = true;
}
} else if (floor(ax) < floor(bx)) {
if (floor(ay) < floor(by)) {
// line is draw upleft-to-downright
if (floor(x) < floor(px) || floor(y) > floor(py))
result = true;
} else if (floor(ay) > floor(by)) {
// line is draw downleft-to-upright
if (floor(x) > floor(px) || floor(y) > floor(py))
result = true;
} else {
// line is flat horizontal
if (y > ay)
result = true;
}
} else {
// line is vertical
if (floor(ay) < floor(by)) {
if (x < ax) result = true;
} else if (floor(ay) > floor(by)) {
if (x > ax) result = true;
} else {
if (!(x == ax && y == ay))
result = true;
}
}
return result;
}
/*! \internal
if (ax,ay) to (bx,by) describes a line, and (x,y) is a point on
that line, returns -1 if (x,y) is outside the (ax,ay) bounds, 1 if
it is outside the (bx,by) bounds and 0 if (x,y) is within (ax,ay)
and (bx,by).
*/
static int pointInLine(double x, double y, double ax, double ay,
double bx, double by)
{
if (ax > bx) {
if (ay < by) {
// line is draw upright-to-downleft
// if (x,y) is in on or above the upper right point,
// return -1.
if (y <= ay && x >= ax)
return -1;
// if (x,y) is in on or below the lower left point,
// return 1.
if (y >= by && x <= bx)
return 1;
} else {
// line is draw downright-to-upleft
// If the line is flat, only use the x coordinate.
if (floor(ay) == floor(by)) {
// if (x is to the right of the rightmost point,
// return -1. otherwise if x is to the left of the
// leftmost point, return 1.
if (x >= ax)
return -1;
else if (x <= bx)
return 1;
} else {
// if (x,y) is on or below the lower right point,
// return -1.
if (y >= ay && x >= ax)
return -1;
// if (x,y) is on or above the upper left point,
// return 1.
if (y <= by && x <= bx)
return 1;
}
}
} else {
if (ay < by) {
// line is draw upleft-to-downright
// If (x,y) is on or above the upper left point, return
// -1.
if (y <= ay && x <= ax)
return -1;
// If (x,y) is on or below the lower right point, return
// 1.
if (y >= by && x >= bx)
return 1;
} else {
// line is draw downleft-to-upright
// If the line is flat, only use the x coordinate.
if (floor(ay) == floor(by)) {
if (x <= ax)
return -1;
else if (x >= bx)
return 1;
} else {
// If (x,y) is on or below the lower left point, return
// -1.
if (y >= ay && x <= ax)
return -1;
// If (x,y) is on or above the upper right point, return
// 1.
if (y <= by && x >= bx)
return 1;
}
}
}
// No tests proved that (x,y) was outside [(ax,ay),(bx,by)], so we
// assume it's inside the line's bounds.
return 0;
}
/*! \internal
\a a, \a b and \a c are corner points of an equilateral triangle.
(\a x,\a y) is an arbitrary point inside or outside this triangle.
If (x,y) is inside the triangle, this function returns the double
point (x,y).
Otherwise, the intersection of the perpendicular projection of
(x,y) onto the closest triangle edge is returned, unless this
intersection is outside the triangle's bounds, in which case the
corner closest to the intersection is returned instead.
Yes, it's trigonometry.
*/
QPointF QtColorTriangle::movePointToTriangle(double x, double y, const Vertex &a,
const Vertex &b, const Vertex &c) const
{
// Let v1A be the vector from (x,y) to a.
// Let v2A be the vector from a to b.
// Find the angle alphaA between v1A and v2A.
double v1xA = x - a.point.x();
double v1yA = y - a.point.y();
double v2xA = b.point.x() - a.point.x();
double v2yA = b.point.y() - a.point.y();
double vpA = vprod(v1xA, v1yA, v2xA, v2yA);
double cosA = vpA / (vlen(v1xA, v1yA) * vlen(v2xA, v2yA));
double alphaA = acos(cosA);
// Let v1B be the vector from x to b.
// Let v2B be the vector from b to c.
double v1xB = x - b.point.x();
double v1yB = y - b.point.y();
double v2xB = c.point.x() - b.point.x();
double v2yB = c.point.y() - b.point.y();
double vpB = vprod(v1xB, v1yB, v2xB, v2yB);
double cosB = vpB / (vlen(v1xB, v1yB) * vlen(v2xB, v2yB));
double alphaB = acos(cosB);
// Let v1C be the vector from x to c.
// Let v2C be the vector from c back to a.
double v1xC = x - c.point.x();
double v1yC = y - c.point.y();
double v2xC = a.point.x() - c.point.x();
double v2yC = a.point.y() - c.point.y();
double vpC = vprod(v1xC, v1yC, v2xC, v2yC);
double cosC = vpC / (vlen(v1xC, v1yC) * vlen(v2xC, v2yC));
double alphaC = acos(cosC);
// Find the radian angles between the (1,0) vector and the points
// A, B, C and (x,y). Use this information to determine which of
// the edges we should project (x,y) onto.
double angleA = angleAt(a.point, contentsRect());
double angleB = angleAt(b.point, contentsRect());
double angleC = angleAt(c.point, contentsRect());
double angleP = angleAt(QPointF(x, y), contentsRect());
// If (x,y) is in the a-b area, project onto the a-b vector.
if (angleBetweenAngles(angleP, angleA, angleB)) {
// Find the distance from (x,y) to a. Then use the slope of
// the a-b vector with this distance and the angle between a-b
// and a-(x,y) to determine the point of intersection of the
// perpendicular projection from (x,y) onto a-b.
double pdist = sqrt(qsqr(x - a.point.x()) + qsqr(y - a.point.y()));
// the length of all edges is always > 0
double p0x = a.point.x() + ((b.point.x() - a.point.x()) / vlen(v2xB, v2yB)) * cos(alphaA) * pdist;
double p0y = a.point.y() + ((b.point.y() - a.point.y()) / vlen(v2xB, v2yB)) * cos(alphaA) * pdist;
// If (x,y) is above the a-b line, which basically means it's
// outside the triangle, then return its projection onto a-b.
if (pointAbovePoint(x, y, p0x, p0y, a.point.x(), a.point.y(), b.point.x(), b.point.y())) {
// If the projection is "outside" a, return a. If it is
// outside b, return b. Otherwise return the projection.
int n = pointInLine(p0x, p0y, a.point.x(), a.point.y(), b.point.x(), b.point.y());
if (n < 0)
return a.point;
else if (n > 0)
return b.point;
return QPointF(p0x, p0y);
}
} else if (angleBetweenAngles(angleP, angleB, angleC)) {
// If (x,y) is in the b-c area, project onto the b-c vector.
double pdist = sqrt(qsqr(x - b.point.x()) + qsqr(y - b.point.y()));
// the length of all edges is always > 0
double p0x = b.point.x() + ((c.point.x() - b.point.x()) / vlen(v2xC, v2yC)) * cos(alphaB) * pdist;
double p0y = b.point.y() + ((c.point.y() - b.point.y()) / vlen(v2xC, v2yC)) * cos(alphaB) * pdist;
if (pointAbovePoint(x, y, p0x, p0y, b.point.x(), b.point.y(), c.point.x(), c.point.y())) {
int n = pointInLine(p0x, p0y, b.point.x(), b.point.y(), c.point.x(), c.point.y());
if (n < 0)
return b.point;
else if (n > 0)
return c.point;
return QPointF(p0x, p0y);
}
} else if (angleBetweenAngles(angleP, angleC, angleA)) {
// If (x,y) is in the c-a area, project onto the c-a vector.
double pdist = sqrt(qsqr(x - c.point.x()) + qsqr(y - c.point.y()));
// the length of all edges is always > 0
double p0x = c.point.x() + ((a.point.x() - c.point.x()) / vlen(v2xA, v2yA)) * cos(alphaC) * pdist;
double p0y = c.point.y() + ((a.point.y() - c.point.y()) / vlen(v2xA, v2yA)) * cos(alphaC) * pdist;
if (pointAbovePoint(x, y, p0x, p0y, c.point.x(), c.point.y(), a.point.x(), a.point.y())) {
int n = pointInLine(p0x, p0y, c.point.x(), c.point.y(), a.point.x(), a.point.y());
if (n < 0)
return c.point;
else if (n > 0)
return a.point;
return QPointF(p0x, p0y);
}
}
// (x,y) is inside the triangle (inside a-b, b-c and a-c).
return QPointF(x, y);
}
/*! \internal
Given the color \a col, this function determines the point in the
equilateral triangle defined with (pa, pb, pc) that displays this
color. The function assumes the color at pa has a hue equal to the
hue of \a col, and that pb is black and pc is white.
In this certain type of triangle, we observe that saturation grows
from the black-color edge towards the black-white edge. The value
grows from the black corner towards the white-color edge. Using
the intersection of the saturation and value points on the three
edges, we are able to determine the point with the same saturation
and value as \a col.
*/
QPointF QtColorTriangle::pointFromColor(const QColor &col) const
{
// Simplifications for the corner cases.
if (col == Qt::black)
return pb;
else if (col == Qt::white)
return pc;
// Find the x and y slopes
double ab_deltax = pb.x() - pa.x();
double ab_deltay = pb.y() - pa.y();
double bc_deltax = pc.x() - pb.x();
double bc_deltay = pc.y() - pb.y();
double ac_deltax = pc.x() - pa.x();
double ac_deltay = pc.y() - pa.y();
// Extract the h,s,v values of col.
int hue,sat,val;
col.getHsv(&hue, &sat, &val);
// Find the line that passes through the triangle where the value
// is equal to our color's value.
double p1 = pa.x() + (ab_deltax * (double) (255 - val)) / 255.0;
double q1 = pa.y() + (ab_deltay * (double) (255 - val)) / 255.0;
double p2 = pb.x() + (bc_deltax * (double) val) / 255.0;
double q2 = pb.y() + (bc_deltay * (double) val) / 255.0;
// Find the line that passes through the triangle where the
// saturation is equal to our color's value.
double p3 = pa.x() + (ac_deltax * (double) (255 - sat)) / 255.0;
double q3 = pa.y() + (ac_deltay * (double) (255 - sat)) / 255.0;
double p4 = pb.x();
double q4 = pb.y();
// Find the intersection between these lines.
double x = 0;
double y = 0;
if (p1 != p2) {
double a = (q2 - q1) / (p2 - p1);
double c = (q4 - q3) / (p4 - p3);
double b = q1 - a * p1;
double d = q3 - c * p3;
x = (d - b) / (a - c);
y = a * x + b;
}
else {
x = p1;
y = q3 + (x - p3) * (q4 - q3) / (p4 - p3);
}
return QPointF(x, y);
}
/*! \internal
Determines the color in the color triangle at the point \a p. Uses
linear interpolation to find the colors to the left and right of
\a p, then uses the same technique to find the color at \a p using
these two colors.
*/
QColor QtColorTriangle::colorFromPoint(const QPointF &p) const
{
// Find the outer radius of the hue gradient.
int outerRadius = (contentsRect().width() - 1) / 2;
if ((contentsRect().height() - 1) / 2 < outerRadius)
outerRadius = (contentsRect().height() - 1) / 2;
// Find the center coordinates
double cx = (double) contentsRect().center().x();
double cy = (double) contentsRect().center().y();
// Find the a, b and c from their angles, the center of the rect
// and the radius of the hue gradient donut.
QPointF pa(cx + (cos(a) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(a) * (outerRadius - (outerRadius / 5.0))));
QPointF pb(cx + (cos(b) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(b) * (outerRadius - (outerRadius / 5.0))));
QPointF pc(cx + (cos(c) * (outerRadius - (outerRadius / 5.0))),
cy - (sin(c) * (outerRadius - (outerRadius / 5.0))));
// Find the hue value from the angle of the 'a' point.
double angle = a - PI/2.0;
if (angle < 0) angle += TWOPI;
double hue = (360.0 * angle) / TWOPI;
// Create the color of the 'a' corner point. We know that b is
// black and c is white.
QColor color;
color.setHsv(360 - (int) floor(hue), 255, 255);
// See also drawTrigon(), which basically does exactly the same to
// determine all colors in the trigon.
Vertex aa(color, pa);
Vertex bb(Qt::black, pb);
Vertex cc(Qt::white, pc);
// Make sure p1 is above p2, which is above p3.
Vertex *p1 = &aa;
Vertex *p2 = &bb;
Vertex *p3 = &cc;
if (p1->point.y() > p2->point.y()) swap(&p1, &p2);
if (p1->point.y() > p3->point.y()) swap(&p1, &p3);
if (p2->point.y() > p3->point.y()) swap(&p2, &p3);
// Find the slopes of all edges in the trigon. All the three y
// deltas here are positive because of the above sorting.
double p1p2ydist = p2->point.y() - p1->point.y();
double p1p3ydist = p3->point.y() - p1->point.y();
double p2p3ydist = p3->point.y() - p2->point.y();
double p1p2xdist = p2->point.x() - p1->point.x();
double p1p3xdist = p3->point.x() - p1->point.x();
double p2p3xdist = p3->point.x() - p2->point.x();
// The first x delta decides wether we have a lefty or a righty
// trigon. A lefty trigon has its tallest edge on the right hand
// side of the trigon. The righty trigon has it on its left side.
// This property determines wether the left or the right set of x
// coordinates will be continuous.
bool lefty = p1p2xdist < 0;
// Find whether the selector's y is in the first or second shorty,
// counting from the top and downwards. This is used to find the
// color at the selector point.
bool firstshorty = (p.y() >= p1->point.y() && p.y() < p2->point.y());
// From the y value of the selector's position, find the left and
// right x values.
double leftx;
double rightx;
if (lefty) {
if (firstshorty) {
leftx = p1->point.x();
if (floor(p1p2ydist) != 0.0) {
leftx += (p1p2xdist * (p.y() - p1->point.y())) / p1p2ydist;
} else {
leftx = qMin(p1->point.x(), p2->point.x());
}
} else {
leftx = p2->point.x();
if (floor(p2p3ydist) != 0.0) {
leftx += (p2p3xdist * (p.y() - p2->point.y())) / p2p3ydist;
} else {
leftx = qMin(p2->point.x(), p3->point.x());
}
}
rightx = p1->point.x();
rightx += (p1p3xdist * (p.y() - p1->point.y())) / p1p3ydist;
} else {
leftx = p1->point.x();
leftx += (p1p3xdist * (p.y() - p1->point.y())) / p1p3ydist;
if (firstshorty) {
rightx = p1->point.x();
if (floor(p1p2ydist) != 0.0) {
rightx += (p1p2xdist * (p.y() - p1->point.y())) / p1p2ydist;
} else {
rightx = qMax(p1->point.x(), p2->point.x());
}
} else {
rightx = p2->point.x();
if (floor(p2p3ydist) != 0.0) {
rightx += (p2p3xdist * (p.y() - p2->point.y())) / p2p3ydist;
} else {
rightx = qMax(p2->point.x(), p3->point.x());
}
}
}
// Find the r,g,b values of the points on the trigon's edges that
// are to the left and right of the selector.
double rshort = 0, gshort = 0, bshort = 0;
double rlong = 0, glong = 0, blong = 0;
if (firstshorty) {
if (floor(p1p2ydist) != 0.0) {
rshort = p2->color.r * (p.y() - p1->point.y()) / p1p2ydist;
gshort = p2->color.g * (p.y() - p1->point.y()) / p1p2ydist;
bshort = p2->color.b * (p.y() - p1->point.y()) / p1p2ydist;
rshort += p1->color.r * (p2->point.y() - p.y()) / p1p2ydist;
gshort += p1->color.g * (p2->point.y() - p.y()) / p1p2ydist;
bshort += p1->color.b * (p2->point.y() - p.y()) / p1p2ydist;
} else {
if (lefty) {
if (p1->point.x() <= p2->point.x()) {
rshort = p1->color.r;
gshort = p1->color.g;
bshort = p1->color.b;
} else {
rshort = p2->color.r;
gshort = p2->color.g;
bshort = p2->color.b;
}
} else {
if (p1->point.x() > p2->point.x()) {
rshort = p1->color.r;
gshort = p1->color.g;
bshort = p1->color.b;
} else {
rshort = p2->color.r;
gshort = p2->color.g;
bshort = p2->color.b;
}
}
}
} else {
if (floor(p2p3ydist) != 0.0) {
rshort = p3->color.r * (p.y() - p2->point.y()) / p2p3ydist;
gshort = p3->color.g * (p.y() - p2->point.y()) / p2p3ydist;
bshort = p3->color.b * (p.y() - p2->point.y()) / p2p3ydist;
rshort += p2->color.r * (p3->point.y() - p.y()) / p2p3ydist;
gshort += p2->color.g * (p3->point.y() - p.y()) / p2p3ydist;
bshort += p2->color.b * (p3->point.y() - p.y()) / p2p3ydist;
} else {
if (lefty) {
if (p2->point.x() <= p3->point.x()) {
rshort = p2->color.r;
gshort = p2->color.g;
bshort = p2->color.b;
} else {
rshort = p3->color.r;
gshort = p3->color.g;
bshort = p3->color.b;
}
} else {
if (p2->point.x() > p3->point.x()) {
rshort = p2->color.r;
gshort = p2->color.g;
bshort = p2->color.b;
} else {
rshort = p3->color.r;
gshort = p3->color.g;
bshort = p3->color.b;
}
}
}
}
// p1p3ydist is never 0
rlong = p3->color.r * (p.y() - p1->point.y()) / p1p3ydist;
glong = p3->color.g * (p.y() - p1->point.y()) / p1p3ydist;
blong = p3->color.b * (p.y() - p1->point.y()) / p1p3ydist;
rlong += p1->color.r * (p3->point.y() - p.y()) / p1p3ydist;
glong += p1->color.g * (p3->point.y() - p.y()) / p1p3ydist;
blong += p1->color.b * (p3->point.y() - p.y()) / p1p3ydist;
// rshort,gshort,bshort is the color on one of the shortys.
// rlong,glong,blong is the color on the longy. So depending on
// wether we have a lefty trigon or not, we can determine which
// colors are on the left and right edge.
double rl, gl, bl, rr, gr, br;
if (lefty) {
rl = rshort; gl = gshort; bl = bshort;
rr = rlong; gr = glong; br = blong;
} else {
rl = rlong; gl = glong; bl = blong;
rr = rshort; gr = gshort; br = bshort;
}
// Find the distance from the left x to the right x (xdist). Then
// find the distances from the selector to each of these (saxdist
// and saxdist2). These distances are used to find the color at
// the selector.
double xdist = rightx - leftx;
double saxdist = p.x() - leftx;
double saxdist2 = xdist - saxdist;
// Now determine the r,g,b values of the selector using a linear
// approximation.
double r, g, b;
if (xdist != 0.0) {
r = (saxdist2 * rl / xdist) + (saxdist * rr / xdist);
g = (saxdist2 * gl / xdist) + (saxdist * gr / xdist);
b = (saxdist2 * bl / xdist) + (saxdist * br / xdist);
} else {
// In theory, the left and right color will be equal here. But
// because of the loss of precision, we get an error on both
// colors. The best approximation we can get is from adding
// the two errors, which in theory will eliminate the error
// but in practise will only minimize it.
r = (rl + rr) / 2;
g = (gl + gr) / 2;
b = (bl + br) / 2;
}
// Now floor the color components and fit them into proper
// boundaries. This again is to compensate for the error caused by
// loss of precision.
int ri = (int) floor(r);
int gi = (int) floor(g);
int bi = (int) floor(b);
if (ri < 0) ri = 0;
else if (ri > 255) ri = 255;
if (gi < 0) gi = 0;
else if (gi > 255) gi = 255;
if (bi < 0) bi = 0;
else if (bi > 255) bi = 255;
// Voila, we have the color at the point of the selector.
return QColor(ri, gi, bi);
} | 33.818783 | 106 | 0.542535 | jcfr |
206e4387e1fafaa69f9661d7a1431a3b4e08fe97 | 306 | hpp | C++ | Source/BufferConversions.hpp | ncorgan/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 2 | 2021-01-19T02:21:48.000Z | 2022-03-26T23:05:49.000Z | Source/BufferConversions.hpp | ncorgan/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 3 | 2020-07-26T18:48:21.000Z | 2020-10-28T00:45:42.000Z | Source/BufferConversions.hpp | pothosware/PothosArrayFire | b2ce286827cefdc45507dbae65879a943e977479 | [
"BSD-3-Clause"
] | 1 | 2022-03-24T06:22:20.000Z | 2022-03-24T06:22:20.000Z | // Copyright (c) 2019-2020 Nicholas Corgan
// SPDX-License-Identifier: BSD-3-Clause
#pragma once
#include <Pothos/Framework.hpp>
#include <arrayfire.h>
//
// Pothos::BufferChunk <-> af::array
//
template <typename AfArrayType>
Pothos::BufferChunk afArrayTypeToBufferChunk(const AfArrayType& afArray);
| 19.125 | 73 | 0.751634 | ncorgan |
206ea1f266af27686ef257661c687a374307fd14 | 1,836 | cpp | C++ | contrib/server_side/sse/examples/ticker.cpp | gatehouse/cppcms | 61da055ffeb349b4eda14bc9ac393af9ce842364 | [
"MIT"
] | 388 | 2017-03-01T07:39:21.000Z | 2022-03-30T19:38:41.000Z | contrib/server_side/sse/examples/ticker.cpp | gatehouse/cppcms | 61da055ffeb349b4eda14bc9ac393af9ce842364 | [
"MIT"
] | 81 | 2017-03-08T20:28:00.000Z | 2022-01-23T08:19:31.000Z | contrib/server_side/sse/examples/ticker.cpp | gatehouse/cppcms | 61da055ffeb349b4eda14bc9ac393af9ce842364 | [
"MIT"
] | 127 | 2017-03-05T21:53:40.000Z | 2022-02-25T02:31:01.000Z | //
// Copyright (C) 2008-2012 Artyom Beilis (Tonkikh) <artyomtnk@yahoo.com>
//
// See accompanying file COPYING.TXT file for licensing details.
//
#include "server_sent_events.h"
#include <cppcms/application.h>
#include <cppcms/applications_pool.h>
#include <cppcms/service.h>
#include <cppcms/http_context.h>
#include <booster/aio/deadline_timer.h>
#include <booster/system_error.h>
#include <sstream>
class ticker : public cppcms::application {
public:
ticker(cppcms::service &srv) :
cppcms::application(srv),
tm_(srv.get_io_service()),
price_(1.0)
{
stream_ = sse::state_stream::create(srv.get_io_service());
wait();
}
void wait()
{
tm_.expires_from_now(booster::ptime::from_number(double(rand())/RAND_MAX + 0.01));
tm_.async_wait([=](booster::system::error_code const &e){
if(!e) {
on_timer();
wait();
}
});
}
void on_timer()
{
price_ += double(rand()) / RAND_MAX * 2.0 - 1;
if(price_ <= 0.01)
price_ = 0.01;
std::ostringstream ss;
ss << price_;
stream_->update(ss.str());
}
void main(std::string /*url*/)
{
stream_->accept(release_context());
}
private:
booster::shared_ptr<sse::state_stream> stream_;
booster::aio::deadline_timer tm_;
double price_;
};
int main(int argc,char **argv)
{
try {
cppcms::service service(argc,argv);
booster::intrusive_ptr<ticker> c=new ticker(service);
service.applications_pool().mount(c);
service.run();
}
catch(std::exception const &e) {
std::cerr<<"Catched exception: "<<e.what()<<std::endl;
return 1;
}
return 0;
}
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
| 23.844156 | 90 | 0.589325 | gatehouse |
207442aa50ebc1a77ef2169e92d6185ed0b3e4cb | 14,376 | cpp | C++ | NuclearSegmentation/NucleusEditor/Trace.cpp | tostathaina/farsight | 7e9d6d15688735f34f7ca272e4e715acd11473ff | [
"Apache-2.0"
] | 8 | 2016-07-22T11:24:19.000Z | 2021-04-10T04:22:31.000Z | NuclearSegmentation/NucleusEditor/Trace.cpp | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | null | null | null | NuclearSegmentation/NucleusEditor/Trace.cpp | YanXuHappygela/Farsight | 1711b2a1458c7e035edd21fe0019a1f7d23fcafa | [
"Apache-2.0"
] | 7 | 2016-07-21T07:39:17.000Z | 2020-01-29T02:03:27.000Z | #include "Trace.h"
#pragma warning(disable:4996)
bool TraceObject::ReadFromFeatureTracksFileForKymograph(char *filename,int type_offset=0)
{
FILE * fp = fopen(filename,"r");
if(fp == NULL)
{
printf("Could not open %s for reading\n",filename);
return false;
}
int curr_track = -1;
TraceLine* curr_line = NULL;
int line_count=0;
int curr_id = 0;
while(!feof(fp))
{
int track;
double x,y,z;
int t;
TraceBit tbit;
fscanf(fp,"%d %d %lf %lf %lf",&track,&t,&x,&y,&z);//We do not represent the z axis, instead use it for coloring the tracks
tbit.x = x; tbit.y = 2.97/2.79*y; tbit.z = t; tbit.id = z;line_count++;
tbit.r = 1;
if(track!=curr_track)
{
curr_track = track;
TraceLine* tline = new TraceLine();
trace_lines.push_back(tline);
tline->SetId(curr_id++);
tline->SetType(1+type_offset);
curr_line = tline;
}
curr_line->AddTraceBit(tbit);
}
printf("I read %d lines from the file %s\n",line_count,filename);
fclose(fp);
return true;
}
bool TraceObject::ReadFromFeatureTracksFile(char *filename,int type_offset=0)
{
FILE * fp = fopen(filename,"r");
if(fp==NULL)
return false;
int curr_track = -1;
TraceLine* curr_line = NULL;
int curr_id = 0;
while(!feof(fp))
{
int track;
TraceBit tbit;
fscanf(fp,"%d %d %lf %lf %lf",&track,&tbit.id,&tbit.x,&tbit.y,&tbit.z);
tbit.r = 1;
if(track!=curr_track)
{
curr_track = track;
TraceLine* tline = new TraceLine();
tline->SetId(curr_id++);
tline->SetType(1+type_offset);
trace_lines.push_back(tline);
curr_line = tline;
}
curr_line->AddTraceBit(tbit);
}
fclose(fp);
return true;
}
bool TraceObject::ReadFromSWCFile(char * filename)
{
FILE * fp = fopen(filename, "r");
if(fp==NULL)
{
printf("Couldn't open file %s for parsing\n",filename);
return false;
}
char buff[1024];
stdext::hash_map<unsigned int, unsigned long long int> hash_load;
int tc = 0;
unsigned char child_count[1000000];
int id, type,parent;
double x,y,z,r;
while(!feof(fp))
{
fgets(buff,1024,fp);
int pc = 0;
while(buff[pc]==' '&&(pc<1023))
pc++;
if(buff[pc]=='#') // ignoring comment lines for now. We have to read scale from it! TODO
continue;
//sscanf(buff,"%d %d %lf %lf %lf %lf %d",&id,&type,&x,&y,&z,&r,&parent);
sscanf(buff,"%d %*lf %*lf %*lf %*lf %*lf %d",&id,&parent);
tc++;
child_count[id]=0;
if(parent!=-1)
child_count[parent]++;
}
//printf("I read %d lines\n",tc);
fclose(fp);
fp = fopen(filename,"r");
int tcc =0;
while(!feof(fp))
{
tcc++;
//printf("Done %d\n",tcc);
fgets(buff,1024,fp);
int pc = 0;
while(buff[pc]==' '&&(pc<1023))
pc++;
if(buff[pc]=='#') // ignoring comment lines for now. We have to read scale from it! TODO
continue;
sscanf(buff,"%d %d %lf %lf %lf %lf %d",&id,&type,&x,&y,&z,&r,&parent);
TraceBit tbit;
tbit.x=x;tbit.y=y;tbit.z=z;tbit.id=id;tbit.r =r;
if(parent==-1)
{
TraceLine *line = new TraceLine();
line->SetType(type);
line->SetId(type);
line->AddTraceBit(tbit);
hash_load[id]=(unsigned long long int)line;
trace_lines.push_back(line);
}
else if (child_count[parent]==1)
{
TraceLine* line = reinterpret_cast<TraceLine*>(hash_load[parent]);
hash_load[id] = (unsigned long long int)line;
TraceLine::TraceBitsType::iterator iter = line->GetTraceBitIteratorEnd();
iter--;
TraceLine::TraceBitsType::iterator iterbegin = line->GetTraceBitIteratorBegin();
do
{
if(iter->id==parent)
{
++iter;
line->GetTraceBitsPointer()->insert(iter,tbit);
// printf("Successfully inserted\n");
break;
}
--iter;
}while(iter!=iterbegin);
}
else
{
TraceLine * line = new TraceLine();
line->SetType(type);
line->SetId(type);
line->AddTraceBit(tbit);
hash_load[id]=(unsigned long long int)line;
TraceLine * old_line = reinterpret_cast<TraceLine*>(hash_load[parent]);
old_line->AddBranch(line);
line->SetParent(old_line);
}
}
printf("Finished loading\n");
//Print(std::cout);
fclose(fp);
return true;
}
//void TraceObject::CreatePolyDataRecursive(TraceLine* tline, vtkSmartPointer<vtkFloatArray> point_scalars, vtkSmartPointer<vtkPoints> line_points,vtkSmartPointer<vtkCellArray> line_cells)
void TraceObject::CreatePolyDataRecursive(TraceLine* tline, vtkSmartPointer<vtkUnsignedCharArray> point_scalars, vtkSmartPointer<vtkPoints> line_points,vtkSmartPointer<vtkCellArray> line_cells)
{
//tline->Print(std::cout);
//scanf("%*c");
TraceLine::TraceBitsType tbits;
TraceLine::TraceBitsType::iterator iter=tline->GetTraceBitIteratorBegin();
tline->SetId(iter->id);
double point[3];
unsigned int return_id;
unsigned int cell_id;
unsigned int old_id;
unsigned char color[3];
int color_index = iter->id%6;
switch(color_index)
{
//Cyan
case 0:
color[0]=0;
color[1]=255;
color[2]=255;
break;
//Royal Blue 65-105-225
case 1:
color[0]=65;
color[1]=105;
color[2]=255;
break;
//Red
case 2:
color[0]=255;
color[1]=0;
color[2]=0;
break;
//Blue
case 3:
color[0]=0;
color[1]=0;
color[2]=255;
break;
//Orange 255-165-0
case 4:
color[0]=255;
color[1]=165;
color[2]=0;
break;
//Violet 238-130-238
case 5:
color[0]=255;
color[1]=255;
color[2]=0;
break;
}
std::vector<unsigned int>* cell_id_array=tline->GetMarkers();
point[0] = iter->x;
point[1]= iter->y;
point[2]= iter->z;
return_id = line_points->InsertNextPoint(point);
tline->points_hash[return_id] = *iter;
hashp[return_id]=(unsigned long long int)tline;
iter->marker = return_id;
std::vector<TraceBit> tbitpair;
//tbitpair.push_back(*iter);
/* Rest of the lines for the current tline */
iter++;
int pc = 0;
unsigned int track = 1;
unsigned int cid = 1;
std::list<TraceBit>::iterator old_iter;
while(iter!=tline->GetTraceBitIteratorEnd())
{
//printf("in loop %d\n",++pc);
old_id = return_id;
point[0] = iter->x;point[1]=iter->y;point[2]=iter->z;
return_id = line_points->InsertNextPoint(point);
tline->points_hash[return_id] = *iter;
hashp[return_id]=(unsigned long long int)tline;
iter->marker = return_id;
//point_scalars->InsertNextTuple1(iter->id/40.0);
iter->track_marker = point_scalars->InsertNextTupleValue(color);
if (pc==0)
track = iter->track_marker;
cell_id = line_cells->InsertNextCell(2);
// store vtk cells and tbits defining them***********************
--iter;
old_iter = iter;
tbitpair.push_back(*old_iter);
++iter;
tbitpair.push_back(*iter);
tline->subtrace_hash[cell_id]= tbitpair;
tbitpair.clear();
// finished storing**********************************************
iter->track_cell_id =cell_id;
if (pc==0)
cid = iter->track_cell_id;
cell_id_array->push_back(cell_id);
hashc[cell_id]=reinterpret_cast<unsigned long long int>(tline);
line_cells->InsertCellPoint(old_id);
line_cells->InsertCellPoint(return_id);
++iter;
++pc;
}
iter = tline->GetTraceBitIteratorBegin();
iter->track_marker = track;
iter->track_cell_id = cid;
/* Recursive calls to the branches if they exist */
//for(int counter=0; counter< tline->GetBranchPointer()->size(); counter++)
//{
// //printf("I should be having children too! what am I doing here?\n");
// CreatePolyDataRecursive((*tline->GetBranchPointer())[counter],point_scalars,line_points,line_cells);
//}
}
void CollectTraceBitsRecursive(std::vector<TraceBit> &vec,TraceLine *l)
{
TraceLine::TraceBitsType *p = l->GetTraceBitsPointer();
TraceLine::TraceBitsType::iterator iter = p->begin();
TraceLine::TraceBitsType::iterator iterend = p->end();
while(iter!=iterend)
{
vec.push_back(*iter);
iter++;
}
std::vector<TraceLine*>* bp = l->GetBranchPointer();
for(int counter=0; counter< bp->size(); counter++)
{
CollectTraceBitsRecursive(vec,(*bp)[counter]);
}
}
std::vector<TraceBit> TraceObject::CollectTraceBits()
{
std::vector<TraceBit> vec;
for(int counter=0; counter<trace_lines.size(); counter++)
CollectTraceBitsRecursive(vec,trace_lines[counter]);
return vec;
}
//bool TraceObject::WriteToSWCFile(char *filename)
//{
// FILE * fp = fopen(filename,"w");
// stdext::hash_map<unsigned long long int,int> hash_dump;
// if(fp == NULL)
// {
// printf("Couldn't open %s for writing\n",filename);
// return false;
// }
// int cur_id = 1;
// std::queue<TraceLine*> q;
// for(int counter=0; counter<trace_lines.size(); counter++)
// {
// q.push(trace_lines[counter]);
// }
// while(!q.empty())
// {
// TraceLine *t = q.front();
// q.pop();
// TraceLine::TraceBitsType::iterator iter = t->GetTraceBitIteratorBegin();
// TraceLine::TraceBitsType::iterator iterend = t->GetTraceBitIteratorEnd();
// hash_dump[reinterpret_cast<unsigned long long int>(t)]=cur_id+t->GetTraceBitsPointer()->size()-1;
// if(t->GetParent()==NULL)
// {
// fprintf(fp,"%d %d %0.2lf %0.2lf %0.2lf %0.2lf %d\n",cur_id++,t->GetType(),iter->x,iter->y,iter->z,iter->r,-1);
// }
// else
// {
// fprintf(fp,"%d %d %0.2lf %0.2lf %0.2lf %0.2lf %d\n",cur_id++,t->GetType(),iter->x,iter->y,iter->z,iter->r,hash_dump[reinterpret_cast<unsigned long long int>(t->GetParent())]);
// }
// iter++;
// while(iter!=iterend)
// {
// fprintf(fp,"%d %d %0.2lf %0.2lf %0.2lf %0.2lf %d\n",cur_id,t->GetType(),iter->x,iter->y,iter->z,iter->r,cur_id-1);
// cur_id++;
// iter++;
// }
// for(int counter=0; counter<t->GetBranchPointer()->size(); counter++)
// {
// q.push((*t->GetBranchPointer())[counter]);
// }
// }
// fclose(fp);
// return true;
//}
vtkSmartPointer<vtkPolyData> TraceObject::GetVTKPolyData()
{
hashp.clear();
printf("Started creating vtkPolyData for rendering purposes ... ");
vtkSmartPointer<vtkPolyData> poly_traces=vtkSmartPointer<vtkPolyData>::New();
// vtkSmartPointer<vtkFloatArray> point_scalars = vtkSmartPointer<vtkFloatArray>::New(); //responsible for coloring the traces
vtkSmartPointer<vtkUnsignedCharArray> point_scalars = vtkSmartPointer<vtkUnsignedCharArray>::New(); //responsible for coloring the traces
// point_scalars->SetNumberOfComponents(1);
point_scalars->SetNumberOfComponents(3);
point_scalars->SetName("colors");
vtkSmartPointer<vtkPoints> line_points=vtkSmartPointer<vtkPoints>::New();
line_points->SetDataTypeToDouble();
vtkSmartPointer<vtkCellArray> line_cells=vtkSmartPointer<vtkCellArray>::New();
printf("Starting CreatePolyDataRecursive\n");
for(int counter=0; counter<trace_lines.size(); counter++)
{
/*printf("Calling CreatePolyDataRecursive %dth time\n",counter+1);*/
CreatePolyDataRecursive(trace_lines[counter],point_scalars,line_points,line_cells);
}
printf("Finished CreatePolyDataRecursive\n");
poly_traces->SetPoints(line_points);
poly_traces->SetLines(line_cells);
// poly_traces->GetPointData()->SetScalars(point_scalars);
poly_traces->GetCellData()->SetScalars(point_scalars);
OriginalColors = vtkSmartPointer<vtkUnsignedCharArray>::New();
OriginalColors->DeepCopy(point_scalars);
printf("Done\n");
return poly_traces;
}
// Handy functions to read Props from the xml
// Hope this is the right way to read and delete memory
//int xmlReadInt(xmlNodePtr p,char *s,int def)
//{
// xmlChar * charp = xmlGetProp(p, BAD_CAST s);
// int num;
// if(charp!=NULL)
// {
// num = atof((char*)charp);
// delete [] charp;
// }
// else
// {
// num = def; // THIS SHOULD NEVER HAPPEN
// }
// return num;
//}
//
//float xmlReadFloat(xmlNodePtr p,char *s,float def)
//{
// xmlChar * charp = xmlGetProp(p, BAD_CAST s);
// float num;
// if(charp!=NULL)
// {
// num = atof((char*)charp);
// delete [] charp;
// }
// else
// {
// num = def; // THIS SHOULD NEVER HAPPEN
// }
// return num;
//}
//
//bool TraceObject::ReadFromRPIXMLFile(char * filename)
//{
// printf("Started reading from %s ...",filename);
//
// stdext::hash_map<unsigned int, unsigned long long int> hash_load;
// /* reads the XML file */
// int count = 0;
// /* test if libxml works and if xml is parsed*/
// LIBXML_TEST_VERSION;
// xmlDocPtr doc;
// doc = xmlReadFile(filename, NULL, 0);
// if (doc == NULL)
// {
// fprintf(stderr, "Failed to parse %s\n", filename);
// return false;
// }
////finds the root of the xml tree
// xmlNodePtr root_node = NULL, trace_node = NULL, line_node = NULL, bit_node = NULL;
// root_node = xmlDocGetRootElement(doc);
// //std::cout << "Root node: " << root_node->name <<std::endl;
//
// line_node = root_node->children;
// //reading lines
// for ( ; line_node; line_node = line_node->next)
// {
// if (line_node->type == XML_ELEMENT_NODE && !xmlStrcmp(line_node->name, BAD_CAST "TraceLine"))
// {
// float lid = xmlReadFloat(line_node,"ID",1);// default should never come for this case
// int type = xmlReadInt(line_node,"Type",1);
// int parent = xmlReadInt(line_node,"Parent",-1);
//
// TraceLine * tline = new TraceLine();
// tline->SetId(lid);
// tline->SetType(type);
// hash_load[lid]=reinterpret_cast<unsigned long long int>(tline);
// if(parent!=-1)
// {
// TraceLine * tparent = reinterpret_cast<TraceLine*>(hash_load[parent]);
// tline->SetParent(tparent);
// tparent->GetBranchPointer()->push_back(tline);
// }
// else
// {
// trace_lines.push_back(tline);
// }
// //std::cout << "Line node: " << line_node->name << " " <<lid << std::endl;
// int counter= 0, pid =0; double x, y, z;
// bit_node = line_node->children;
//
// //reading points
// for ( ;bit_node; bit_node = bit_node->next)
// {
// TraceBit tbit;
// if ( !xmlStrcmp(bit_node->name, BAD_CAST "TraceBit") )
// {
// pid = xmlReadInt(bit_node,"ID",0);
// x = xmlReadFloat(bit_node,"X",0);
// y = xmlReadFloat(bit_node,"Y",0);
// z = xmlReadFloat(bit_node,"Z",0);
// //printf("pid %d\n",pid);
// tbit.x = x; tbit.y = y; tbit.z = z; tbit.id = pid;
// tline->AddTraceBit(tbit);
// counter++;
// }
// }
//
// }
// }
// printf("Done\n");
// return true;
//}
void TraceLine::Getstats()
{
double XF, XB, YF, YB, ZF, ZB;
XF = m_trace_bits.front().x;
XB = m_trace_bits.back().x;
YF= m_trace_bits.front().y;
YB= m_trace_bits.back().y;
ZF= m_trace_bits.front().z;
ZB= m_trace_bits.back().z;
printf("Trace # %d \t Trace Size: \t %d ", m_id, m_trace_bits.size());
printf("First bit x: %4.2f y: %4.2f z: %4.2f \t", XF, YF, ZF);
printf("Endt bit x: %4.2f y: %4.2f z: %4.2f \n", XB, YB, ZB);
};
| 27.435115 | 193 | 0.65032 | tostathaina |
2075bcb585d944b48c82d9b8299daafb2440718e | 11,733 | cpp | C++ | src/AudioFrame.cpp | SolarAquarion/ffmpegyag | bb77508afd7dd30b853ff8e56a9a062c01ca8237 | [
"MIT"
] | 12 | 2017-09-24T06:27:25.000Z | 2022-02-02T09:40:38.000Z | src/AudioFrame.cpp | SolarAquarion/ffmpegyag | bb77508afd7dd30b853ff8e56a9a062c01ca8237 | [
"MIT"
] | 3 | 2017-09-24T06:34:06.000Z | 2018-06-11T05:31:21.000Z | src/AudioFrame.cpp | SolarAquarion/ffmpegyag | bb77508afd7dd30b853ff8e56a9a062c01ca8237 | [
"MIT"
] | 4 | 2018-03-02T15:23:12.000Z | 2019-06-05T12:07:13.000Z | #include "AudioFrame.h"
AudioFrame::AudioFrame(int64_t FrameTimestamp, int64_t FrameTimecode, int64_t FrameDuration, int FrameSampleRate, int FrameChannels, AVSampleFormat FrameSampleFormat, size_t FrameSampleCount)
{
Timestamp = FrameTimestamp;
Timecode = FrameTimecode;
Duration = FrameDuration;
SampleRate = FrameSampleRate;
ChannelCount = FrameChannels;
PCMFormat = FrameSampleFormat;
SampleCount = FrameSampleCount;
DataSize = av_samples_get_buffer_size(NULL, FrameChannels, FrameSampleCount, PCMFormat, 1);
ChannelSize = DataSize / ChannelCount;
SampleSize = DataSize / SampleCount;
SampleFormatSize = SampleSize / ChannelCount;
Data = (unsigned char*)av_malloc(DataSize);
}
AudioFrame::~AudioFrame()
{
av_free(Data);
Data = NULL;
}
void AudioFrame::FillFrame(unsigned char** FrameData)
{
if(av_sample_fmt_is_planar(PCMFormat) > 0)
{
// Convert non-interleaved data to interleaved data
// TODO: Is ordering of channels correct?
// [ L L L L R R R R C C C C ] -> [ L R C L R C L R C L R C ]
for(size_t s=0, b=0, so=0; s<SampleCount; s++)
{
so = s*SampleFormatSize;
for(int c=0; c<ChannelCount; c++)
{
for(int f=0; f<SampleFormatSize; f++)
{
// FrameData only holds a maximum of AV_NUM_DATA_POINTERS planes(channels)
if(c < AV_NUM_DATA_POINTERS)
{
Data[b] = FrameData[c][so+f];
}
else
{
Data[b] = 0;
}
b++;
}
}
}
}
else
{
memcpy(Data, FrameData[0], DataSize);
}
}
void AudioFrame::FilterFrameIntersection(int64_t* FilterTimeFrom, int64_t* FilterTimeTo, size_t* p1, size_t* p2)
{
int64_t Endtime = Timecode + Duration;
// TODO (ronny#medium#): verify all conditions for correctness, unit testing?
if(Endtime < *FilterTimeFrom)
{
*p1 = SampleCount;
*p2 = SampleCount;
return; // Outside Before
}
// invalid segment interval
if(*FilterTimeFrom >= *FilterTimeTo)
{
*p2 = SampleCount;
if(Timecode < *FilterTimeFrom)
{
*p1 = SampleCount * (*FilterTimeFrom - Timecode) / Duration;
return; // Inside
}
*p1 = 0;
return; // Intersects @From
}
if(Timecode > *FilterTimeTo)
{
*p1 = 0;
*p2 = 0;
return; // Outside After
}
// this audio packet lies completely inside the filter range
if(Timecode >= *FilterTimeFrom && Endtime <= *FilterTimeTo)
{
*p1 = 0;
*p2 = SampleCount;
return; // Inside
}
if(Timecode <= *FilterTimeFrom && Endtime >= *FilterTimeFrom)
{
*p1 = SampleCount * (*FilterTimeFrom - Timecode) / Duration;
if(Endtime <= *FilterTimeTo)
{
*p2 = SampleCount;
return; // Intersects @From
}
*p2 = SampleCount * (*FilterTimeTo - Timecode) / Duration;
return; // Intersects @From & @To
}
if(Timecode <= *FilterTimeTo && Endtime >= *FilterTimeTo)
{
*p2 = SampleCount * (*FilterTimeTo - Timecode) / Duration;
if(Timecode >= *FilterTimeFrom)
{
*p1 = 0;
return; // Intersects @To
}
*p1 = SampleCount * (*FilterTimeFrom - Timecode) / Duration;
return; // Intersects @From & @To
}
printf("ERROR AudioFrame::FilterFrameIntersection(...): No appropriate audio packet pivots found!\n");
*p1 = 0;
*p2 = SampleCount;
}
void AudioFrame::MuteClipped(int64_t* FilterTimeFrom, int64_t* FilterTimeTo)
{
if(Timecode < *FilterTimeFrom || Timecode + Duration > *FilterTimeTo)
{
size_t PivotFrom;
size_t PivotTo;
FilterFrameIntersection(FilterTimeFrom, FilterTimeTo, &PivotFrom, &PivotTo);
// mute sound between [0...PivotFrom]
memset(Data, 0, PivotFrom * SampleSize);
// keep sound between [PivotFrom...PivotTo]
//memset(...)
// mute sound between [PivotTo...SampleCount]
memset(Data + (PivotTo * SampleSize), 0, (SampleCount - PivotTo) * SampleSize);
}
}
void AudioFrame::Fade(int64_t* FilterTimeFrom, int64_t* FilterTimeTo, FadingType FadeType, FadingCurve FadeCurve)
{
if((FadeType == FadeIn && Timecode < *FilterTimeTo) || (FadeType == FadeOut && Timecode + Duration > *FilterTimeFrom))
{
size_t PivotFrom;
size_t PivotTo;
FilterFrameIntersection(FilterTimeFrom, FilterTimeTo, &PivotFrom, &PivotTo);
if(FadeType == FadeIn)
{
// mute sound between [0...PivotFrom]
memset(Data, 0, PivotFrom * SampleSize);
}
// keep sound between [0...PivotFrom]
// fade sound between [PivotFrom...PivotTo]
// unfortunately we using milli seconds as resolution -> accuracy max. 1ms, but should be sufficient for fading
int64_t ratio_den = *FilterTimeTo - *FilterTimeFrom;
int64_t ratio_num = ratio_den;
short* data_16 = (short*)Data;
int* data_32 = (int*)Data;
float* data_f = (float*)Data;
double* data_d = (double*)Data;
size_t index;
for(size_t sample_index=PivotFrom; sample_index<PivotTo; sample_index++) // loop all samples
{
if(FadeType == FadeIn)
{
ratio_num = Timecode - *FilterTimeFrom + (Duration * (int64_t)sample_index / (int64_t)SampleCount);
}
if(FadeType == FadeOut)
{
ratio_num = Timecode - *FilterTimeTo + (Duration * (int64_t)sample_index / (int64_t)SampleCount);
}
for(size_t c=0; c<(size_t)ChannelCount; c++) // loop all channels
{
// NOTE: non-interleaved (planar) formats can be treated as interleaved data,
// because it was converted during the assignment (FillFrame(*data))
index = sample_index * ChannelCount + c;
if(PCMFormat == AV_SAMPLE_FMT_U8 || PCMFormat == AV_SAMPLE_FMT_U8P)
{
if(FadeCurve == FadeLinear)
{
Data[index] = (unsigned char)(Data[index] * ratio_num / ratio_den);
}
if(FadeCurve == FadeQuadratic)
{
Data[index] = (unsigned char)(Data[index] * ratio_num / ratio_den);
}
}
if(PCMFormat == AV_SAMPLE_FMT_S16 || PCMFormat == AV_SAMPLE_FMT_S16P)
{
if(FadeCurve == FadeLinear)
{
data_16[index] = (short)(data_16[index] * ratio_num / ratio_den);
}
if(FadeCurve == FadeQuadratic)
{
data_16[index] = (short)(data_16[index] * ratio_num / ratio_den);
}
}
if(PCMFormat == AV_SAMPLE_FMT_S32 || PCMFormat == AV_SAMPLE_FMT_S32P)
{
if(FadeCurve == FadeLinear)
{
data_32[index] = (int)(data_32[index] * ratio_num / ratio_den);
}
if(FadeCurve == FadeQuadratic)
{
data_32[index] = (int)(data_32[index] * ratio_num / ratio_den);
}
}
if(PCMFormat == AV_SAMPLE_FMT_FLT || PCMFormat == AV_SAMPLE_FMT_FLTP)
{
if(FadeCurve == FadeLinear)
{
data_f[index] = (float)(data_f[index] * ((float)ratio_num / (float)ratio_den));
}
if(FadeCurve == FadeQuadratic)
{
data_f[index] = (float)(data_f[index] * ((float)ratio_num / (float)ratio_den));
}
}
if(PCMFormat == AV_SAMPLE_FMT_DBL || PCMFormat == AV_SAMPLE_FMT_DBLP)
{
if(FadeCurve == FadeLinear)
{
data_d[index] = (double)(data_d[index] * ((double)ratio_num / (double)ratio_den));
}
if(FadeCurve == FadeQuadratic)
{
data_d[index] = (double)(data_d[index] * ((double)ratio_num / (double)ratio_den));
}
}
}
}
data_16 = NULL;
data_32 = NULL;
data_f = NULL;
data_d = NULL;
if(FadeType == FadeOut)
{
// mute sound between [PivotTo...SampleCount]
memset(Data + (PivotTo * SampleSize), 0, (SampleCount - PivotTo) * SampleSize);
}
// keep sound between [PivotTo...SampleCount]
}
}
void AudioFrame::MixDown()
{
if(ChannelCount > 2)
{
short* data_16 = (short*)Data;
int* data_32 = (int*)Data;
float* data_f = (float*)Data;
double* data_d = (double*)Data;
size_t index;
size_t index_center_channel;
for(size_t sample_index=0; sample_index<SampleCount; sample_index++) // loop all samples
{
// NOTE: non-interleaved (planar) formats can be treated as interleaved data,
// because it was converted during the assignment (FillFrame(*data))
index = sample_index*ChannelCount;
// NOTE: Order of interleaved channels -> Front_L, Front_R, Center, LowFreq, Side_L, Side_R, Back_L, Back_R
index_center_channel = 2;
if(PCMFormat == AV_SAMPLE_FMT_U8 || PCMFormat == AV_SAMPLE_FMT_U8P)
{
Data[index+0] = (unsigned char)((Data[index+0] + Data[index+index_center_channel]) / 2); // center ++> left
Data[index+1] = (unsigned char)((Data[index+1] + Data[index+index_center_channel]) / 2); // center ++> right
}
if(PCMFormat == AV_SAMPLE_FMT_S16 || PCMFormat == AV_SAMPLE_FMT_S16P)
{
data_16[index+0] = (short)((data_16[index+0] + data_16[index+index_center_channel]) / 2); // center ++> left
data_16[index+1] = (short)((data_16[index+1] + data_16[index+index_center_channel]) / 2); // center ++> right
}
if(PCMFormat == AV_SAMPLE_FMT_S32 || PCMFormat == AV_SAMPLE_FMT_S32P)
{
data_32[index+0] = (int)((data_32[index+0] + data_32[index+index_center_channel]) / 2); // center ++> left
data_32[index+1] = (int)((data_32[index+1] + data_32[index+index_center_channel]) / 2); // center ++> right
}
if(PCMFormat == AV_SAMPLE_FMT_FLT || PCMFormat == AV_SAMPLE_FMT_FLTP)
{
data_f[index+0] = (float)((data_f[index+0] + data_f[index+index_center_channel]) / 2); // center ++> left
data_f[index+1] = (float)((data_f[index+1] + data_f[index+index_center_channel]) / 2); // center ++> right
}
if(PCMFormat == AV_SAMPLE_FMT_DBL || PCMFormat == AV_SAMPLE_FMT_DBLP)
{
data_d[index+0] = (double)((data_d[index+0] + data_d[index+index_center_channel]) / 2); // center ++> left
data_d[index+1] = (double)((data_d[index+1] + data_d[index+index_center_channel]) / 2); // center ++> right
}
}
data_16 = NULL;
data_32 = NULL;
data_f = NULL;
data_d = NULL;
}
}
| 37.605769 | 191 | 0.534987 | SolarAquarion |
2078ab0a8052b643b6f058bef4387d0a4ecf618f | 44,530 | cpp | C++ | src/C++/Descriptors/Descriptors.cpp | cesmix-mit/MDP | 746e4f4aead5911ddeda77b0d2c117e3b70cc5c4 | [
"MIT"
] | 1 | 2021-09-15T03:09:46.000Z | 2021-09-15T03:09:46.000Z | src/C++/Descriptors/Descriptors.cpp | cesmix-mit/MDP | 746e4f4aead5911ddeda77b0d2c117e3b70cc5c4 | [
"MIT"
] | 1 | 2022-01-24T16:11:07.000Z | 2022-01-24T16:11:07.000Z | src/C++/Descriptors/Descriptors.cpp | cesmix-mit/MDP | 746e4f4aead5911ddeda77b0d2c117e3b70cc5c4 | [
"MIT"
] | null | null | null | /***************************************************************************
Molecular Dynamics Potentials (MDP)
CESMIX-MIT Project
Contributing authors: Ngoc-Cuong Nguyen (cuongng@mit.edu, exapde@gmail.com)
***************************************************************************/
#ifndef __DESCRIPTORS
#define __DESCRIPTORS
#include "snappotential.cpp"
void InitSphericalHarmonics(shstruct &sh, commonstruct &common)
{
// L the maximum degree of spherical harmonics
// K the number of zeros of spherical Bessel functions
// Nub number of non-zero unqiue bispectrum compoments of spherical harmonics
// Ncg the total number of non-zero Clebsch-Gordan coefficients
// backend computing platform
Int L = common.L;
Int K = common.K;
Int backend = common.backend;
Int Nub;// number of non-zero unqiue bispectrum compoments of spherical harmonics
Int Ncg;// the total number of non-zero Clebsch-Gordan coefficients
Int M = (L+1)*(L+2)/2;
Int L2 = (L+1)*(L+1);
Int K2 = K*(K+1);
// factorial table
dstype fac[168];
for (Int i=0; i<168; i++)
fac[i] = (dstype) factable[i];
// get index pairs (k2, k1) with k2 <= k1
Int indk[K2];
cpuGetIndk(indk, K);
dstype f[L+1];
dstype P[M];
dstype tmp[M];
dstype df[L+1];
dstype dP[M];
dstype dtmp[M];
// x, y, z
Int N = 100;
string filein = "spherecoords.bin";
ifstream in(filein.c_str(), ios::in | ios::binary);
if (!in)
error("Unable to open file " + filein);
dstype *sph;
readarray(in, &sph, N*3);
in.close();
dstype *the = &sph[0];
dstype *phi = &sph[N];
dstype *r = &sph[2*N];
dstype x[N];
dstype y[N];
dstype z[N];
cpuSphere2Cart(x, y, z, the, phi, r, N);
dstype Ylmr[L2];
dstype Ylmi[L2];
dstype b[L2*(L+1)];
cpuSphericalHarmonicsAtomSum(Ylmr, Ylmi, x, y, z, P, tmp, fac, M_PI, L, N);
cpuSphericalHarmonicsBispectrum(b, Ylmr, Ylmi, fac, L);
// compute non-zero Clebsch-Gordan coefficients
Nub = cpuSphericalHarmonicsBispectrumIndex(b, L);
Int indl[Nub*3];
cpuSphericalHarmonicsBispectrumIndex(indl, b, Nub, L);
Ncg = cgcoefficients(indl, Nub);
Int indm[Ncg*3];
Int rowm[Nub+1];
dstype cg[Ncg];
cgcoefficients(cg, indm, rowm, indl, fac, Ncg, Nub);
// roots of spherical Bessel functions
string filename = "besselzeros.bin";
ifstream fin(filename.c_str(), ios::in | ios::binary);
if (!fin)
error("Unable to open file " + filename);
dstype *bzeros;
readarray(fin, &bzeros, 25*20);
fin.close();
dstype x0[(L+1)*K];
for (int k=0; k<K; k++)
for (int l=0; l<(L+1); l++)
x0[k*(L+1) + l] = bzeros[k*25 + l]/common.rcutml;
//printArray2D(x0, (1+L), K, backend);
//cout<<common.rcutml<<endl;
//sh.freememory(backend);
// allocate memory for sh struct
TemplateMalloc(&sh.indk, K2, backend);
TemplateMalloc(&sh.indl, Nub*3, backend);
TemplateMalloc(&sh.indm, Ncg*3, backend);
TemplateMalloc(&sh.rowm, Nub+1, backend);
TemplateMalloc(&sh.cg, Ncg, backend);
TemplateMalloc(&sh.fac, 168, backend);
TemplateMalloc(&sh.x0, (L+1)*K, backend);
TemplateMalloc(&sh.f, (L+1), backend);
TemplateMalloc(&sh.P, M, backend);
TemplateMalloc(&sh.tmp, M, backend);
TemplateMalloc(&sh.df, (L+1), backend);
TemplateMalloc(&sh.dP, M, backend);
TemplateMalloc(&sh.dtmp, M, backend);
// copy data to sh struct
if (backend==2) { // GPU
#ifdef HAVE_CUDA
CUDA_CHECK( cudaMemcpy(sh.indk, indk, K2*sizeof(Int), cudaMemcpyHostToDevice ) );
CUDA_CHECK( cudaMemcpy(sh.indl, indl, Nub*3*sizeof(Int), cudaMemcpyHostToDevice ) );
CUDA_CHECK( cudaMemcpy(sh.indm, indm, Ncg*3*sizeof(Int), cudaMemcpyHostToDevice ) );
CUDA_CHECK( cudaMemcpy(sh.rowm, rowm, (Nub+1)*sizeof(Int), cudaMemcpyHostToDevice ) );
CUDA_CHECK( cudaMemcpy(sh.x0, x0, ((L+1)*K)*sizeof(dstype), cudaMemcpyHostToDevice ) );
CUDA_CHECK( cudaMemcpy(sh.cg, cg, Ncg*sizeof(dstype), cudaMemcpyHostToDevice ) );
CUDA_CHECK( cudaMemcpy(sh.fac, fac, 168*sizeof(dstype), cudaMemcpyHostToDevice ) );
#endif
}
else { // CPU
for (int i=0; i<K2; i++)
sh.indk[i] = indk[i];
for (int i=0; i<Nub*3; i++)
sh.indl[i] = indl[i];
for (int i=0; i<Ncg*3; i++)
sh.indm[i] = indm[i];
for (int i=0; i<=Nub; i++)
sh.rowm[i] = rowm[i];
for (int i=0; i<(L+1)*K; i++)
sh.x0[i] = x0[i];
for (int i=0; i<Ncg; i++)
sh.cg[i] = cg[i];
for (int i=0; i<168; i++)
sh.fac[i] = fac[i];
}
common.Nub = Nub;// number of non-zero unqiue bispectrum compoments of spherical harmonics
common.Ncg = Ncg;// the total number of non-zero Clebsch-Gordan coefficients
if (common.descriptor==0) {
Int Nub = common.Nub;
if (common.spectrum==0) { // power spectrum
common.Nbf = (L+1)*K*(K+1)/2; // number of power components
common.Npower = (L+1)*K*(K+1)/2; // number of power components
common.Nbispectrum = 0;
}
else if (common.spectrum==1) { // bispectrum
common.Nbf = Nub*K*(K+1)/2; // number of bispectrum components
common.Npower = 0;
common.Nbispectrum = Nub*K*(K+1)/2; // number of bispectrum components
}
else if (common.spectrum==2) { // power spectrum and bispectrum
common.Npower = (L+1)*K*(K+1)/2; // number of power components
common.Nbispectrum = Nub*K*(K+1)/2; // number of bispectrum components
common.Nbf = common.Npower + common.Nbispectrum;
}
else {
}
}
if (common.chemtype == 0)
common.Ncoeff = common.Nbf*common.natomtypes;
else
common.Ncoeff = common.Nbf*common.natomtypes*common.natomtypes;
sh.L= common.L;
sh.K= common.K;
sh.Nub= common.Nub;
sh.Ncg= common.Ncg;
sh.npower= common.Npower;
sh.nbispectrum= common.Nbispectrum;
sh.nbasis= common.Nbf;
//cout<<common.L<<" "<<common.K<<" "<<common.Nub<<" "<<common.Ncg<<" "<<common.Npower<<" "<<common.Nbispectrum<<" "<<common.Nbf<<" "<<common.Ncoeff<<endl;
}
void SphericalHarmonicBesselDescriptors(dstype *e, neighborstruct &nb, commonstruct &common, appstruct &app, tempstruct &tmp,
shstruct &sh, dstype* x, dstype *q, dstype* param, dstype *rcutsq, Int *atomtype, Int nparam, Int typei, Int typej, Int decomp)
{
Int Nbf = common.Nbf;
Int ncq = 0;
for (Int b=0; b<common.nba; b++) {
Int e1 = common.ablks[b];
Int e2 = common.ablks[b+1];
Int na = e2 - e1; // number of atoms in this block
Int neighmax = common.neighmax;
Int dim = common.dim;
Int backend = common.backend;
Int *ilist = &tmp.intmem[0]; //na
if (typei>0) {
Int *olist = &tmp.intmem[na]; //na
ArrayFill(olist, e1, na, backend);
Int *t0 = &tmp.intmem[2*na]; //na
Int *t1 = &tmp.intmem[3*na]; //na
na = FindAtomType(ilist, olist, atomtype, t0, t1, typei, na, backend);
}
else {
ArrayFill(ilist, e1, na, backend);
}
Int *pairnum = &tmp.intmem[na]; // na
Int *pairlist = &tmp.intmem[2*na]; // na*neighmax
if (typej>0)
FullNeighPairList(pairnum, pairlist, x, rcutsq, atomtype, ilist, nb.alist, nb.neighlist, nb.neighnum, na, neighmax, typej, dim, backend);
else
FullNeighPairList(pairnum, pairlist, x, rcutsq, ilist, nb.neighlist, nb.neighnum, na, neighmax, dim, backend);
//a list contains the starting positions of the first neighbor
Int *pairnumsum = &tmp.intmem[2*na+na*neighmax]; // na+1
//cpuCumsum(pairnumsum, pairnum, na+1);
Cumsum(pairnumsum, pairnum, &tmp.intmem[3*na+na*neighmax+1], &tmp.intmem[4*na+na*neighmax+2], na+1, backend);
int ntuples = IntArrayGetValueAtIndex(pairnumsum, na, backend);
Int *ai = &tmp.intmem[1+3*na+na*neighmax]; // ntuples
Int *aj = &tmp.intmem[1+3*na+ntuples+na*neighmax]; // ntuples
Int *ti = &tmp.intmem[1+3*na+2*ntuples+na*neighmax]; // ntuples
Int *tj = &tmp.intmem[1+3*na+3*ntuples+na*neighmax]; // ntuples
//dstype *xij = &tmp.tmpmem[0]; // ntuples*dim
Int nbasis = common.K*(common.L+1)*(common.L+1);
dstype *xij = &tmp.tmpmem[2*na*nbasis+ntuples*(2*nbasis)]; // ntuples*dim
dstype *qi;
dstype *qj;
NeighPairs(xij, qi, qj, x, q, ai, aj, ti, tj, pairnum, pairlist, pairnumsum, ilist, nb.alist,
atomtype, na, neighmax, ncq, dim, backend);
dstype *cr = &tmp.tmpmem[0]; // na*nbasis
dstype *ci = &tmp.tmpmem[na*nbasis]; // na*nbasis
dstype *sr = &tmp.tmpmem[2*na*nbasis]; // ntuples*nbasis
dstype *si = &tmp.tmpmem[2*na*nbasis+ntuples*(1*nbasis)]; // ntuples*nbasis
SphericalHarmonicsBessel(sr, si, xij, sh.x0, sh.P, sh.tmp, sh.f,
sh.fac, M_PI, common.L, common.K, ntuples, backend);
dstype *ei = &tmp.tmpmem[2*na*nbasis+ntuples*(2*nbasis)]; // na * Nbf
RadialSphericalHarmonicsSpectrum(ei, cr, ci, sr, si, sh.cg, sh.indk, sh.indl, sh.indm,
sh.rowm, pairnumsum, common.Nub, common.Ncg, na, common.L, common.K, common.spectrum, backend);
// ei : na x Nbf, onevec : na x 1, e : Nbf x 1
// e = e + ei^T*onevec
dstype *onevec = &tmp.tmpmem[0]; // na
ArraySetValue(onevec, 1.0, na, common.backend);
PGEMTV(common.cublasHandle, na, Nbf, &one, ei, na, onevec, inc1, &one, e, inc1, common.backend);
}
}
void implSphericalHarmonicBesselDescriptors(dstype *e, neighborstruct &nb, commonstruct &common,
appstruct &app, tempstruct &tmp, shstruct &sh, dstype* x, dstype *q, dstype* param, Int nparam)
{
//ArraySetValue(e, 0.0, common.Ncoeff, common.backend);
// ArraySetValue(f, 0.0, common.dim*common.inum*common.Ncoeff, common.backend);
Int natomtypes = common.natomtypes;
if (natomtypes==1) {
SphericalHarmonicBesselDescriptors(e, nb, common, app, tmp, sh, x, q, param, &app.rcutsqml[0],
nb.atomtype, nparam, 0, 0, common.decomposition);
}
else {
Int Nbf = common.Nbf;
Int inum = common.inum;
if (common.chemtype == 0) {
for (int i = 0; i < natomtypes; i++)
SphericalHarmonicBesselDescriptors(&e[i*Nbf], nb, common, app, tmp, sh,
x, q, param, &app.rcutsqml[0], nb.atomtype, nparam, i+1, 0, common.decomposition);
}
else {
for (int i = 0; i < natomtypes; i++)
for (int j = 0; j < natomtypes; j++)
SphericalHarmonicBesselDescriptors(&e[(j+i*natomtypes)*Nbf], nb, common, app, tmp, sh, x, q,
param, &app.rcutsqml[0], nb.atomtype, nparam, i+1, j+1, common.decomposition);
}
}
}
void SphericalHarmonicBesselDescriptors(dstype *e, dstype *f, neighborstruct &nb, commonstruct &common, appstruct &app, tempstruct &tmp,
shstruct &sh, dstype* x, dstype *q, dstype* param, dstype *rcutsq, Int *atomtype, Int nparam, Int typei, Int typej, Int decomp)
{
Int Nbf = common.Nbf;
Int ncq = 0;
INIT_TIMING;
for (Int b=0; b<common.nba; b++) {
Int e1 = common.ablks[b];
Int e2 = common.ablks[b+1];
Int na = e2 - e1; // number of atoms in this block
Int neighmax = common.neighmax;
Int dim = common.dim;
Int backend = common.backend;
START_TIMING;
Int *ilist = &tmp.intmem[0]; //na
if (typei>0) {
Int *olist = &tmp.intmem[na]; //na
ArrayFill(olist, e1, na, backend);
Int *t0 = &tmp.intmem[2*na]; //na
Int *t1 = &tmp.intmem[3*na]; //na
na = FindAtomType(ilist, olist, atomtype, t0, t1, typei, na, backend);
}
else {
ArrayFill(ilist, e1, na, backend);
}
Int *pairnum = &tmp.intmem[na]; // na
Int *pairlist = &tmp.intmem[2*na]; // na*neighmax
if (typej>0)
FullNeighPairList(pairnum, pairlist, x, rcutsq, atomtype, ilist, nb.alist, nb.neighlist, nb.neighnum, na, neighmax, typej, dim, backend);
else
FullNeighPairList(pairnum, pairlist, x, rcutsq, ilist, nb.neighlist, nb.neighnum, na, neighmax, dim, backend);
//printArray2D(nb.neighnum, 1, na, common.backend);
//a list contains the starting positions of the first neighbor
Int *pairnumsum = &tmp.intmem[2*na+na*neighmax]; // na+1
//cpuCumsum(pairnumsum, pairnum, na+1);
Cumsum(pairnumsum, pairnum, &tmp.intmem[3*na+na*neighmax+1], &tmp.intmem[4*na+na*neighmax+2], na+1, backend);
int ntuples = IntArrayGetValueAtIndex(pairnumsum, na, common.backend);
END_TIMING(50);
START_TIMING;
Int *ai = &tmp.intmem[1+3*na+na*neighmax]; // ntuples
Int *aj = &tmp.intmem[1+3*na+ntuples+na*neighmax]; // ntuples
Int *ti = &tmp.intmem[1+3*na+2*ntuples+na*neighmax]; // ntuples
Int *tj = &tmp.intmem[1+3*na+3*ntuples+na*neighmax]; // ntuples
//dstype *xij = &tmp.tmpmem[0]; // ntuples*dim
Int nbasis = common.K*(common.L+1)*(common.L+1);
dstype *xij = &tmp.tmpmem[2*na*nbasis+ntuples*(8*nbasis)]; // ntuples*dim
dstype *qi;
dstype *qj;
NeighPairs(xij, qi, qj, x, q, ai, aj, ti, tj, pairnum, pairlist, pairnumsum, ilist, nb.alist,
atomtype, na, neighmax, ncq, dim, backend);
END_TIMING(51);
START_TIMING;
dstype *cr = &tmp.tmpmem[0]; // na*nbasis
dstype *ci = &tmp.tmpmem[na*nbasis]; // na*nbasis
dstype *srx = &tmp.tmpmem[2*na*nbasis]; // ntuples*nbasis
dstype *sry = &tmp.tmpmem[2*na*nbasis+ntuples*(1*nbasis)]; // ntuples*nbasis
dstype *srz = &tmp.tmpmem[2*na*nbasis+ntuples*(2*nbasis)]; // ntuples*nbasis
dstype *six = &tmp.tmpmem[2*na*nbasis+ntuples*(3*nbasis)]; // ntuples*nbasis
dstype *siy = &tmp.tmpmem[2*na*nbasis+ntuples*(4*nbasis)]; // ntuples*nbasis
dstype *siz = &tmp.tmpmem[2*na*nbasis+ntuples*(5*nbasis)]; // ntuples*nbasis
dstype *sr = &tmp.tmpmem[2*na*nbasis+ntuples*(6*nbasis)]; // ntuples*nbasis
dstype *si = &tmp.tmpmem[2*na*nbasis+ntuples*(7*nbasis)]; // ntuples*nbasis
SphericalHarmonicsBesselWithDeriv(sr, si, srx, six, sry, siy, srz, siz, xij,
sh.x0, sh.P, sh.tmp, sh.f, sh.dP, sh.dtmp, sh.df, sh.fac, M_PI, common.L, common.K, ntuples, backend);
END_TIMING(52);
// string fn0 = (common.backend == 2) ? "srgpu.bin" : "srcpu.bin";
// writearray2file(fn0, sr, ntuples*nbasis, common.backend);
// fn0 = (common.backend == 2) ? "sigpu.bin" : "sicpu.bin";
// writearray2file(fn0, si, ntuples*nbasis, common.backend);
// fn0 = (common.backend == 2) ? "xijgpu.bin" : "xijcpu.bin";
// writearray2file(fn0, xij, ntuples*dim, common.backend);
// #ifdef HAVE_CHECK // check
// dstype epsil = 1e-6;
// dstype *sr1 = new dstype[ntuples*nbasis];
// dstype *si1 = new dstype[ntuples*nbasis];
// dstype *xi1 = new dstype[ntuples*dim];
// dstype *xii = new dstype[ntuples*dim];
// dstype *ei1 = new dstype[na*Nbf];
// dstype *onev = new dstype[na];
// dstype *et = new dstype[Nbf];
// cpuArrayCopy(xii, xij, dim*ntuples);
// cpuArrayCopy(xi1, xij, dim*ntuples);
// ArraySetValue(onev, 1.0, na, common.backend);
//
// cpuArrayRowkAXPB(xi1, xij, 1.0, epsil, dim, ntuples, 0);
// cpuSphericalHarmonicsBessel(sr1, si1, xi1, sh.x0, sh.P, sh.tmp, sh.f,
// sh.fac, M_PI, common.L, common.K, ntuples);
// cpuArrayAXPBY(sr1, sr1, sr, 1.0/epsil, -1.0/epsil, ntuples*nbasis);
// cpuArrayAXPBY(sr1, sr1, srx, 1.0, -1.0, ntuples*nbasis);
// cpuArrayAbs(sr1, sr1, ntuples*nbasis);
// cout<<"Maximum absolute error: "<<cpuArrayMax(sr1, ntuples*nbasis)<<endl;
//
// cpuArrayCopy(xi1, xij, dim*ntuples);
// cpuArrayRowkAXPB(xi1, xij, 1.0, epsil, dim, ntuples, 1);
// cpuSphericalHarmonicsBessel(sr1, si1, xi1, sh.x0, sh.P, sh.tmp, sh.f,
// sh.fac, M_PI, common.L, common.K, ntuples);
// cpuArrayAXPBY(sr1, sr1, sr, 1.0/epsil, -1.0/epsil, ntuples*nbasis);
// cpuArrayAXPBY(sr1, sr1, sry, 1.0, -1.0, ntuples*nbasis);
// cpuArrayAbs(sr1, sr1, ntuples*nbasis);
// cout<<"Maximum absolute error: "<<cpuArrayMax(sr1, ntuples*nbasis)<<endl;
//
// cpuArrayCopy(xi1, xij, dim*ntuples);
// cpuArrayRowkAXPB(xi1, xij, 1.0, epsil, dim, ntuples, 2);
// cpuSphericalHarmonicsBessel(sr1, si1, xi1, sh.x0, sh.P, sh.tmp, sh.f,
// sh.fac, M_PI, common.L, common.K, ntuples);
// cpuArrayAXPBY(sr1, sr1, sr, 1.0/epsil, -1.0/epsil, ntuples*nbasis);
// cpuArrayAXPBY(sr1, sr1, srz, 1.0, -1.0, ntuples*nbasis);
// cpuArrayAbs(sr1, sr1, ntuples*nbasis);
// cout<<"Maximum absolute error: "<<cpuArrayMax(sr1, ntuples*nbasis)<<endl;
// #endif
START_TIMING;
dstype *ei = &tmp.tmpmem[2*na*nbasis+ntuples*(8*nbasis)]; // na * Nbf
RadialSphericalHarmonicsSpectrum(ei, cr, ci, sr, si, sh.cg, sh.indk, sh.indl, sh.indm,
sh.rowm, pairnumsum, common.Nub, common.Ncg, na, common.L, common.K, common.spectrum, backend);
// ei : na x Nbf, onevec : na x 1, e : Nbf x 1
// e = e + ei^T*onevec
dstype *onevec = &tmp.tmpmem[2*na*nbasis+ntuples*(6*nbasis)]; // na
ArraySetValue(onevec, one, na, common.backend);
PGEMTV2(common.cublasHandle, na, Nbf, &one, ei, na, onevec, inc1, &one, e, inc1, common.backend);
END_TIMING(53);
// string fn1 = (common.backend == 2) ? "eigpu.bin" : "eicpu.bin";
// writearray2file(fn1, ei, na*Nbf, common.backend);
// fn1 = (common.backend == 2) ? "egpu.bin" : "ecpu.bin";
// writearray2file(fn1, e, Nbf, common.backend);
//fn1 = (common.backend == 2) ? "ogpu.bin" : "ocpu.bin";
//writearray2file(fn1, onevec, na, common.backend);
START_TIMING;
dstype *fij = &tmp.tmpmem[2*na*nbasis+ntuples*(6*nbasis)]; // dim * ntuples * Nbf
// RadialSphericalHarmonicsSpectrumDeriv(fij, cr, ci, srx, six, sry, siy, srz, siz, sh.cg, sh.indk,
// sh.indl, sh.indm, sh.rowm, pairnumsum, common.Nub, common.Ncg, na, common.L, common.K, common.spectrum, backend);
RadialSphericalHarmonicsSpectrumDeriv(fij, cr, ci, srx, six, sry, siy, srz, siz, sh.cg, sh.indk,
sh.indl, sh.indm, sh.rowm, ai, pairnumsum, common.Nub, common.Ncg, na, ntuples, common.L, common.K, common.spectrum, backend);
END_TIMING(54);
// fn1 = (common.backend == 2) ? "fijgpu.bin" : "fijcpu.bin";
// writearray2file(fn1, fij, dim*ntuples*Nbf, common.backend);
// error("here");
// #ifdef HAVE_CHECK // check
// for (int i = 0; i<dim*ntuples; i++) {
// cpuArrayCopy(xi1, xii, dim*ntuples);
// xi1[i] = xi1[i] + epsil;
// cpuSphericalHarmonicsBessel(sr1, si1, xi1, sh.x0, sh.P, sh.tmp, sh.f,
// sh.fac, M_PI, common.L, common.K, ntuples);
//
// cpuRadialSphericalHarmonicsSpectrum(ei1, cr, ci, sr1, si1, sh.cg, sh.indk, sh.indl, sh.indm,
// sh.rowm, pairnumsum, common.Nub, common.Ncg, na, common.L, common.K, common.spectrum);
//
// PGEMTV(common.cublasHandle, na, Nbf, &one, ei1, na, onev, inc1, &zero, et, inc1, common.backend);
// printArray2D(e, 1, Nbf, common.backend);
// printArray2D(et, 1, Nbf, common.backend);
// for (int j=0; j<Nbf; j++)
// et[j] = fabs((et[j]-e[j])/epsil - fij[i + dim*ntuples*j]);
// cout<<"Maximum absolute error: "<<cpuArrayMax(et, Nbf)<<endl;
// }
// delete[] sr1;
// delete[] si1;
// delete[] xi1;
// delete[] xii;
// delete[] ei1;
// delete[] onev;
// delete[] et;
// error("here");
// #endif
START_TIMING;
if (decomp==0)
ForceDecomposition(f, fij, ai, aj, common.inum, ntuples, Nbf, backend);
else {
CenterAtomDecomposition(f, fij, ilist, pairnumsum, common.inum, ntuples, na, Nbf, backend);
ArrayCopy(tmp.intmem, aj, ntuples, backend);
Int *jlist = &tmp.intmem[ntuples];
Int *bnumsum = &tmp.intmem[2*ntuples];
Int *index = &tmp.intmem[3*ntuples]; // ntuples
Int *p0 = &tmp.intmem[4*ntuples]; // ntuples
Int *p1 = &tmp.intmem[5*ntuples]; // ntuples
Int *p2 = &tmp.intmem[6*ntuples]; // ntuples
Int *p3 = &tmp.intmem[7*ntuples]; // ntuples
Int naj = UniqueSort(jlist, bnumsum, index, p0, tmp.intmem, p1, p2, p3, ntuples, backend);
NeighborAtomDecomposition(f, fij, jlist, bnumsum, index, common.inum, ntuples, naj, Nbf, backend);
}
END_TIMING(55);
}
#ifdef HAVE_DEBUG
string fn = (common.backend == 2) ? "dgpu.bin" : "dcpu.bin";
writearray2file(fn, e, Nbf, common.backend);
fn = (common.backend == 2) ? "ddgpu.bin" : "ddcpu.bin";
writearray2file(fn, f, common.inum*Nbf, common.backend);
//error("here");
#endif
}
void implSphericalHarmonicBesselDescriptors(dstype *e, dstype *f, neighborstruct &nb, commonstruct &common,
appstruct &app, tempstruct &tmp, shstruct &sh, dstype* x, dstype *q, dstype* param, Int nparam)
{
//ArraySetValue(e, 0.0, common.Ncoeff, common.backend);
// ArraySetValue(f, 0.0, common.dim*common.inum*common.Ncoeff, common.backend);
Int natomtypes = common.natomtypes;
if (natomtypes==1) {
SphericalHarmonicBesselDescriptors(e, f, nb, common, app, tmp, sh, x, q, param, &app.rcutsqml[0],
nb.atomtype, nparam, 0, 0, common.decomposition);
}
else {
Int Nbf = common.Nbf;
Int inum = common.inum;
if (common.chemtype == 0) {
for (int i = 0; i < natomtypes; i++)
SphericalHarmonicBesselDescriptors(&e[i*Nbf], &f[i*3*inum*Nbf], nb, common, app, tmp, sh,
x, q, param, &app.rcutsqml[0], nb.atomtype, nparam, i+1, 0, common.decomposition);
}
else {
for (int i = 0; i < natomtypes; i++)
for (int j = 0; j < natomtypes; j++)
SphericalHarmonicBesselDescriptors(&e[(j+i*natomtypes)*Nbf], &f[(j+i*natomtypes)*3*inum*Nbf], nb, common, app, tmp, sh, x, q,
param, &app.rcutsqml[0], nb.atomtype, nparam, i+1, j+1, common.decomposition);
}
}
}
void SphericalHarmonicBesselEnergyForce(dstype *e, dstype *f, neighborstruct &nb, commonstruct &common, appstruct &app, tempstruct &tmp,
shstruct &sh, dstype* x, dstype *coeff, dstype *q, dstype* param, dstype *rcutsq, Int *atomtype, Int nparam, Int typei, Int typej, Int decomp)
{
Int Nbf = common.Nbf;
Int ncq = 0;
for (Int b=0; b<common.nba; b++) {
Int e1 = common.ablks[b];
Int e2 = common.ablks[b+1];
Int na = e2 - e1; // number of atoms in this block
Int neighmax = common.neighmax;
Int dim = common.dim;
Int backend = common.backend;
Int *ilist = &tmp.intmem[0]; //na
if (typei>0) {
Int *olist = &tmp.intmem[na]; //na
ArrayFill(olist, e1, na, backend);
Int *t0 = &tmp.intmem[2*na]; //na
Int *t1 = &tmp.intmem[3*na]; //na
na = FindAtomType(ilist, olist, atomtype, t0, t1, typei, na, backend);
}
else {
ArrayFill(ilist, e1, na, backend);
}
Int *pairnum = &tmp.intmem[na]; // na
Int *pairlist = &tmp.intmem[2*na]; // na*neighmax
if (typej>0)
FullNeighPairList(pairnum, pairlist, x, rcutsq, atomtype, ilist, nb.alist, nb.neighlist, nb.neighnum, na, neighmax, typej, dim, backend);
else
FullNeighPairList(pairnum, pairlist, x, rcutsq, ilist, nb.neighlist, nb.neighnum, na, neighmax, dim, backend);
//a list contains the starting positions of the first neighbor
Int *pairnumsum = &tmp.intmem[2*na+na*neighmax]; // na+1
Cumsum(pairnumsum, pairnum, &tmp.intmem[3*na+na*neighmax+1], &tmp.intmem[4*na+na*neighmax+2], na+1, backend);
int ntuples = IntArrayGetValueAtIndex(pairnumsum, na, common.backend);
Int *ai = &tmp.intmem[1+3*na+na*neighmax]; // ntuples
Int *aj = &tmp.intmem[1+3*na+ntuples+na*neighmax]; // ntuples
Int *ti = &tmp.intmem[1+3*na+2*ntuples+na*neighmax]; // ntuples
Int *tj = &tmp.intmem[1+3*na+3*ntuples+na*neighmax]; // ntuples
//dstype *xij = &tmp.tmpmem[0]; // ntuples*dim
Int nbasis = common.K*(common.L+1)*(common.L+1);
dstype *xij = &tmp.tmpmem[2*na*nbasis+ntuples*(8*nbasis)]; // ntuples*dim
dstype *qi;
dstype *qj;
NeighPairs(xij, qi, qj, x, q, ai, aj, ti, tj, pairnum, pairlist, pairnumsum, ilist, nb.alist,
atomtype, na, neighmax, ncq, dim, backend);
// #ifdef HAVE_CHECK
// dstype *xi1 = new dstype[ntuples*dim];
// dstype *xii = new dstype[ntuples*dim];
// cpuArrayCopy(xii, xij, dim*ntuples);
// cpuArrayCopy(xi1, xij, dim*ntuples);
// #endif
dstype *cr = &tmp.tmpmem[0]; // na*nbasis
dstype *ci = &tmp.tmpmem[na*nbasis]; // na*nbasis
dstype *srx = &tmp.tmpmem[2*na*nbasis]; // ntuples*nbasis
dstype *sry = &tmp.tmpmem[2*na*nbasis+ntuples*(1*nbasis)]; // ntuples*nbasis
dstype *srz = &tmp.tmpmem[2*na*nbasis+ntuples*(2*nbasis)]; // ntuples*nbasis
dstype *six = &tmp.tmpmem[2*na*nbasis+ntuples*(3*nbasis)]; // ntuples*nbasis
dstype *siy = &tmp.tmpmem[2*na*nbasis+ntuples*(4*nbasis)]; // ntuples*nbasis
dstype *siz = &tmp.tmpmem[2*na*nbasis+ntuples*(5*nbasis)]; // ntuples*nbasis
dstype *sr = &tmp.tmpmem[2*na*nbasis+ntuples*(6*nbasis)]; // ntuples*nbasis
dstype *si = &tmp.tmpmem[2*na*nbasis+ntuples*(7*nbasis)]; // ntuples*nbasis
SphericalHarmonicsBesselWithDeriv(sr, si, srx, six, sry, siy, srz, siz, xij,
sh.x0, sh.P, sh.tmp, sh.f, sh.dP, sh.dtmp, sh.df, sh.fac, M_PI, common.L, common.K, ntuples, backend);
dstype *di = &tmp.tmpmem[2*na*nbasis+ntuples*(8*nbasis)]; // na * Nbf
RadialSphericalHarmonicsSpectrum(di, cr, ci, sr, si, sh.cg, sh.indk,
sh.indl, sh.indm, sh.rowm, pairnumsum, common.Nub, common.Ncg, na, common.L, common.K, common.spectrum, backend);
// di : na x Nbf, coeff : Nbf x 1, ei : na x 1
// ei = di*coeff
dstype *ei = &tmp.tmpmem[2*na*nbasis+ntuples*(6*nbasis)]; // na
PGEMNV(common.cublasHandle, na, Nbf, &one, di, na, coeff, inc1, &zero, ei, inc1, common.backend);
CenterAtomDecomposition(e, ei, ilist, na, backend);
dstype *dd = &tmp.tmpmem[2*na*nbasis+ntuples*(6*nbasis)]; // dim * ntuples * Nbf
RadialSphericalHarmonicsSpectrumDeriv(dd, cr, ci, srx, six, sry, siy, srz, siz, sh.cg, sh.indk,
sh.indl, sh.indm, sh.rowm, pairnumsum, common.Nub, common.Ncg, na, common.L, common.K, common.spectrum, backend);
dstype *fij = &tmp.tmpmem[0]; // dim * ntuples
PGEMNV(common.cublasHandle, dim*ntuples, Nbf, &minusone, dd, dim*ntuples, coeff, inc1, &zero, fij, inc1, common.backend);
// #ifdef HAVE_CHECK
// dstype en = cpuArraySum(e, na);
// dstype epsil = 1e-6;
// dstype *sr1 = new dstype[ntuples*nbasis];
// dstype *si1 = new dstype[ntuples*nbasis];
// dstype *cr1 = new dstype[na*nbasis];
// dstype *ci1 = new dstype[na*nbasis];
// dstype *ei1 = new dstype[na*Nbf];
// dstype *onev = new dstype[na];
// dstype *et = new dstype[Nbf];
// ArraySetValue(onev, 1.0, na, common.backend);
// for (int i = 0; i<dim*ntuples; i++) {
// cpuArrayCopy(xi1, xii, dim*ntuples);
// xi1[i] = xi1[i] + epsil;
//
// cpuSphericalHarmonicsBessel(sr1, si1, xi1, sh.x0, sh.P, sh.tmp, sh.f,
// sh.fac, M_PI, common.L, common.K, ntuples);
//
// cpuRadialSphericalHarmonicsSpectrum(ei1, cr1, ci1, sr1, si1, sh.cg, sh.indk, sh.indl, sh.indm,
// sh.rowm, pairnumsum, common.Nub, common.Ncg, na, common.L, common.K, common.spectrum);
//
// PGEMTV(common.cublasHandle, na, Nbf, &one, ei1, na, onev, inc1, &zero, et, inc1, common.backend);
//
// dstype em = 0.0;
// for (int j=0; j<Nbf; j++)
// em += et[j]*coeff[j];
// dstype emax = fabs((en-em)/epsil - fij[i]);
//
// cout<<"Maximum absolute error: "<<emax<<endl;
// }
// delete[] sr1;
// delete[] si1;
// delete[] cr1;
// delete[] ci1;
// delete[] xi1;
// delete[] xii;
// delete[] ei1;
// delete[] onev;
// delete[] et;
// error("here");
// #endif
if (decomp==0)
ForceDecomposition(f, fij, ai, aj, ntuples, backend);
else {
CenterAtomDecomposition(f, fij, ilist, pairnumsum, na, backend);
ArrayCopy(tmp.intmem, aj, ntuples, backend);
Int *jlist = &tmp.intmem[ntuples];
Int *bnumsum = &tmp.intmem[2*ntuples];
Int *index = &tmp.intmem[3*ntuples]; // ntuples
Int *p0 = &tmp.intmem[4*ntuples]; // ntuples
Int *p1 = &tmp.intmem[5*ntuples]; // ntuples
Int *p2 = &tmp.intmem[6*ntuples]; // ntuples
Int *p3 = &tmp.intmem[7*ntuples]; // ntuples
Int naj = UniqueSort(jlist, bnumsum, index, p0, tmp.intmem, p1, p2, p3, ntuples, backend);
NeighborAtomDecomposition(f, fij, jlist, bnumsum, index, naj, backend);
}
}
}
void implSphericalHarmonicBesselEnergyForce(dstype *e, dstype *f, neighborstruct &nb, commonstruct &common,
appstruct &app, tempstruct &tmp, shstruct &sh, dstype* x, dstype *coeff, dstype *q, dstype* param, Int nparam)
{
//ArraySetValue(e, 0.0, common.inum, common.backend);
//ArraySetValue(f, 0.0, common.dim*common.inum, common.backend);
Int natomtypes = common.natomtypes;
if (natomtypes==1) {
SphericalHarmonicBesselEnergyForce(e, f, nb, common, app, tmp, sh, x, coeff, q, param, &app.rcutsqml[0],
nb.atomtype, nparam, 0, 0, common.decomposition);
}
else {
Int Nbf = common.Nbf;
Int inum = common.inum;
if (common.chemtype == 0) {
for (int i = 0; i < natomtypes; i++)
SphericalHarmonicBesselEnergyForce(e, f, nb, common, app, tmp, sh,
x, &coeff[i*Nbf], q, param, &app.rcutsqml[0], nb.atomtype, nparam, i+1, 0, common.decomposition);
}
else {
for (int i = 0; i < natomtypes; i++)
for (int j = 0; j < natomtypes; j++)
SphericalHarmonicBesselEnergyForce(e, f, nb, common, app, tmp, sh,
x, &coeff[(j+i*natomtypes)*Nbf], q, param, &app.rcutsqml[0], nb.atomtype, nparam, i+1, j+1, common.decomposition);
}
}
}
void SphericalHarmonicBesselEnergyForceVirial(dstype *e, dstype *f, dstype *v, neighborstruct &nb, commonstruct &common, appstruct &app, tempstruct &tmp,
shstruct &sh, dstype* x, dstype *coeff, dstype *q, dstype* param, dstype *rcutsq, Int *atomtype, Int nparam, Int typei, Int typej, Int decomp)
{
Int Nbf = common.Nbf;
Int ncq = 0;
for (Int b=0; b<common.nba; b++) {
Int e1 = common.ablks[b];
Int e2 = common.ablks[b+1];
Int na = e2 - e1; // number of atoms in this block
Int neighmax = common.neighmax;
Int dim = common.dim;
Int backend = common.backend;
Int *ilist = &tmp.intmem[0]; //na
if (typei>0) {
Int *olist = &tmp.intmem[na]; //na
ArrayFill(olist, e1, na, backend);
Int *t0 = &tmp.intmem[2*na]; //na
Int *t1 = &tmp.intmem[3*na]; //na
na = FindAtomType(ilist, olist, atomtype, t0, t1, typei, na, backend);
}
else {
ArrayFill(ilist, e1, na, backend);
}
Int *pairnum = &tmp.intmem[na]; // na
Int *pairlist = &tmp.intmem[2*na]; // na*neighmax
if (typej>0)
FullNeighPairList(pairnum, pairlist, x, rcutsq, atomtype, ilist, nb.alist, nb.neighlist, nb.neighnum, na, neighmax, typej, dim, backend);
else
FullNeighPairList(pairnum, pairlist, x, rcutsq, ilist, nb.neighlist, nb.neighnum, na, neighmax, dim, backend);
//a list contains the starting positions of the first neighbor
Int *pairnumsum = &tmp.intmem[2*na+na*neighmax]; // na+1
Cumsum(pairnumsum, pairnum, &tmp.intmem[3*na+na*neighmax+1], &tmp.intmem[4*na+na*neighmax+2], na+1, backend);
int ntuples = IntArrayGetValueAtIndex(pairnumsum, na, common.backend);
Int *ai = &tmp.intmem[1+3*na+na*neighmax]; // ntuples
Int *aj = &tmp.intmem[1+3*na+ntuples+na*neighmax]; // ntuples
Int *ti = &tmp.intmem[1+3*na+2*ntuples+na*neighmax]; // ntuples
Int *tj = &tmp.intmem[1+3*na+3*ntuples+na*neighmax]; // ntuples
//dstype *xij = &tmp.tmpmem[0]; // ntuples*dim
Int nbasis = common.K*(common.L+1)*(common.L+1);
dstype *xij = &tmp.tmpmem[2*na*nbasis+ntuples*(8*nbasis)]; // ntuples*dim
dstype *qi;
dstype *qj;
NeighPairs(xij, qi, qj, x, q, ai, aj, ti, tj, pairnum, pairlist, pairnumsum, ilist, nb.alist,
atomtype, na, neighmax, ncq, dim, backend);
// #ifdef HAVE_CHECK
// dstype *xi1 = new dstype[ntuples*dim];
// dstype *xii = new dstype[ntuples*dim];
// cpuArrayCopy(xii, xij, dim*ntuples);
// cpuArrayCopy(xi1, xij, dim*ntuples);
// #endif
dstype *cr = &tmp.tmpmem[0]; // na*nbasis
dstype *ci = &tmp.tmpmem[na*nbasis]; // na*nbasis
dstype *srx = &tmp.tmpmem[2*na*nbasis]; // ntuples*nbasis
dstype *sry = &tmp.tmpmem[2*na*nbasis+ntuples*(1*nbasis)]; // ntuples*nbasis
dstype *srz = &tmp.tmpmem[2*na*nbasis+ntuples*(2*nbasis)]; // ntuples*nbasis
dstype *six = &tmp.tmpmem[2*na*nbasis+ntuples*(3*nbasis)]; // ntuples*nbasis
dstype *siy = &tmp.tmpmem[2*na*nbasis+ntuples*(4*nbasis)]; // ntuples*nbasis
dstype *siz = &tmp.tmpmem[2*na*nbasis+ntuples*(5*nbasis)]; // ntuples*nbasis
dstype *sr = &tmp.tmpmem[2*na*nbasis+ntuples*(6*nbasis)]; // ntuples*nbasis
dstype *si = &tmp.tmpmem[2*na*nbasis+ntuples*(7*nbasis)]; // ntuples*nbasis
SphericalHarmonicsBesselWithDeriv(sr, si, srx, six, sry, siy, srz, siz, xij,
sh.x0, sh.P, sh.tmp, sh.f, sh.dP, sh.dtmp, sh.df, sh.fac, M_PI, common.L, common.K, ntuples, backend);
dstype *di = &tmp.tmpmem[2*na*nbasis+ntuples*(8*nbasis)]; // na * Nbf
RadialSphericalHarmonicsSpectrum(di, cr, ci, sr, si, sh.cg, sh.indk,
sh.indl, sh.indm, sh.rowm, pairnumsum, common.Nub, common.Ncg, na, common.L, common.K, common.spectrum, backend);
// di : na x Nbf, coeff : Nbf x 1, ei : na x 1
// ei = di*coeff
dstype *ei = &tmp.tmpmem[2*na*nbasis+ntuples*(6*nbasis)]; // na
PGEMNV(common.cublasHandle, na, Nbf, &one, di, na, coeff, inc1, &zero, ei, inc1, common.backend);
CenterAtomDecomposition(e, ei, ilist, na, backend);
dstype *dd = &tmp.tmpmem[2*na*nbasis+ntuples*(6*nbasis)]; // dim * ntuples * Nbf
RadialSphericalHarmonicsSpectrumDeriv(dd, cr, ci, srx, six, sry, siy, srz, siz, sh.cg, sh.indk,
sh.indl, sh.indm, sh.rowm, pairnumsum, common.Nub, common.Ncg, na, common.L, common.K, common.spectrum, backend);
dstype *fij = &tmp.tmpmem[0]; // dim * ntuples
PGEMNV(common.cublasHandle, dim*ntuples, Nbf, &minusone, dd, dim*ntuples, coeff, inc1, &zero, fij, inc1, common.backend);
// #ifdef HAVE_CHECK
// dstype en = cpuArraySum(e, na);
// dstype epsil = 1e-6;
// dstype *sr1 = new dstype[ntuples*nbasis];
// dstype *si1 = new dstype[ntuples*nbasis];
// dstype *cr1 = new dstype[na*nbasis];
// dstype *ci1 = new dstype[na*nbasis];
// dstype *ei1 = new dstype[na*Nbf];
// dstype *onev = new dstype[na];
// dstype *et = new dstype[Nbf];
// ArraySetValue(onev, 1.0, na, common.backend);
// for (int i = 0; i<dim*ntuples; i++) {
// cpuArrayCopy(xi1, xii, dim*ntuples);
// xi1[i] = xi1[i] + epsil;
//
// cpuSphericalHarmonicsBessel(sr1, si1, xi1, sh.x0, sh.P, sh.tmp, sh.f,
// sh.fac, M_PI, common.L, common.K, ntuples);
//
// cpuRadialSphericalHarmonicsSpectrum(ei1, cr1, ci1, sr1, si1, sh.cg, sh.indk, sh.indl, sh.indm,
// sh.rowm, pairnumsum, common.Nub, common.Ncg, na, common.L, common.K, common.spectrum);
//
// PGEMTV(common.cublasHandle, na, Nbf, &one, ei1, na, onev, inc1, &zero, et, inc1, common.backend);
//
// dstype em = 0.0;
// for (int j=0; j<Nbf; j++)
// em += et[j]*coeff[j];
// dstype emax = fabs((en-em)/epsil - fij[i]);
//
// cout<<"Maximum absolute error: "<<emax<<endl;
// }
// delete[] sr1;
// delete[] si1;
// delete[] cr1;
// delete[] ci1;
// delete[] xi1;
// delete[] xii;
// delete[] ei1;
// delete[] onev;
// delete[] et;
// error("here");
// #endif
if (decomp==0)
ForceDecomposition(f, fij, ai, aj, ntuples, backend);
else {
CenterAtomDecomposition(f, fij, ilist, pairnumsum, na, backend);
ArrayCopy(tmp.intmem, aj, ntuples, backend);
Int *jlist = &tmp.intmem[ntuples];
Int *bnumsum = &tmp.intmem[2*ntuples];
Int *index = &tmp.intmem[3*ntuples]; // ntuples
Int *p0 = &tmp.intmem[4*ntuples]; // ntuples
Int *p1 = &tmp.intmem[5*ntuples]; // ntuples
Int *p2 = &tmp.intmem[6*ntuples]; // ntuples
Int *p3 = &tmp.intmem[7*ntuples]; // ntuples
Int naj = UniqueSort(jlist, bnumsum, index, p0, tmp.intmem, p1, p2, p3, ntuples, backend);
NeighborAtomDecomposition(f, fij, jlist, bnumsum, index, naj, backend);
}
SnapTallyVirialFull(v, fij, xij, ai, aj, common.inum, ntuples, backend);
}
}
void implSphericalHarmonicBesselEnergyForceVirial(dstype *e, dstype *f, dstype *v, neighborstruct &nb, commonstruct &common,
appstruct &app, tempstruct &tmp, shstruct &sh, dstype* x, dstype *coeff, dstype *q, dstype* param, Int nparam)
{
//ArraySetValue(e, 0.0, common.inum, common.backend);
//ArraySetValue(f, 0.0, common.dim*common.inum, common.backend);
Int natomtypes = common.natomtypes;
if (natomtypes==1) {
SphericalHarmonicBesselEnergyForceVirial(e, f, v, nb, common, app, tmp, sh, x, coeff, q, param, &app.rcutsqml[0],
nb.atomtype, nparam, 0, 0, common.decomposition);
}
else {
Int Nbf = common.Nbf;
Int inum = common.inum;
if (common.chemtype == 0) {
for (int i = 0; i < natomtypes; i++)
SphericalHarmonicBesselEnergyForceVirial(e, f, v, nb, common, app, tmp, sh,
x, &coeff[i*Nbf], q, param, &app.rcutsqml[0], nb.atomtype, nparam, i+1, 0, common.decomposition);
}
else {
for (int i = 0; i < natomtypes; i++)
for (int j = 0; j < natomtypes; j++)
SphericalHarmonicBesselEnergyForceVirial(e, f, v, nb, common, app, tmp, sh,
x, &coeff[(j+i*natomtypes)*Nbf], q, param, &app.rcutsqml[0], nb.atomtype, nparam, i+1, j+1, common.decomposition);
}
}
}
#endif
| 51.539352 | 173 | 0.521379 | cesmix-mit |
20886b776887e4f3b83d13e859e9084ae53ee7fb | 38,248 | cc | C++ | src/hooks/dhcp/flex_option/tests/flex_option_unittests.cc | svenauhagen/kea | 8a575ad46dee1487364fad394e7a325337200839 | [
"Apache-2.0"
] | null | null | null | src/hooks/dhcp/flex_option/tests/flex_option_unittests.cc | svenauhagen/kea | 8a575ad46dee1487364fad394e7a325337200839 | [
"Apache-2.0"
] | null | null | null | src/hooks/dhcp/flex_option/tests/flex_option_unittests.cc | svenauhagen/kea | 8a575ad46dee1487364fad394e7a325337200839 | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2019 Internet Systems Consortium, Inc. ("ISC")
//
// 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/.
/// @file This file contains tests which verify flexible option.
#include <config.h>
#include <flex_option.h>
#include <flex_option_log.h>
#include <dhcp/option_string.h>
#include <dhcp/libdhcp++.h>
#include <dhcpsrv/cfgmgr.h>
#include <eval/eval_context.h>
#include <hooks/callout_manager.h>
#include <hooks/hooks.h>
#include <gtest/gtest.h>
#include <sstream>
using namespace std;
using namespace isc;
using namespace isc::data;
using namespace isc::dhcp;
using namespace isc::eval;
using namespace isc::hooks;
using namespace isc::flex_option;
namespace {
/// @brief Test class derived from FlexOptionImpl
class TestFlexOptionImpl : public FlexOptionImpl {
public:
/// Export getMutableOptionConfigMap.
using FlexOptionImpl::getMutableOptionConfigMap;
/// @brief Configure clone which records the error.
///
/// @param options The element with option config list.
void testConfigure(ConstElementPtr options) {
err_msg_.clear();
try {
configure(options);
} catch (const std::exception& ex) {
err_msg_ = string(ex.what());
throw;
}
}
/// @brief Get the last error message.
///
/// @return The last error message.
const string& getErrMsg() const {
return (err_msg_);
}
private:
/// @brief Last error message.
string err_msg_;
};
/// @brief The type of shared pointers to TestFlexOptionImpl
typedef boost::shared_ptr<TestFlexOptionImpl> TestFlexOptionImplPtr;
/// @brief Test fixture for testing the Flex Option library.
class FlexOptionTest : public ::testing::Test {
public:
/// @brief Constructor.
FlexOptionTest() {
impl_.reset(new TestFlexOptionImpl());
CfgMgr::instance().setFamily(AF_INET);
}
/// @brief Destructor.
virtual ~FlexOptionTest() {
CfgMgr::instance().setFamily(AF_INET);
impl_.reset();
}
/// @brief Flex Option implementation.
TestFlexOptionImplPtr impl_;
};
// Verify that the configuration must exist.
TEST_F(FlexOptionTest, noConfig) {
ElementPtr options;
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'options' parameter is mandatory", impl_->getErrMsg());
}
// Verify that the configuration must be a list.
TEST_F(FlexOptionTest, configNotList) {
ElementPtr options = Element::createMap();
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'options' parameter must be a list", impl_->getErrMsg());
}
// Verify that the configuration can be the empty list.
TEST_F(FlexOptionTest, configEmpty) {
ElementPtr options = Element::createList();
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
}
// Verify that an option configuration must exist.
TEST_F(FlexOptionTest, noOptionConfig) {
ElementPtr options = Element::createList();
ElementPtr option;
options->add(option);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("null option element", impl_->getErrMsg());
}
// Verify that an option configuration must be a map.
TEST_F(FlexOptionTest, optionConfigNotMap) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createList();
options->add(option);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("option element is not a map", impl_->getErrMsg());
}
// Verify that an option configuration must have code or name.
TEST_F(FlexOptionTest, optionConfigNoCodeName) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
ostringstream errmsg;
errmsg << "'code' or 'name' must be specified: " << option->str();
EXPECT_EQ(errmsg.str(), impl_->getErrMsg());
}
// Verify that the v4 option code must be in [1..254].
TEST_F(FlexOptionTest, optionConfigBadCode4) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr add = Element::create(string("'ab'"));
option->set("add", add);
ElementPtr code = Element::create(false);
option->set("code", code);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'code' must be an integer: false", impl_->getErrMsg());
code = Element::create(-1);
option->set("code", code);
EXPECT_THROW(impl_->testConfigure(options), OutOfRange);
EXPECT_EQ("invalid 'code' value -1 not in [0..255]", impl_->getErrMsg());
code = Element::create(DHO_PAD);
option->set("code", code);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("invalid 'code' value 0: reserved for PAD", impl_->getErrMsg());
code = Element::create(DHO_END);
option->set("code", code);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("invalid 'code' value 255: reserved for END", impl_->getErrMsg());
code = Element::create(256);
option->set("code", code);
EXPECT_THROW(impl_->testConfigure(options), OutOfRange);
EXPECT_EQ("invalid 'code' value 256 not in [0..255]", impl_->getErrMsg());
code = Element::create(1);
option->set("code", code);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
code = Element::create(254);
option->set("code", code);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
}
// Verify that the v6 option code must be in [1..65535].
TEST_F(FlexOptionTest, optionConfigBadCode6) {
CfgMgr::instance().setFamily(AF_INET6);
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr add = Element::create(string("'ab'"));
option->set("add", add);
ElementPtr code = Element::create(false);
option->set("code", code);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'code' must be an integer: false", impl_->getErrMsg());
code = Element::create(-1);
option->set("code", code);
EXPECT_THROW(impl_->testConfigure(options), OutOfRange);
EXPECT_EQ("invalid 'code' value -1 not in [0..65535]", impl_->getErrMsg());
code = Element::create(0);
option->set("code", code);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("invalid 'code' value 0: reserved", impl_->getErrMsg());
code = Element::create(65536);
option->set("code", code);
EXPECT_THROW(impl_->testConfigure(options), OutOfRange);
EXPECT_EQ("invalid 'code' value 65536 not in [0..65535]", impl_->getErrMsg());
code = Element::create(1);
option->set("code", code);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
code = Element::create(65535);
option->set("code", code);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
}
// Verify that the name must be a string.
TEST_F(FlexOptionTest, optionConfigBadName) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr add = Element::create(string("'ab'"));
option->set("add", add);
ElementPtr name = Element::create(true);
option->set("name", name);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'name' must be a string: true", impl_->getErrMsg());
}
// Verify that the name must not be empty.
TEST_F(FlexOptionTest, optionConfigEmptyName) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr add = Element::create(string("'ab'"));
option->set("add", add);
ElementPtr name = Element::create(string());
option->set("name",name);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'name' must not be empty", impl_->getErrMsg());
}
// Verify that the name must be a known option.
TEST_F(FlexOptionTest, optionConfigUnknownName) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr add = Element::create(string("'ab'"));
option->set("add", add);
ElementPtr name = Element::create(string("foobar"));
option->set("name",name);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("no known 'foobar' option in 'dhcp4' space", impl_->getErrMsg());
}
// Verify that the name can be a standard option.
TEST_F(FlexOptionTest, optionConfigStandardName) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr add = Element::create(string("'ab'"));
option->set("add", add);
ElementPtr name = Element::create(string("host-name"));
option->set("name", name);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
auto map = impl_->getOptionConfigMap();
EXPECT_EQ(1, map.count(DHO_HOST_NAME));
}
// Verify that the name can be an user defined option.
TEST_F(FlexOptionTest, optionConfigDefinedName) {
OptionDefSpaceContainer defs;
OptionDefinitionPtr def(new OptionDefinition("my-option", 222, "string"));
defs.addItem(def, DHCP4_OPTION_SPACE);
EXPECT_NO_THROW(LibDHCP::setRuntimeOptionDefs(defs));
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr add = Element::create(string("'ab'"));
option->set("add", add);
ElementPtr name = Element::create(string("my-option"));
option->set("name", name);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
auto map = impl_->getOptionConfigMap();
EXPECT_EQ(1, map.count(222));
}
// Last resort is only option 43...
// Verify that the name must match the code.
TEST_F(FlexOptionTest, optionConfigCodeNameMismatch) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr add = Element::create(string("'ab'"));
option->set("add", add);
ElementPtr code = Element::create(DHO_HOST_NAME + 1);
option->set("code", code);
ElementPtr name = Element::create(string("host-name"));
option->set("name", name);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
string expected = "option 'host-name' is defined as code: 12, ";
expected += "not the specified code: 13";
EXPECT_EQ(expected, impl_->getErrMsg());
}
// Verify that an option can be configured only once.
TEST_F(FlexOptionTest, optionConfigTwice) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr add = Element::create(string("'ab'"));
option->set("add", add);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
options->add(option);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("option 12 was already specified", impl_->getErrMsg());
}
// Verify that the add value must be a string.
TEST_F(FlexOptionTest, optionConfigAddNotString) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr add = Element::create(true);
option->set("add", add);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'add' must be a string: true", impl_->getErrMsg());
}
// Verify that the add value must not be empty.
TEST_F(FlexOptionTest, optionConfigEmptyAdd) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr add = Element::create(string());
option->set("add", add);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'add' must not be empty", impl_->getErrMsg());
}
// Verify that the add value must parse.
TEST_F(FlexOptionTest, optionConfigBadAdd) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr add = Element::create(string("ifelse('a','b','c')"));
option->set("add", add);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
string expected = "can't parse add expression [ifelse('a','b','c')] ";
expected += "error: <string>:1.11: syntax error, ";
expected += "unexpected \",\", expecting ==";
EXPECT_EQ(expected, impl_->getErrMsg());
}
// Verify that a valid v4 add value is accepted.
TEST_F(FlexOptionTest, optionConfigAdd4) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr add = Element::create(string("'abc'"));
option->set("add", add);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
auto map = impl_->getOptionConfigMap();
FlexOptionImpl::OptionConfigPtr opt_cfg;
ASSERT_NO_THROW(opt_cfg = map.at(DHO_HOST_NAME));
ASSERT_TRUE(opt_cfg);
EXPECT_EQ(DHO_HOST_NAME, opt_cfg->getCode());
EXPECT_EQ(FlexOptionImpl::ADD, opt_cfg->getAction());
EXPECT_EQ("'abc'", opt_cfg->getText());
ExpressionPtr expr = opt_cfg->getExpr();
ASSERT_TRUE(expr);
ASSERT_EQ(1, expr->size());
Pkt4Ptr pkt4(new Pkt4(DHCPDISCOVER, 12345));
ValueStack values;
EXPECT_NO_THROW(expr->at(0)->evaluate(*pkt4, values));
ASSERT_EQ(1, values.size());
EXPECT_EQ("abc", values.top());
}
// Verify that a valid v6 add value is accepted.
TEST_F(FlexOptionTest, optionConfigAdd6) {
CfgMgr::instance().setFamily(AF_INET6);
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(D6O_BOOTFILE_URL);
option->set("code", code);
ElementPtr add = Element::create(string("'abc'"));
option->set("add", add);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
auto map = impl_->getOptionConfigMap();
FlexOptionImpl::OptionConfigPtr opt_cfg;
ASSERT_NO_THROW(opt_cfg = map.at(D6O_BOOTFILE_URL));
ASSERT_TRUE(opt_cfg);
EXPECT_EQ(D6O_BOOTFILE_URL, opt_cfg->getCode());
EXPECT_EQ(FlexOptionImpl::ADD, opt_cfg->getAction());
EXPECT_EQ("'abc'", opt_cfg->getText());
ExpressionPtr expr = opt_cfg->getExpr();
ASSERT_TRUE(expr);
ASSERT_EQ(1, expr->size());
Pkt6Ptr pkt6(new Pkt6(DHCPV6_SOLICIT, 12345));
ValueStack values;
EXPECT_NO_THROW(expr->at(0)->evaluate(*pkt6, values));
ASSERT_EQ(1, values.size());
EXPECT_EQ("abc", values.top());
}
// Verify that the supersede value must be a string.
TEST_F(FlexOptionTest, optionConfigSupersedeNotString) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr supersede = Element::create(123);
option->set("supersede", supersede);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'supersede' must be a string: 123", impl_->getErrMsg());
}
// Verify that the supersede value must not be empty.
TEST_F(FlexOptionTest, optionConfigEmptySupersede) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr supersede = Element::create(string());
option->set("supersede", supersede);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'supersede' must not be empty", impl_->getErrMsg());
}
// Verify that the supersede value must parse.
TEST_F(FlexOptionTest, optionConfigBadSupersede) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr supersede = Element::create(string("ifelse('a','b','c')"));
option->set("supersede", supersede);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
string expected = "can't parse supersede expression [ifelse('a','b','c')] ";
expected += "error: <string>:1.11: syntax error, ";
expected += "unexpected \",\", expecting ==";
EXPECT_EQ(expected, impl_->getErrMsg());
}
// Verify that a valid v4 supersede value is accepted.
TEST_F(FlexOptionTest, optionConfigSupersede4) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr supersede = Element::create(string("'abc'"));
option->set("supersede", supersede);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
auto map = impl_->getOptionConfigMap();
FlexOptionImpl::OptionConfigPtr opt_cfg;
ASSERT_NO_THROW(opt_cfg = map.at(DHO_HOST_NAME));
ASSERT_TRUE(opt_cfg);
EXPECT_EQ(DHO_HOST_NAME, opt_cfg->getCode());
EXPECT_EQ(FlexOptionImpl::SUPERSEDE, opt_cfg->getAction());
EXPECT_EQ("'abc'", opt_cfg->getText());
ExpressionPtr expr = opt_cfg->getExpr();
ASSERT_TRUE(expr);
ASSERT_EQ(1, expr->size());
Pkt4Ptr pkt4(new Pkt4(DHCPDISCOVER, 12345));
ValueStack values;
EXPECT_NO_THROW(expr->at(0)->evaluate(*pkt4, values));
ASSERT_EQ(1, values.size());
EXPECT_EQ("abc", values.top());
}
// Verify that a valid v6 supersede value is accepted.
TEST_F(FlexOptionTest, optionConfigSupersede6) {
CfgMgr::instance().setFamily(AF_INET6);
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(D6O_BOOTFILE_URL);
option->set("code", code);
ElementPtr supersede = Element::create(string("'abc'"));
option->set("supersede", supersede);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
auto map = impl_->getOptionConfigMap();
FlexOptionImpl::OptionConfigPtr opt_cfg;
ASSERT_NO_THROW(opt_cfg = map.at(D6O_BOOTFILE_URL));
ASSERT_TRUE(opt_cfg);
EXPECT_EQ(D6O_BOOTFILE_URL, opt_cfg->getCode());
EXPECT_EQ(FlexOptionImpl::SUPERSEDE, opt_cfg->getAction());
EXPECT_EQ("'abc'", opt_cfg->getText());
ExpressionPtr expr = opt_cfg->getExpr();
ASSERT_TRUE(expr);
ASSERT_EQ(1, expr->size());
Pkt6Ptr pkt6(new Pkt6(DHCPV6_SOLICIT, 12345));
ValueStack values;
EXPECT_NO_THROW(expr->at(0)->evaluate(*pkt6, values));
ASSERT_EQ(1, values.size());
EXPECT_EQ("abc", values.top());
}
// Verify that the remove value must be a string.
TEST_F(FlexOptionTest, optionConfigRemoveNotString) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr remove = Element::createMap();
option->set("remove", remove);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'remove' must be a string: { }", impl_->getErrMsg());
}
// Verify that the remove value must not be empty.
TEST_F(FlexOptionTest, optionConfigEmptyRemove) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr remove = Element::create(string());
option->set("remove", remove);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
EXPECT_EQ("'remove' must not be empty", impl_->getErrMsg());
}
// Verify that the remove value must parse.
TEST_F(FlexOptionTest, optionConfigBadRemove) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr remove = Element::create(string("'abc'"));
option->set("remove", remove);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
string expected = "can't parse remove expression ['abc'] error: ";
expected += "<string>:1.6: syntax error, unexpected end of file, ";
expected += "expecting ==";
EXPECT_EQ(expected,impl_->getErrMsg());
}
// Verify that a valid v4 remove value is accepted.
TEST_F(FlexOptionTest, optionConfigRemove4) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr remove = Element::create(string("'abc' == 'abc'"));
option->set("remove", remove);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
auto map = impl_->getOptionConfigMap();
FlexOptionImpl::OptionConfigPtr opt_cfg;
ASSERT_NO_THROW(opt_cfg = map.at(DHO_HOST_NAME));
ASSERT_TRUE(opt_cfg);
EXPECT_EQ(DHO_HOST_NAME, opt_cfg->getCode());
EXPECT_EQ(FlexOptionImpl::REMOVE, opt_cfg->getAction());
EXPECT_EQ("'abc' == 'abc'", opt_cfg->getText());
ExpressionPtr expr = opt_cfg->getExpr();
ASSERT_TRUE(expr);
ASSERT_EQ(3, expr->size());
Pkt4Ptr pkt4(new Pkt4(DHCPDISCOVER, 12345));
ValueStack values;
EXPECT_NO_THROW(expr->at(0)->evaluate(*pkt4, values));
ASSERT_EQ(1, values.size());
EXPECT_EQ("abc", values.top());
EXPECT_NO_THROW(expr->at(1)->evaluate(*pkt4, values));
ASSERT_EQ(2, values.size());
EXPECT_NO_THROW(expr->at(2)->evaluate(*pkt4, values));
ASSERT_EQ(1, values.size());
EXPECT_EQ("true", values.top());
}
// Verify that a valid v6 remove value is accepted.
TEST_F(FlexOptionTest, optionConfigRemove6) {
CfgMgr::instance().setFamily(AF_INET6);
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(D6O_BOOTFILE_URL);
option->set("code", code);
ElementPtr remove = Element::create(string("'abc' == 'abc'"));
option->set("remove", remove);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
auto map = impl_->getOptionConfigMap();
FlexOptionImpl::OptionConfigPtr opt_cfg;
ASSERT_NO_THROW(opt_cfg = map.at(D6O_BOOTFILE_URL));
ASSERT_TRUE(opt_cfg);
EXPECT_EQ(D6O_BOOTFILE_URL, opt_cfg->getCode());
EXPECT_EQ(FlexOptionImpl::REMOVE, opt_cfg->getAction());
EXPECT_EQ("'abc' == 'abc'", opt_cfg->getText());
ExpressionPtr expr = opt_cfg->getExpr();
ASSERT_TRUE(expr);
ASSERT_EQ(3, expr->size());
Pkt6Ptr pkt6(new Pkt6(DHCPV6_SOLICIT, 12345));
ValueStack values;
EXPECT_NO_THROW(expr->at(0)->evaluate(*pkt6, values));
ASSERT_EQ(1, values.size());
EXPECT_EQ("abc", values.top());
EXPECT_NO_THROW(expr->at(1)->evaluate(*pkt6, values));
ASSERT_EQ(2, values.size());
EXPECT_NO_THROW(expr->at(2)->evaluate(*pkt6, values));
ASSERT_EQ(1, values.size());
EXPECT_EQ("true", values.top());
}
// Verify that multiple actions are not accepted.
TEST_F(FlexOptionTest, optionConfigMultipleAction) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
// add and supersede.
ElementPtr add = Element::create(string("'abc'"));
option->set("add", add);
ElementPtr supersede = Element::create(string("'abc'"));
option->set("supersede", supersede);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
ostringstream errmsg;
errmsg << "multiple actions: " << option->str();
EXPECT_EQ(errmsg.str(), impl_->getErrMsg());
// supersede and remove.
option->remove("add");
ElementPtr remove = Element::create(string("'abc' == 'abc'"));
option->set("remove", remove);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
errmsg.str("");
errmsg << "multiple actions: " << option->str();
EXPECT_EQ(errmsg.str(), impl_->getErrMsg());
// add and remove.
option->remove("supersede");
option->set("add", add);
EXPECT_THROW(impl_->testConfigure(options), BadValue);
errmsg.str("");
errmsg << "multiple actions: " << option->str();
EXPECT_EQ(errmsg.str(), impl_->getErrMsg());
}
// Verify that multiple options are accepted.
TEST_F(FlexOptionTest, optionConfigList) {
ElementPtr options = Element::createList();
ElementPtr option1 = Element::createMap();
options->add(option1);
ElementPtr code1 = Element::create(DHO_HOST_NAME);
option1->set("code", code1);
ElementPtr add1 = Element::create(string("'abc'"));
option1->set("add", add1);
ElementPtr option2 = Element::createMap();
options->add(option2);
ElementPtr code2 = Element::create(DHO_ROOT_PATH);
option2->set("code", code2);
ElementPtr supersede2 = Element::create(string("'/'"));
option2->set("supersede", supersede2);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
auto map = impl_->getOptionConfigMap();
EXPECT_EQ(2, map.size());
FlexOptionImpl::OptionConfigPtr opt1_cfg;
ASSERT_NO_THROW(opt1_cfg = map.at(DHO_HOST_NAME));
ASSERT_TRUE(opt1_cfg);
EXPECT_EQ(DHO_HOST_NAME, opt1_cfg->getCode());
EXPECT_EQ(FlexOptionImpl::ADD, opt1_cfg->getAction());
EXPECT_EQ("'abc'", opt1_cfg->getText());
FlexOptionImpl::OptionConfigPtr opt2_cfg;
ASSERT_NO_THROW(opt2_cfg = map.at(DHO_ROOT_PATH));
ASSERT_TRUE(opt2_cfg);
EXPECT_EQ(DHO_ROOT_PATH, opt2_cfg->getCode());
EXPECT_EQ(FlexOptionImpl::SUPERSEDE, opt2_cfg->getAction());
EXPECT_EQ("'/'", opt2_cfg->getText());
}
// Verify that empty option config list does nothing.
TEST_F(FlexOptionTest, processEmpty) {
Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 12345));
Pkt4Ptr response(new Pkt4(DHCPOFFER, 12345));
string response_txt = response->toText();
EXPECT_NO_THROW(impl_->process<Pkt4Ptr>(Option::V4, query, response));
EXPECT_EQ(response_txt, response->toText());
}
// Verify that NONE action really does nothing.
TEST_F(FlexOptionTest, processNone) {
CfgMgr::instance().setFamily(AF_INET6);
FlexOptionImpl::OptionConfigPtr
opt_cfg(new FlexOptionImpl::OptionConfig(D6O_BOOTFILE_URL));
EXPECT_EQ(FlexOptionImpl::NONE, opt_cfg->getAction());
auto map = impl_->getMutableOptionConfigMap();
map[DHO_HOST_NAME] = opt_cfg;
Pkt6Ptr query(new Pkt6(DHCPV6_SOLICIT, 12345));
Pkt6Ptr response(new Pkt6(DHCPV6_ADVERTISE, 12345));
string response_txt = response->toText();
EXPECT_NO_THROW(impl_->process<Pkt6Ptr>(Option::V6, query, response));
EXPECT_EQ(response_txt, response->toText());
}
// Verify that ADD action adds the specified option.
TEST_F(FlexOptionTest, processAdd) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr add = Element::create(string("'abc'"));
option->set("add", add);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 12345));
Pkt4Ptr response(new Pkt4(DHCPOFFER, 12345));
EXPECT_FALSE(response->getOption(DHO_HOST_NAME));
EXPECT_NO_THROW(impl_->process<Pkt4Ptr>(Option::V4, query, response));
OptionPtr opt = response->getOption(DHO_HOST_NAME);
ASSERT_TRUE(opt);
EXPECT_EQ(DHO_HOST_NAME, opt->getType());
const OptionBuffer& buffer = opt->getData();
ASSERT_EQ(3, buffer.size());
EXPECT_EQ(0, memcmp(&buffer[0], "abc", 3));
}
// Verify that ADD action does not add an already existing option.
TEST_F(FlexOptionTest, processAddExisting) {
CfgMgr::instance().setFamily(AF_INET6);
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(D6O_BOOTFILE_URL);
option->set("code", code);
ElementPtr add = Element::create(string("'abc'"));
option->set("add", add);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
Pkt6Ptr query(new Pkt6(DHCPV6_SOLICIT, 12345));
Pkt6Ptr response(new Pkt6(DHCPV6_ADVERTISE, 12345));
OptionStringPtr str(new OptionString(Option::V6, D6O_BOOTFILE_URL, "http"));
response->addOption(str);
EXPECT_NO_THROW(impl_->process<Pkt6Ptr>(Option::V6, query, response));
OptionPtr opt = response->getOption(D6O_BOOTFILE_URL);
ASSERT_TRUE(opt);
EXPECT_EQ(D6O_BOOTFILE_URL, opt->getType());
EXPECT_EQ("http", opt->toString());
}
// Verify that ADD action does not add an empty value.
TEST_F(FlexOptionTest, processAddEmpty) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr add = Element::create(string("''"));
option->set("add", add);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 12345));
Pkt4Ptr response(new Pkt4(DHCPOFFER, 12345));
string response_txt = response->toText();
EXPECT_FALSE(response->getOption(DHO_HOST_NAME));
EXPECT_NO_THROW(impl_->process<Pkt4Ptr>(Option::V4, query, response));
EXPECT_EQ(response_txt, response->toText());
EXPECT_FALSE(response->getOption(DHO_HOST_NAME));
}
// Verify that SUPERSEDE action supersedes the specified option.
TEST_F(FlexOptionTest, processSupersede) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr supersede = Element::create(string("'abc'"));
option->set("supersede", supersede);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 12345));
Pkt4Ptr response(new Pkt4(DHCPOFFER, 12345));
EXPECT_FALSE(response->getOption(DHO_HOST_NAME));
EXPECT_NO_THROW(impl_->process<Pkt4Ptr>(Option::V4, query, response));
OptionPtr opt = response->getOption(DHO_HOST_NAME);
ASSERT_TRUE(opt);
EXPECT_EQ(DHO_HOST_NAME, opt->getType());
const OptionBuffer& buffer = opt->getData();
ASSERT_EQ(3, buffer.size());
EXPECT_EQ(0, memcmp(&buffer[0], "abc", 3));
}
// Verify that SUPERSEDE action supersedes an already existing option.
TEST_F(FlexOptionTest, processSupersedeExisting) {
CfgMgr::instance().setFamily(AF_INET6);
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(D6O_BOOTFILE_URL);
option->set("code", code);
ElementPtr supersede = Element::create(string("0xabcdef"));
option->set("supersede", supersede);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
Pkt6Ptr query(new Pkt6(DHCPV6_SOLICIT, 12345));
Pkt6Ptr response(new Pkt6(DHCPV6_ADVERTISE, 12345));
OptionStringPtr str(new OptionString(Option::V6, D6O_BOOTFILE_URL, "http"));
response->addOption(str);
EXPECT_NO_THROW(impl_->process<Pkt6Ptr>(Option::V6, query, response));
OptionPtr opt = response->getOption(D6O_BOOTFILE_URL);
ASSERT_TRUE(opt);
EXPECT_EQ(D6O_BOOTFILE_URL, opt->getType());
const OptionBuffer& buffer = opt->getData();
ASSERT_EQ(3, buffer.size());
uint8_t expected[] = { 0xab, 0xcd, 0xef };
EXPECT_EQ(0, memcmp(&buffer[0], expected, 3));
}
// Verify that SUPERSEDE action does not supersede an empty value.
TEST_F(FlexOptionTest, processSupersedeEmpty) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr supersede = Element::create(string("''"));
option->set("supersede", supersede);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 12345));
Pkt4Ptr response(new Pkt4(DHCPOFFER, 12345));
string response_txt = response->toText();
EXPECT_FALSE(response->getOption(DHO_HOST_NAME));
EXPECT_NO_THROW(impl_->process<Pkt4Ptr>(Option::V4, query, response));
EXPECT_EQ(response_txt, response->toText());
EXPECT_FALSE(response->getOption(DHO_HOST_NAME));
// Empty value does not remove existing values.
OptionStringPtr str(new OptionString(Option::V4, DHO_HOST_NAME, "abc"));
response->addOption(str);
EXPECT_NO_THROW(impl_->process<Pkt4Ptr>(Option::V4, query, response));
OptionPtr opt = response->getOption(DHO_HOST_NAME);
ASSERT_TRUE(opt);
EXPECT_EQ(DHO_HOST_NAME, opt->getType());
const OptionBuffer& buffer = opt->getData();
ASSERT_EQ(3, buffer.size());
EXPECT_EQ(0, memcmp(&buffer[0], "abc", 3));
}
// Verify that REMOVE action removes an already existing option.
TEST_F(FlexOptionTest, processRemove) {
CfgMgr::instance().setFamily(AF_INET6);
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(D6O_BOOTFILE_URL);
option->set("code", code);
ElementPtr remove = Element::create(string("'abc' == 'abc'"));
option->set("remove", remove);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
Pkt6Ptr query(new Pkt6(DHCPV6_SOLICIT, 12345));
Pkt6Ptr response(new Pkt6(DHCPV6_ADVERTISE, 12345));
OptionStringPtr str(new OptionString(Option::V6, D6O_BOOTFILE_URL, "http"));
response->addOption(str);
EXPECT_NO_THROW(impl_->process<Pkt6Ptr>(Option::V6, query, response));
EXPECT_FALSE(response->getOption(D6O_BOOTFILE_URL));
}
// Verify that REMOVE action does nothing if the option is not present.
TEST_F(FlexOptionTest, processRemoveNoOption) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_HOST_NAME);
option->set("code", code);
ElementPtr remove = Element::create(string("'abc' == 'abc'"));
option->set("remove", remove);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 12345));
Pkt4Ptr response(new Pkt4(DHCPOFFER, 12345));
string response_txt = response->toText();
EXPECT_FALSE(response->getOption(DHO_HOST_NAME));
EXPECT_NO_THROW(impl_->process<Pkt4Ptr>(Option::V4, query, response));
EXPECT_EQ(response_txt, response->toText());
EXPECT_FALSE(response->getOption(DHO_HOST_NAME));
}
// Verify that REMOVE action does nothing when the expression evaluates to false.
TEST_F(FlexOptionTest, processRemoveFalse) {
CfgMgr::instance().setFamily(AF_INET6);
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(D6O_BOOTFILE_URL);
option->set("code", code);
ElementPtr remove = Element::create(string("'abc' == 'xyz'"));
option->set("remove", remove);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
Pkt6Ptr query(new Pkt6(DHCPV6_SOLICIT, 12345));
Pkt6Ptr response(new Pkt6(DHCPV6_ADVERTISE, 12345));
OptionStringPtr str(new OptionString(Option::V6, D6O_BOOTFILE_URL, "http"));
response->addOption(str);
string response_txt = response->toText();
EXPECT_NO_THROW(impl_->process<Pkt6Ptr>(Option::V6, query, response));
EXPECT_EQ(response_txt, response->toText());
EXPECT_TRUE(response->getOption(D6O_BOOTFILE_URL));
}
// A more complex check...
TEST_F(FlexOptionTest, processFullTest) {
ElementPtr options = Element::createList();
ElementPtr option = Element::createMap();
options->add(option);
ElementPtr code = Element::create(DHO_BOOT_FILE_NAME);
option->set("code", code);
string expr = "ifelse(option[host-name].exists,";
expr += "concat(option[host-name].text,'.boot'),'')";
ElementPtr add = Element::create(expr);
option->set("add", add);
EXPECT_NO_THROW(impl_->testConfigure(options));
EXPECT_TRUE(impl_->getErrMsg().empty());
Pkt4Ptr query(new Pkt4(DHCPDISCOVER, 12345));
Pkt4Ptr response(new Pkt4(DHCPOFFER, 12345));
OptionStringPtr str(new OptionString(Option::V4, DHO_HOST_NAME, "foo"));
query->addOption(str);
EXPECT_FALSE(response->getOption(DHO_BOOT_FILE_NAME));
EXPECT_NO_THROW(impl_->process<Pkt4Ptr>(Option::V4, query, response));
OptionPtr opt = response->getOption(DHO_BOOT_FILE_NAME);
ASSERT_TRUE(opt);
EXPECT_EQ(DHO_BOOT_FILE_NAME, opt->getType());
const OptionBuffer& buffer = opt->getData();
ASSERT_EQ(8, buffer.size());
EXPECT_EQ(0, memcmp(&buffer[0], "foo.boot", 8));
}
} // end of anonymous namespace
| 37.242454 | 82 | 0.691879 | svenauhagen |
208879a88dc78097cc46d062421c0b9964318939 | 101 | cpp | C++ | gen/DMListener.cpp | Wanket/DM | 2b74cbb66ebb7954b48598869cde62aee021c49f | [
"MIT"
] | null | null | null | gen/DMListener.cpp | Wanket/DM | 2b74cbb66ebb7954b48598869cde62aee021c49f | [
"MIT"
] | null | null | null | gen/DMListener.cpp | Wanket/DM | 2b74cbb66ebb7954b48598869cde62aee021c49f | [
"MIT"
] | null | null | null |
// Generated from /home/wanket/Projects/DM/grammar/DM.g4 by ANTLR 4.7.2
#include "DMListener.h"
| 12.625 | 71 | 0.712871 | Wanket |
208c9c87b731803550534e629c27e52784c2aa37 | 3,207 | hpp | C++ | src/webots/vrml/WbFieldModel.hpp | binppo/webots | 9ac92fb46265173f25ac2358e052e3a04991cf01 | [
"Apache-2.0"
] | null | null | null | src/webots/vrml/WbFieldModel.hpp | binppo/webots | 9ac92fb46265173f25ac2358e052e3a04991cf01 | [
"Apache-2.0"
] | null | null | null | src/webots/vrml/WbFieldModel.hpp | binppo/webots | 9ac92fb46265173f25ac2358e052e3a04991cf01 | [
"Apache-2.0"
] | 1 | 2021-09-09T10:34:42.000Z | 2021-09-09T10:34:42.000Z | // Copyright 1996-2019 Cyberbotics Ltd.
//
// 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.
#ifndef WB_FIELD_MODEL_HPP
#define WB_FIELD_MODEL_HPP
//
// Description: a class that defines a model for a node's field
// The model is used in WbNodeModels.
//
#include <QtCore/QString>
#include <WbValue.hpp>
#include <WbVariant.hpp>
#include <core/WbConfig.h>
class WbTokenizer;
class WbToken;
class WbVrmlWriter;
class WB_LIB_EXPORT WbFieldModel {
public:
// create from tokenizer
WbFieldModel(WbTokenizer *tokenizer, const QString &worldPath);
// field name
const QString &name() const { return mName; }
// VRML export
bool isVrml() const { return mIsVrml; }
void write(WbVrmlWriter &writer) const;
bool isDeprecated() const { return mIsDeprecated; }
// Hidden field flag
bool isHiddenField() const { return mIsHiddenField; }
bool isHiddenParameter() const { return mIsHiddenParameter; }
bool isUnconnected() const { return mIsUnconnected; }
// default value
WbValue *defaultValue() const { return mDefaultValue; }
// accepted values
bool isValueAccepted(const WbValue *value, int *refusedIndex) const;
bool hasRestrictedValues() const { return !mAcceptedValues.isEmpty(); }
const QList<WbVariant> acceptedValues() const { return mAcceptedValues; }
// field type
WbFieldType type() const { return mDefaultValue->type(); }
bool isMultiple() const;
bool isSingle() const;
// useful tokens for error reporting
WbToken *nameToken() const { return mNameToken; }
// template
void setTemplateRegenerator(bool isRegenerator) { mIsTemplateRegenerator = isRegenerator; }
bool isTemplateRegenerator() const { return mIsTemplateRegenerator; }
// add/remove a reference to this field model from a field, a proto model or a node model instance
// when the reference count reaches zero (in unref()) the field model is deleted
void ref() const;
void unref() const;
// delete this field model
// reference count has to be zero
void destroy();
private:
WbFieldModel(const WbFieldModel &); // non constructor-copyable
WbFieldModel &operator=(const WbFieldModel &); // non copyable
~WbFieldModel();
QString mName;
bool mIsVrml;
bool mIsHiddenField, mIsHiddenParameter;
bool mIsTemplateRegenerator;
bool mIsDeprecated;
bool mIsUnconnected;
WbValue *mDefaultValue;
QList<WbVariant> mAcceptedValues; // TODO: const WbVariant
WbToken *mNameToken;
mutable int mRefCount;
WbValue *createValueForVrmlType(const QString &type, WbTokenizer *tokenizer, const QString &worldPath);
QList<WbVariant> getAcceptedValues(const QString &type, WbTokenizer *tokenizer, const QString &worldPath);
};
#endif
| 30.836538 | 108 | 0.741191 | binppo |
208e009d0f1045a14240785fd3d86d3cffe85fd9 | 5,020 | cpp | C++ | UnitTests/ZilchShaders/RendererShared.cpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 52 | 2018-09-11T17:18:35.000Z | 2022-03-13T15:28:21.000Z | UnitTests/ZilchShaders/RendererShared.cpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 1,409 | 2018-09-19T18:03:43.000Z | 2021-06-09T08:33:33.000Z | UnitTests/ZilchShaders/RendererShared.cpp | RachelWilSingh/ZeroCore | e9a2f82d395e5c89fb98eceac44ce60d016dbff3 | [
"MIT"
] | 26 | 2018-09-11T17:16:32.000Z | 2021-11-22T06:21:19.000Z | ///////////////////////////////////////////////////////////////////////////////
///
/// Authors: Joshua Davis
/// Copyright 2015, DigiPen Institute of Technology
///
///////////////////////////////////////////////////////////////////////////////
#include "Precompiled.hpp"
String mFragmentExtension = "zilchfrag";
String RenderResults::mZilchKey = "Zilch";
LogMessage::LogMessage()
{
}
LogMessage::LogMessage(StringParam filePath, StringParam lineNumber, StringParam message)
{
mFilePath = filePath;
mLineNumber = lineNumber;
mMessage = message;
}
//-------------------------------------------------------------------ErrorReporter
ErrorReporter::ErrorReporter()
{
mAssert = true;
}
void ErrorReporter::Report(StringParam message)
{
ZPrint("%s", message.c_str());
if(mAssert)
ZERO_DEBUG_BREAK;
}
void ErrorReporter::Report(StringParam filePath, StringParam lineNumber, StringParam header, StringParam message)
{
if(!header.Empty())
ZPrint("%s", header.c_str());
// Display the error in visual studio format (so double-clicking the error line will work)
ZPrint("%s(%s): \n\t%s\n", filePath.c_str(), lineNumber.c_str(), message.c_str());
if(mAssert)
ZERO_DEBUG_BREAK;
}
void ErrorReporter::Report(StringParam filePath, StringParam lineNumber, StringParam message)
{
Report(filePath, lineNumber, String(), message);
}
void ErrorReporter::ReportCompilationWarning(StringParam filePath, StringParam lineNumber, StringParam message)
{
bool assert = mAssert;
mAssert = false;
String header = "\n------------Compilation Warnings------------\n\n";
Report(filePath, lineNumber, header, message);
mAssert = assert;
}
void ErrorReporter::ReportCompilationWarning(const Array<LogMessage>& messages)
{
String header = "\n------------Compilation Warnings------------\n\n";
ZPrint("%s", header.c_str());
// Display the error in visual studio format (so double-clicking the error line will work)
for(size_t i = 0; i < messages.Size(); ++i)
{
const LogMessage& message = messages[i];
ZPrint("%s(%s): \n\t%s\n", message.mFilePath.c_str(), message.mLineNumber.c_str(), message.mMessage.c_str());
}
}
void ErrorReporter::ReportCompilationError(StringParam filePath, StringParam lineNumber, StringParam message)
{
String header = "\n------------Compilation Errors------------\n\n";
Report(filePath, lineNumber, header, message);
}
void ErrorReporter::ReportCompilationError(const Array<LogMessage>& messages)
{
String header = "\n------------Compilation Errors------------\n\n";
ZPrint("%s", header.c_str());
// Display the error in visual studio format (so double-clicking the error line will work)
for(size_t i = 0; i < messages.Size(); ++i)
{
const LogMessage& message = messages[i];
ZPrint("%s(%s): \n\t%s\n", message.mFilePath.c_str(), message.mLineNumber.c_str(), message.mMessage.c_str());
}
if(mAssert)
ZERO_DEBUG_BREAK;
}
void ErrorReporter::ReportLinkerError(StringParam filePath, StringParam lineNumber, StringParam message)
{
String header = "\n------------Linker Errors------------\n\n";
Report(filePath, lineNumber, header, message);
}
void ErrorReporter::ReportPostProcessError(StringParam testName, Vec4Param expected, Vec4Param result, int renderTargetIndex)
{
String expectedVectorStr = String::Format("(%g, %g, %g, %g)", expected.x, expected.y, expected.z, expected.w);
String resultVectorStr = String::Format("(%g, %g, %g, %g)", result.x, result.y, result.z, result.w);
String message = String::Format("Post process %s failed target %d. Expected %s but got %s", testName.c_str(), renderTargetIndex, expectedVectorStr.c_str(), resultVectorStr.c_str());
Report(message);
}
void ErrorReporter::DisplayDiffs(StringParam expectedFile, StringParam resultFile)
{
if(mAssert)
{
String parameters = String::Format("\"%s\" \"%s\"", resultFile.c_str(), expectedFile.c_str());
String arguments = String::Format("tortoisemerge.exe %s", parameters.c_str());
SimpleProcess process;
process.ExecProcess("tortoisemerge", arguments.c_str(), nullptr, true);
process.WaitForClose();
}
}
//-------------------------------------------------------------------FragmentInfo
FragmentInfo::FragmentInfo()
{
}
FragmentInfo::FragmentInfo(StringParam filePath)
{
mFilePath = filePath;
mFragmentCode = ReadFileIntoString(filePath);
}
FragmentInfo::FragmentInfo(StringParam filePath, StringParam fragmentCode)
{
mFilePath = filePath;
mFragmentCode = fragmentCode;
}
//-------------------------------------------------------------------BaseRenderer
BaseRenderer::BaseRenderer()
{
// buffer for fullscreen triangle
mFullScreenTriangleVerts[0] = {Vec3(-1, 3, 0), Vec2(0, -1), Vec4()};
mFullScreenTriangleVerts[1] = {Vec3(-1, -1, 0), Vec2(0, 1), Vec4()};
mFullScreenTriangleVerts[2] = {Vec3(3, -1, 0), Vec2(2, 1), Vec4()};
}
| 32.179487 | 184 | 0.629681 | RachelWilSingh |
208ef8e54f0800ecc365ca834868adf9d5b9d3d5 | 930 | cpp | C++ | Challenge-2020-07/3_sum.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2020-07/3_sum.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | Challenge-2020-07/3_sum.cpp | qiufengyu/LetsCode | 196fae0bf5c78ee20d05798a9439596e702fdb24 | [
"MIT"
] | null | null | null | #include "header.h"
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> res;
int size = nums.size();
sort(nums.begin(), nums.end());
for (int i = 0; i < size - 2; i++) {
if ( i > 0 && nums[i] > 0) break;
if (nums[i] == nums[i-1]) continue;
int l = i + 1, r = size - 1;
while (l < r) {
if (nums[i] + nums[l] + nums[r] == 0) {
res.push_back({nums[i], nums[l], nums[r]});
l++; r--;
while (l < r && nums[l] == nums[l - 1]) l++;
while (l < r && nums[r] == nums[r + 1]) r--;
} else if (nums[i] + nums[l] + nums[r] < 0) {
l++;
} else {
r--;
}
}
}
return res;
}
};
int main() {
return 0;
} | 29.0625 | 64 | 0.352688 | qiufengyu |
2092d9f3af99ecdf098a4d38c0c597b3884ff79e | 1,256 | cc | C++ | src/gui/ScreenManager.cc | shiromino/shiromino | 10e9bc650417ea05d5990836c64709af3f82ec5e | [
"CC-BY-4.0"
] | 23 | 2020-07-12T22:49:10.000Z | 2022-03-15T17:58:22.000Z | src/gui/ScreenManager.cc | shiromino/shiromino | 10e9bc650417ea05d5990836c64709af3f82ec5e | [
"CC-BY-4.0"
] | 64 | 2020-07-12T22:27:53.000Z | 2022-01-02T23:10:24.000Z | src/gui/ScreenManager.cc | shiromino/shiromino | 10e9bc650417ea05d5990836c64709af3f82ec5e | [
"CC-BY-4.0"
] | 8 | 2020-08-30T04:16:17.000Z | 2021-06-28T17:12:06.000Z | #include "ScreenManager.h"
#include "CoreState.h"
#include "game_qs.h"
GUIScreen *mainMenu_create(CoreState *cs, ScreenManager *mngr, BitFont& font)
{
SDL_Rect destRect = {0, 0, 640, 480};
GUIScreen *mainMenu = new GUIScreen {cs, "Main Menu", mainMenuInteractionCallback, destRect};
SDL_Rect pentominoRect = {20, 20, 100, 20};
Button *button1 = new Button {0, pentominoRect, "Pentomino C", font};
SDL_Rect g1MasterRect = {20, 42, 100, 20};
Button *button2 = new Button {1, g1MasterRect, "G1 Master", font};
mainMenu->addControlElement(button1);
mainMenu->addControlElement(button2);
return mainMenu;
}
void mainMenuInteractionCallback(GUIInteractable& interactable, GUIEvent& event)
{
if(event.type == mouse_clicked)
{
CoreState *cs = interactable.getWindow()->origin;
switch(interactable.ID)
{
default:
break;
case 0:
cs->p1game = qs_game_create(cs, 0, MODE_PENTOMINO, -1);
cs->p1game->init(cs->p1game);
break;
case 1:
cs->p1game = qs_game_create(cs, 0, MODE_G1_MASTER, -1);
cs->p1game->init(cs->p1game);
break;
}
}
}
| 27.911111 | 97 | 0.599522 | shiromino |
2096cde2cb4d401e3d8d98efe3743aa451fc3fff | 20,092 | cpp | C++ | tests/unittests/tiglWingGuideCurves.cpp | MarAlder/tigl | 76e1f1442a045e1b8b7954119ca6f9c883ea41e2 | [
"Apache-2.0"
] | null | null | null | tests/unittests/tiglWingGuideCurves.cpp | MarAlder/tigl | 76e1f1442a045e1b8b7954119ca6f9c883ea41e2 | [
"Apache-2.0"
] | null | null | null | tests/unittests/tiglWingGuideCurves.cpp | MarAlder/tigl | 76e1f1442a045e1b8b7954119ca6f9c883ea41e2 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2007-2014 German Aerospace Center (DLR/SC)
*
* Created: 2014-02-10 Tobias Stollenwerk <Tobias.Stollenwerk@dlr.de>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* @brief Tests for wing guide curves
*/
#include "test.h" // Brings in the GTest framework
#include "tigl.h"
#include "testUtils.h"
#include "tiglcommonfunctions.h"
#include "CSharedPtr.h"
#include "CCPACSConfigurationManager.h"
#include "BRep_Tool.hxx"
#include "TopoDS_Shape.hxx"
#include "TopTools_SequenceOfShape.hxx"
#include "TopExp_Explorer.hxx"
#include "BRepBuilderAPI_MakeEdge.hxx"
#include "BRepBuilderAPI_MakeWire.hxx"
#include "BRepTools_WireExplorer.hxx"
#include "Geom_Curve.hxx"
#include "Geom_Plane.hxx"
#include "Geom_Circle.hxx"
#include "gp_Pnt.hxx"
#include "gp_Vec.hxx"
#include "BRep_Builder.hxx"
#include "GeomAPI_IntCS.hxx"
#include "GeomAPI_ProjectPointOnCurve.hxx"
#include "CTiglError.h"
#include "CTiglTransformation.h"
#include "CCPACSGuideCurveProfile.h"
#include "CCPACSGuideCurveProfiles.h"
#include "generated/CPACSGuideCurve.h"
#include "CCPACSGuideCurves.h"
#include "CCPACSWingProfileGetPointAlgo.h"
#include "CCPACSGuideCurveAlgo.h"
#include "CCPACSWingSegment.h"
#include "tiglcommonfunctions.h"
/******************************************************************************/
typedef class CSharedPtr<tigl::CTiglPoint> PCTiglPoint;
class WingGuideCurve : public ::testing::Test
{
protected:
void SetUp() override
{
const char* filename = "TestData/simple_test_guide_curves.xml";
ReturnCode tixiRet;
TiglReturnCode tiglRet;
tiglHandle = -1;
tixiHandle = -1;
tixiRet = tixiOpenDocument(filename, &tixiHandle);
ASSERT_TRUE (tixiRet == SUCCESS);
tiglRet = tiglOpenCPACSConfiguration(tixiHandle, "GuideCurveModel", &tiglHandle);
ASSERT_TRUE(tiglRet == TIGL_SUCCESS);
// get guide curve
//tigl::CCPACSGuideCurve & guideCurve = config.GetGuideCurve("GuideCurveModel_Wing_Sec1_El1_Pro");
// constant values for the guide curve points
const double tempy[] = {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9};
beta=std::vector<double>(tempy, tempy + sizeof(tempy) / sizeof(tempy[0]) );
const double tempz[] = {0.0, 0.001, 0.003, 0.009, 0.008, 0.007, 0.006, 0.002, 0.0};
gamma=std::vector<double>(tempz, tempz + sizeof(tempz) / sizeof(tempz[0]) );
}
void TearDown() override
{
ASSERT_TRUE(tiglCloseCPACSConfiguration(tiglHandle) == TIGL_SUCCESS);
ASSERT_TRUE(tixiCloseDocument(tixiHandle) == SUCCESS);
tiglHandle = -1;
tixiHandle = -1;
}
TixiDocumentHandle tixiHandle;
TiglCPACSConfigurationHandle tiglHandle;
//tigl::CCPACSGuideCurve guideCurve;
std::vector<double> alpha;
std::vector<double> beta;
std::vector<double> gamma;
};
/******************************************************************************/
/**
* Tests CCPACSGuideCurveProfile class
*/
TEST_F(WingGuideCurve, tiglWingGuideCurve_CCPACSGuideCurveProfile)
{
tigl::CCPACSGuideCurveProfile guideCurve(NULL);
guideCurve.ReadCPACS(tixiHandle, "/cpacs/vehicles/profiles/guideCurves/guideCurveProfile[5]");
ASSERT_EQ(guideCurve.GetUID(), "GuideCurveModel_Wing_GuideCurveProfile_LeadingEdge_NonLinear");
ASSERT_EQ(guideCurve.GetName(), "NonLinear Leading Edge Guide Curve Profile for GuideCurveModel - Wing");
}
/**
* Tests CCPACSGuideCurveProfiles class
*/
TEST_F(WingGuideCurve, tiglWingGuideCurve_CCPACSGuideCurveProfiles)
{
tigl::CCPACSGuideCurveProfiles guideCurves(NULL);
guideCurves.ReadCPACS(tixiHandle, "/cpacs/vehicles/profiles/guideCurves");
ASSERT_EQ(guideCurves.GetGuideCurveProfileCount(), 6);
tigl::CCPACSGuideCurveProfile& guideCurve = guideCurves.GetGuideCurveProfile("GuideCurveModel_Wing_GuideCurveProfile_LeadingEdge_NonLinear");
ASSERT_EQ(guideCurve.GetUID(), "GuideCurveModel_Wing_GuideCurveProfile_LeadingEdge_NonLinear");
ASSERT_EQ(guideCurve.GetName(), "NonLinear Leading Edge Guide Curve Profile for GuideCurveModel - Wing");
}
/**
* Tests CCPACSGuideCurve class
*/
TEST_F(WingGuideCurve, tiglWingGuideCurve_CCPACSGuideCurve)
{
tigl::CCPACSGuideCurve guideCurve(NULL);
guideCurve.ReadCPACS(tixiHandle, "/cpacs/vehicles/aircraft/model/wings/wing/segments/segment[1]/guideCurves/guideCurve[1]");
ASSERT_EQ(guideCurve.GetUID(), "GuideCurveModel_Wing_Seg_1_2_GuideCurve_TrailingEdgeLower");
ASSERT_EQ(guideCurve.GetName(), "Lower Trailing Edge GuideCurve from GuideCurveModel - Wing Section 1 Main Element to GuideCurveModel - Wing Section 2 Main Element ");
ASSERT_EQ(guideCurve.GetGuideCurveProfileUID(), "GuideCurveModel_Wing_GuideCurveProfile_TrailingEdgeLower_NonLinear");
ASSERT_TRUE(!!guideCurve.GetFromRelativeCircumference_choice2());
ASSERT_EQ(*guideCurve.GetFromRelativeCircumference_choice2(), -1.0);
ASSERT_EQ(guideCurve.GetToRelativeCircumference(), -1.0);
}
/**
* Tests CCPACSGuideCurves class
*/
TEST_F(WingGuideCurve, tiglWingGuideCurve_CCPACSGuideCurves)
{
tigl::CCPACSGuideCurves guideCurves(NULL);
guideCurves.ReadCPACS(tixiHandle, "/cpacs/vehicles/aircraft/model/wings/wing/segments/segment[2]/guideCurves");
ASSERT_EQ(guideCurves.GetGuideCurveCount(), 3);
const tigl::CCPACSGuideCurve& guideCurve = guideCurves.GetGuideCurve("GuideCurveModel_Wing_Seg_2_3_GuideCurve_LeadingEdge");
ASSERT_EQ(guideCurve.GetUID(), "GuideCurveModel_Wing_Seg_2_3_GuideCurve_LeadingEdge");
ASSERT_EQ(guideCurve.GetName(), "Leading Edge GuideCurve from GuideCurveModel - Wing Section 2 Main Element to GuideCurveModel - Wing Section 3 Main Element ");
ASSERT_EQ(guideCurve.GetGuideCurveProfileUID(), "GuideCurveModel_Wing_GuideCurveProfile_LeadingEdge_NonLinear");
ASSERT_TRUE(!guideCurve.GetFromRelativeCircumference_choice2());
ASSERT_EQ(*guideCurve.GetFromGuideCurveUID_choice1(), "GuideCurveModel_Wing_Seg_1_2_GuideCurve_LeadingEdge_NonLinear" );
ASSERT_EQ(guideCurve.GetToRelativeCircumference(), 0.0);
}
/**
* Tests CCPACSWingProfileGetPointAlgo class
*/
TEST_F(WingGuideCurve, tiglWingGuideCurve_CCPACSWingProfileGetPointAlgoOnProfile)
{
// read configuration
tigl::CCPACSConfigurationManager& manager = tigl::CCPACSConfigurationManager::GetInstance();
tigl::CCPACSConfiguration& config = manager.GetConfiguration(tiglHandle);
// get upper and lower wing profile
tigl::CCPACSWingProfile& profile = config.GetWingProfile("GuideCurveModel_Wing_Sec3_El1_Pro");
TopoDS_Edge upperWire = profile.GetUpperWire();
TopoDS_Edge lowerWire = profile.GetLowerWire();
// concatenate wires
TopTools_SequenceOfShape wireContainer;
wireContainer.Append(lowerWire);
wireContainer.Append(upperWire);
// instantiate getPointAlgo
tigl::CCPACSWingProfileGetPointAlgo getPointAlgo(wireContainer);
gp_Pnt point;
gp_Vec tangent;
// plot points and tangents
int N = 20;
int M = 2;
for (int i=0; i<=N+2*M; i++) {
double da = 2.0/double(N);
double alpha = -1.0 -M*da + da*i;
getPointAlgo.GetPointTangent(alpha, point, tangent);
outputXY(i, point.X(), point.Z(), "./TestData/analysis/tiglWingGuideCurve_profileSamplePoints_points.dat");
outputXYVector(i, point.X(), point.Z(), tangent.X(), tangent.Z(), "./TestData/analysis/tiglWingGuideCurve_profileSamplePoints_tangents.dat");
// plot points and tangents with gnuplot by:
// echo "plot 'TestData/analysis/tiglWingGuideCurve_profileSamplePoints_tangents.dat' u 1:2:3:4 with vectors filled head lw 2, 'TestData/analysis/tiglWingGuideCurve_profileSamplePoints_points.dat' w linespoints lw 2" | gnuplot -persist
}
// leading edge: point must be zero and tangent must be in z-direction
getPointAlgo.GetPointTangent(0.0, point, tangent);
ASSERT_NEAR(point.X(), 0.0, 1E-10);
ASSERT_NEAR(point.Y(), 0.0, 1E-10);
ASSERT_NEAR(point.Z(), 0.0, 1E-10);
ASSERT_NEAR(tangent.X(), 0.0, 1E-10);
ASSERT_NEAR(tangent.Y(), 0.0, 1E-10);
// lower trailing edge
getPointAlgo.GetPointTangent(-1.0, point, tangent);
ASSERT_NEAR(point.X(), 1.0, 1E-5);
ASSERT_NEAR(point.Y(), 0.0, 1E-10);
ASSERT_NEAR(point.Z(), -0.003, 1E-5);
// upper trailing edge
getPointAlgo.GetPointTangent(1.0, point, tangent);
ASSERT_NEAR(point.X(), 1.0, 1E-10);
ASSERT_NEAR(point.Y(), 0.0, 1E-10);
ASSERT_NEAR(point.Z(), 0.00126, 1E-10);
// check if tangent is constant for alpha > 1
gp_Vec tangent2;
getPointAlgo.GetPointTangent(1.0, point, tangent);
getPointAlgo.GetPointTangent(2.0, point, tangent2);
ASSERT_EQ(tangent.X(), tangent2.X());
ASSERT_EQ(tangent.Y(), tangent2.Y());
ASSERT_EQ(tangent.Z(), tangent2.Z());
// check if tangent is constant for alpha < 1
getPointAlgo.GetPointTangent(-1.0, point, tangent);
getPointAlgo.GetPointTangent(-2.0, point, tangent2);
ASSERT_EQ(tangent.X(), tangent2.X());
ASSERT_EQ(tangent.Y(), tangent2.Y());
ASSERT_EQ(tangent.Z(), tangent2.Z());
}
/**
* Tests CCPACSWingProfileGetPointAlgo class
*/
TEST_F(WingGuideCurve, tiglWingGuideCurve_CCPACSWingProfileGetPointAlgoOnCircle)
{
double radius1=1.0;
gp_Pnt location1(radius1, 0.0, 0.0);
gp_Ax2 circlePosition1(location1, gp::DY(), gp::DX());
Handle(Geom_Circle) circle1 = new Geom_Circle(circlePosition1, radius1);
// cut into lower and upper half circle
double start=0.0;
double mid=start+M_PI;
double end=mid+M_PI;
TopoDS_Edge innerLowerEdge = BRepBuilderAPI_MakeEdge(circle1, start, mid);
TopoDS_Edge innerUpperEdge = BRepBuilderAPI_MakeEdge(circle1, mid, end);
// concatenate wires for guide curve algo
TopTools_SequenceOfShape innerWireContainer;
innerWireContainer.Append(innerLowerEdge);
innerWireContainer.Append(innerUpperEdge);
// instantiate getPointAlgo
tigl::CCPACSWingProfileGetPointAlgo getPointAlgo(innerWireContainer);
gp_Pnt point;
gp_Vec tangent;
// plot points and tangents
int N = 20;
int M = 2;
for (int i=0; i<=N+2*M; i++) {
double da = 2.0/double(N);
double alpha = -1.0 -M*da + da*i;
getPointAlgo.GetPointTangent(alpha, point, tangent);
outputXY(i, point.X(), point.Z(), "./TestData/analysis/tiglWingGuideCurve_circleSamplePoints_points.dat");
outputXYVector(i, point.X(), point.Z(), tangent.X(), tangent.Z(), "./TestData/analysis/tiglWingGuideCurve_circleSamplePoints_tangents.dat");
// plot points and tangents with gnuplot by:
// echo "plot 'TestData/analysis/tiglWingGuideCurve_circleSamplePoints_tangents.dat' u 1:2:3:4 with vectors filled head lw 2, 'TestData/analysis/tiglWingGuideCurve_circleSamplePoints_points.dat' w linespoints lw 2" | gnuplot -persist
}
// leading edge: point must be zero and tangent must be in z-direction and has to be of length pi
getPointAlgo.GetPointTangent(0.0, point, tangent);
ASSERT_NEAR(point.X(), 0.0, 1E-10);
ASSERT_NEAR(point.Y(), 0.0, 1E-10);
ASSERT_NEAR(point.Z(), 0.0, 1E-10);
ASSERT_NEAR(tangent.X(), 0.0, 1E-10);
ASSERT_NEAR(tangent.Y(), 0.0, 1E-10);
ASSERT_NEAR(tangent.Z(), M_PI, 1E-10);
// check lower trailing edge point. Tangent must be in negative z-direction has to be of length pi
getPointAlgo.GetPointTangent(-1.0, point, tangent);
ASSERT_NEAR(point.X(), 2.0, 1E-10);
ASSERT_NEAR(point.Y(), 0.0, 1E-10);
ASSERT_NEAR(point.Z(), 0.0, 1E-10);
ASSERT_NEAR(tangent.X(), 0.0, 1E-10);
ASSERT_NEAR(tangent.Y(), 0.0, 1E-10);
ASSERT_NEAR(tangent.Z(), -M_PI, 1E-10);
// check upper trailing edge point. Tangent must be in negative z-direction has to be of length pi
getPointAlgo.GetPointTangent(1.0, point, tangent);
ASSERT_NEAR(point.X(), 2.0, 1E-10);
ASSERT_NEAR(point.Y(), 0.0, 1E-10);
ASSERT_NEAR(point.Z(), 0.0, 1E-10);
ASSERT_NEAR(tangent.X(), 0.0, 1E-10);
ASSERT_NEAR(tangent.Y(), 0.0, 1E-10);
ASSERT_NEAR(tangent.Z(), -M_PI, 1E-10);
// check points and tangents for alpha > 1
gp_Pnt point2;
gp_Vec tangent2;
getPointAlgo.GetPointTangent(1.0, point, tangent);
getPointAlgo.GetPointTangent(2.0, point2, tangent2);
ASSERT_NEAR(point2.X(), 2.0, 1E-10);
ASSERT_NEAR(point2.Y(), 0.0, 1E-10);
ASSERT_NEAR(point2.Z(), -M_PI, 1E-10);
ASSERT_EQ(tangent.X(), tangent2.X());
ASSERT_EQ(tangent.Y(), tangent2.Y());
ASSERT_EQ(tangent.Z(), tangent2.Z());
ASSERT_NEAR(point.Distance(point2), M_PI, 1E-10);
// check if tangent is constant for alpha < 1
getPointAlgo.GetPointTangent(-1.0, point, tangent);
getPointAlgo.GetPointTangent(-2.0, point2, tangent2);
ASSERT_NEAR(point2.X(), 2.0, 1E-10);
ASSERT_NEAR(point2.Y(), 0.0, 1E-10);
ASSERT_NEAR(point2.Z(), M_PI, 1E-10);
ASSERT_EQ(tangent.X(), tangent2.X());
ASSERT_EQ(tangent.Y(), tangent2.Y());
ASSERT_EQ(tangent.Z(), tangent2.Z());
ASSERT_NEAR(point.Distance(point2), M_PI, 1E-10);
}
/**
* Tests CCPACSGuideCurveAlgo class
*/
TEST_F(WingGuideCurve, tiglWingGuideCurve_CCPACSGuideCurveAlgo)
{
// create two circles parallel to the x-z plane going through the y-axis at alpha=0
// the sense of rotation is such that the negative z-values come first
double radius1=1.0;
double radius2=1.0;
double distance=1.0;
gp_Pnt location1(radius1, 0.0, 0.0);
gp_Ax2 circlePosition1(location1, gp::DY(), gp::DX());
Handle(Geom_Circle) circle1 = new Geom_Circle(circlePosition1, radius1);
gp_Pnt location2(radius2, distance, 0.0);
gp_Ax2 circlePosition2(location2, gp::DY(), gp::DX());
Handle(Geom_Circle) circle2 = new Geom_Circle(circlePosition2, radius2);
// cut into lower and upper half circle
double start=0.0;
double mid=start+M_PI;
double end=mid+M_PI;
TopoDS_Edge innerLowerEdge = BRepBuilderAPI_MakeEdge(circle1, start, mid);
TopoDS_Edge innerUpperEdge = BRepBuilderAPI_MakeEdge(circle1, mid, end);
TopoDS_Edge outerLowerEdge = BRepBuilderAPI_MakeEdge(circle2, start, mid);
TopoDS_Edge outerUpperEdge = BRepBuilderAPI_MakeEdge(circle2, mid, end);
// concatenate wires for guide curve algo
TopTools_SequenceOfShape innerWireContainer;
innerWireContainer.Append(innerLowerEdge);
innerWireContainer.Append(innerUpperEdge);
TopTools_SequenceOfShape outerWireContainer;
outerWireContainer.Append(outerLowerEdge);
outerWireContainer.Append(outerUpperEdge);
// get guide curve profile
tigl::CCPACSGuideCurveProfile guideCurveProfile(NULL);
guideCurveProfile.ReadCPACS(tixiHandle, "/cpacs/vehicles/profiles/guideCurves/guideCurveProfile[5]");
std::vector<gp_Pnt> guideCurvePnts;
// instantiate guideCurveAlgo
guideCurvePnts = tigl::CCPACSGuideCurveAlgo<tigl::CCPACSWingProfileGetPointAlgo> (innerWireContainer, outerWireContainer, 0.0, 0.0, 2*radius1, 2*radius2, gp_Dir(1., 0., 0.), guideCurveProfile);
TopoDS_Edge guideCurveEdge = EdgeSplineFromPoints(guideCurvePnts);;
// check if guide curve runs through sample points
// get curve
Standard_Real u1, u2;
Handle(Geom_Curve) curve = BRep_Tool::Curve(guideCurveEdge, u1, u2);
// set predicted sample points from cpacs file
const double temp[] = {0.0, 0.0, -0.01, -0.03, -0.09, -0.08, -0.07, -0.06, -0.02, 0.0, 0.0};
std::vector<double> predictedSamplePointsX (temp, temp + sizeof(temp) / sizeof(temp[0]) );
for (unsigned int i = 0; i <= 10; ++i) {
// get intersection point of the guide curve with planes parallel to the x-z plane located at b
double b = i/double(10);
Handle(Geom_Plane) plane = new Geom_Plane(gp_Pnt(0.0, b*distance, 0.0), gp_Dir(0.0, 1.0, 0.0));
GeomAPI_IntCS intersection (curve, plane);
ASSERT_EQ(Standard_True, intersection.IsDone());
ASSERT_EQ(intersection.NbPoints(), 1);
gp_Pnt point = intersection.Point(1);
// scale sample points since 2nd profile is scaled by a factor 2
predictedSamplePointsX[i]*=(2*radius1+(2*radius2-2*radius1)*b);
// check is guide curve runs through the predicted sample points
ASSERT_NEAR(predictedSamplePointsX[i], point.X(), 1E-14);
ASSERT_NEAR(b*distance, point.Y(), 1E-14);
ASSERT_NEAR(0.0, point.Z(), 1E-14);
}
}
/**
* Tests wing segment guide curve routines
*/
TEST_F(WingGuideCurve, tiglWingGuideCurve_CCPACSWingSegment)
{
tigl::CCPACSConfigurationManager& manager = tigl::CCPACSConfigurationManager::GetInstance();
tigl::CCPACSConfiguration& config = manager.GetConfiguration(tiglHandle);
tigl::CCPACSWing& wing = config.GetWing(1);
ASSERT_EQ(wing.GetSegmentCount(),3);
tigl::CCPACSWingSegment& segment3 = wing.GetSegment(3);
ASSERT_TRUE(segment3.GetGuideCurves().get_ptr() != NULL);
tigl::CCPACSGuideCurves& guides = *segment3.GetGuideCurves();
ASSERT_EQ(guides.GetGuideCurveCount(), 3);
// obtain leading edge guide curve
TopoDS_Edge guideCurveEdge = guides.GetGuideCurve(1).GetCurve();
// check if guide curve runs through sample points
// get curve
Standard_Real u1, u2;
Handle(Geom_Curve) curve = BRep_Tool::Curve(guideCurveEdge, u1, u2);
// gamma values of cpacs data points
const double temp[] = {0.0, 0.0, -0.01, -0.03, -0.09, -0.08, -0.07, -0.06, -0.02, 0.0, 0.0};
std::vector<double> gammaDeviation (temp, temp + sizeof(temp) / sizeof(temp[0]) );
// number of sample points
unsigned int N=10;
// segement width
double width=2.0;
// segment position
double position=12.0;
// inner profile scale factor
double innerScale=1.0;
// outer profile scale factor
double outerScale=0.5;
// outer profile has a sweep angle of -30 degrees)
double angle=-M_PI/6.0;
for (unsigned int i = 0; i <= N; ++i) {
// get intersection point of the guide curve with planes in direction n located at b
// n is the y direction rotated pi/6 (30 degrees) inside the x-y plane
double b = width*i/double(N);
gp_Pnt planeLocation = gp_Pnt(b*sin(angle), b*cos(angle)+position, 0.0);
Handle(Geom_Plane) plane = new Geom_Plane(planeLocation, gp_Dir(0.0, 1.0, 0.0));
GeomAPI_IntCS intersection (curve, plane);
ASSERT_EQ(intersection.NbPoints(), 1);
gp_Pnt point = intersection.Point(1);
// start at segment leading edge
gp_Vec predictedPoint(0.0, position, 0.0);
// go along the leading edge
predictedPoint += gp_Vec(b*sin(angle), b*cos(angle), 0.0);
// scale sample points since outer profile's chordline smaller by a factor of 0.5
double s=(innerScale+(outerScale-innerScale)*i/double(N));
// go along direction perpendicular to the leading edge in the x-y plane
predictedPoint += gp_Vec(gammaDeviation[i]*s, 0.0, 0.0);
// check is guide curve runs through the predicted sample points
ASSERT_NEAR(predictedPoint.X(), point.X(), 1E-5);
ASSERT_NEAR(predictedPoint.Y(), point.Y(), 1E-5);
ASSERT_NEAR(predictedPoint.Z(), point.Z(), 1E-14);
}
}
| 43.678261 | 244 | 0.689578 | MarAlder |
209738ad9db6b4e407c0e8878036d5abafb69375 | 4,826 | cc | C++ | src/MyRunAction.cc | ax3l/GPos | 4555cead437f3ca847b6b8a2ce3227a47eb25af7 | [
"BSD-3-Clause-LBNL"
] | 3 | 2021-07-30T21:01:23.000Z | 2021-08-05T18:49:34.000Z | src/MyRunAction.cc | ax3l/GPos | 4555cead437f3ca847b6b8a2ce3227a47eb25af7 | [
"BSD-3-Clause-LBNL"
] | 3 | 2022-03-04T18:38:50.000Z | 2022-03-04T18:39:03.000Z | src/MyRunAction.cc | ax3l/GPos | 4555cead437f3ca847b6b8a2ce3227a47eb25af7 | [
"BSD-3-Clause-LBNL"
] | 2 | 2021-07-30T19:20:46.000Z | 2021-09-17T14:56:10.000Z | /**
* @file MyRunAction.cc
* @author Ligia Diana Amorim
* @date 06/2021
* @copyright GPos 2021 LBNL
*/
#include "MyRunAction.hpp"
/**
* Constructor, where memory size for particle data storage is allocated to ensure code doesn't run
* into memory load issues and tfoil parallel min/max values are initialized.
*
* @param[in] in Parameters read from input.txt file.
* @param[in] tf Pointer to final time of each event.
* @param[in] p Pointer to particle data of each event.
* @param[in] mq Pointer to particle species mass and charge information.
*/
MyRunAction::MyRunAction (Query in, G4double * tf, vector<Part> * p,
map<G4String,map<G4String,G4double>> * mq)
: G4UserRunAction(),
tfoil(0.0, G4MergeMode::kMaximum)
{
input = in;
tfoilM = tf;
particles = p;
// Multiplying factor should be the same as size set in MyEventAction().
// 20 is sufficient for up to 2 mm thick foils.
particles->reserve(input.np*40);
G4cout << "\nGPos only allocates 40 parts per MPI rank for each Event in each Run\n";
masscharge = mq;
if (input.ifback){
tfoil = G4Accumulable<G4double>( numeric_limits<G4double>::max(), G4MergeMode::kMinimum);
}
G4AccumulableManager* accumulableManager = G4AccumulableManager::Instance();
accumulableManager->RegisterAccumulable(tfoil);
}
/**
* Destructor.
*/
MyRunAction::~MyRunAction ()
{
}
/**
* Run start function, where the runManager saves the random number seed so that simulation results
* can be reproduced and the accumulable tfoil is initialized.
*/
void MyRunAction::BeginOfRunAction (const G4Run*)
{
G4RunManager::GetRunManager()->SetRandomNumberStore(false);
G4AccumulableManager* accumulableManager = G4AccumulableManager::Instance();
accumulableManager->Reset();
}
/**
* At the end of each run, tfoil is merged accross parallel threads and MPI ranks.
*
* @param run Run identifier pointer.
*/
void MyRunAction::EndOfRunAction (const G4Run* run)
{
G4int nofEvents = run->GetNumberOfEvent();
if (nofEvents == 0) return;
G4AccumulableManager* accumulableManager = G4AccumulableManager::Instance();
accumulableManager->Merge();
G4int rank = G4MPImanager::GetManager()->GetRank();
G4int tid = G4Threading::G4GetThreadId();
if (IsMaster()) {
*tfoilM = tfoil.GetValue();
if (input.debug) G4cout << "Accumulated tfoil = " << *tfoilM << " ns\n";
Reduce();
G4cout << "End of Global Run for MPI rank "
<< rank << " with total # Events : " << nofEvents
<< ", task " << tid << ", # parts : " << particles-> size() << "\n";
Properties p(input);
p.ComputeBeams(tfoilM, particles, masscharge);
}
else {
G4cout << "End of Local Run for MPI rank "
<< rank << " and task " << tid
<< " with # parts : " << particles-> size() << "\n";
}
}
/**
* At the end of each event, tfoil is updated to represent the min/max global time of all particles
* up to that event.
*
* @param tg Global end time of each event.
*/
void MyRunAction::ComputeTFoil (G4double tg){
if (input.ifback) {
tfoil = min(tfoil.GetValue(), tg);
}
else {
tfoil = max(tfoil.GetValue(), tg);
}
}
/**
* At the end of each event, particle data is added to particles vector.
*
* @param p vector containing all event particles data.
*/
void MyRunAction::AddParticles (vector<Part> p)
{
particles->insert(particles->begin(), p.begin(), p.end());
if (particles->size() == particles->capacity()) {
G4ExceptionDescription msg;
msg << "\nProgram ran out of memory -> Use more MPI ranks\n"
<< "#particles : " << particles->size()
<< "\ncapacity : " << particles->capacity() << "\n";
G4Exception("MyRunAction::AddParticles()",
"GPos error #9.0",FatalException,msg);
}
}
/**
* At the end of each event, each new species mass and charge information is added.
*
* @param mq map of species mass and charge.
*/
void MyRunAction::AddMapMQ (map<G4String,map<G4String,G4double>> mq)
{
for (const auto &name : mq){
if ( masscharge -> find(name.first) == masscharge -> end() ){
(*masscharge)[name.first] = mq[name.first];
}
}
}
/**
* Function to merge the global end time accross all MPI ranks (called after thread information is
* meged).
*/
void MyRunAction::Reduce ()
{
G4double tf = tfoil.GetValue();
MPI_Op op;
if (input.ifback) op = MPI_MIN;
else op = MPI_MAX;
G4int reduce = MPI_Allreduce(&tf, tfoilM, 1, MPI_DOUBLE,
op, MPI_COMM_WORLD);
if (reduce){
G4ExceptionDescription msg;
msg << "\nMPI Reduce failed\n";
G4Exception("MyRunAction::Reduce()",
"GPos error #9.1",FatalException,msg);
}
}
| 30.544304 | 100 | 0.640075 | ax3l |
2098ec4d8fdccefe938aa81571c5dcb93d2384c6 | 28,136 | cpp | C++ | tools/geomc/main.cpp | tonipes/wargrid | 2458f3f606f28fe6892c67eb736d5c8282d02c85 | [
"MIT"
] | null | null | null | tools/geomc/main.cpp | tonipes/wargrid | 2458f3f606f28fe6892c67eb736d5c8282d02c85 | [
"MIT"
] | null | null | null | tools/geomc/main.cpp | tonipes/wargrid | 2458f3f606f28fe6892c67eb736d5c8282d02c85 | [
"MIT"
] | null | null | null | // ============================================================================
// Kimberlite
//
// Copyright 2020 Toni Pesola. All Rights Reserved.
// ============================================================================
#define KB_TOOL_ONLY
#include <kb/foundation/core.h>
#include <kb/foundation/time.h>
#include <kb/foundation/array.h>
#include <kb/log.h>
#include <kbextra/cliargs.h>
#include <kbextra/geometry.h>
#include <kbextra/vertex.h>
#include "kb/foundation.cpp"
#include "kb/log.cpp"
#include "kbextra/texture.cpp"
#include "kbextra/vertex.cpp"
#include "kbextra/cliargs.cpp"
#include "kbextra/geometry.cpp"
#include <meshoptimizer/meshoptimizer.h>
#include <meshoptimizer/allocator.cpp>
#include <meshoptimizer/clusterizer.cpp>
#include <meshoptimizer/indexcodec.cpp>
#include <meshoptimizer/indexgenerator.cpp>
#include <meshoptimizer/overdrawanalyzer.cpp>
#include <meshoptimizer/overdrawoptimizer.cpp>
#include <meshoptimizer/simplifier.cpp>
#include <meshoptimizer/spatialorder.cpp>
#include <meshoptimizer/stripifier.cpp>
#include <meshoptimizer/vcacheanalyzer.cpp>
#include <meshoptimizer/vcacheoptimizer.cpp>
#include <meshoptimizer/vertexcodec.cpp>
#include <meshoptimizer/vertexfilter.cpp>
#include <meshoptimizer/vfetchanalyzer.cpp>
#include <meshoptimizer/vfetchoptimizer.cpp>
#define CGLTF_IMPLEMENTATION
#include <cgltf/cgltf.h>
#include <platform/platform_rwops_stdio.cpp>
#define EXIT_FAIL 1
#define EXIT_SUCCESS 0
#define POSITION_TYPE kb::float4
#define NORMAL_TYPE kb::float4
#define TANGENT_TYPE kb::float4
#define TEXCOORD_TYPE kb::float4
#define COLOR_TYPE kb::float4
#define JOINT_TYPE kb::float4
#define WEIGHT_TYPE kb::float4
const uint16_t POSITION_COMPONENT_COUNT = sizeof(POSITION_TYPE) / sizeof(float);
const uint16_t NORMAL_COMPONENT_COUNT = sizeof(NORMAL_TYPE) / sizeof(float);
const uint16_t TANGENT_COMPONENT_COUNT = sizeof(TANGENT_TYPE) / sizeof(float);
const uint16_t TEXCOORD_COMPONENT_COUNT = sizeof(TEXCOORD_TYPE) / sizeof(float);
const uint16_t COLOR_COMPONENT_COUNT = sizeof(COLOR_TYPE) / sizeof(float);
const uint16_t JOINT_COMPONENT_COUNT = sizeof(JOINT_TYPE) / sizeof(float);
const uint16_t WEIGHT_COMPONENT_COUNT = sizeof(WEIGHT_TYPE) / sizeof(float);
using IndexType = uint32_t;
// Temporary storage types
struct PrimitiveParseData {
uint32_t first_triangle;
uint32_t triangle_count;
int32_t material;
};
struct MeshParseData {
char name[KB_CONFIG_MAX_NAME_SIZE];
uint32_t prim_count;
PrimitiveParseData* prims;
};
struct VertexIndices {
IndexType position;
IndexType normal;
IndexType tangent;
IndexType texcoords;
IndexType colors;
IndexType weights;
IndexType joints;
};
struct IndexTriangle {
VertexIndices vert[3];
};
struct VertexData {
kb::array<POSITION_TYPE> positions;
kb::array<NORMAL_TYPE> normals;
kb::array<TANGENT_TYPE> tangents;
kb::array<TEXCOORD_TYPE> texcoords;
kb::array<COLOR_TYPE> colors;
kb::array<JOINT_TYPE> joints;
kb::array<WEIGHT_TYPE> weights;
kb::array<IndexTriangle> triangles;
};
template <typename T>
int32_t index_from(const T* f, const T* e) {
if (f == nullptr || e == nullptr || e < f) return -1;
return e - f;
}
void print_help(const char* error = nullptr) {
if (error != nullptr) printf("%s\n\n", error);
printf(
"Kimberlite geomc\n"
"\tUsage: geomc --input <file> --output <file> --index_size <int>\n"
"\tSet data to export with\n"
"\t\t--position\n"
"\t\t--normal\n"
"\t\t--tangent\n"
"\t\t--texcoord\n"
"\t\t--color\n"
"\t\t--joints\n"
"\t\t--weights\n"
);
}
kb_xform get_node_xform(cgltf_node* node) {
kb_xform xform;
xform.position = { 0, 0, 0 };
xform.scale = { 1, 1, 1 };
xform.rotation = { 0, 0, 0, 1 };
if (node->has_matrix) {
printf("\t\tTODO: decompose matrix\n");
}
if (node->has_translation) {
xform.position = { node->translation[0], node->translation[1], node->translation[2] };
}
if (node->has_rotation) {
xform.rotation = { node->rotation[0], node->rotation[1], node->rotation[2], node->rotation[3] };
}
if (node->has_scale) {
xform.scale = { node->scale[0], node->scale[1], node->scale[2] };
}
return xform;
}
int main(int argc, const char* argv[]) {
int exit_val = EXIT_FAIL;
cgltf_result result;
uint64_t total_optim_time = 0;
cgltf_options options = {};
cgltf_data* gltf_data = nullptr;
uint32_t input_size = 0;
void* input_data = nullptr;
kb_stream* rwops_in = nullptr;
kb_stream* rwops_out = nullptr;
const char* in_filepath = nullptr;
const char* out_filepath = nullptr;
MeshParseData* parse_meshes = nullptr;
VertexData vertex_data = {};
bool export_position = false;
bool export_normal = false;
bool export_tangent = false;
bool export_texcoord = false;
bool export_color = false;
bool export_joints = false;
bool export_weights = false;
int index_size = 0;
uint64_t max_prim_size = 0;
// Output geom
kb_geometry_data geom = {};
kb_cli_args args {};
kb_cliargs_init(&args, argc, argv);
if (kb_cliargs_has(&args, "help")) {
print_help();
goto end;
}
kb_cliargs_get_str(&args, &in_filepath, "input");
if (in_filepath == nullptr) {
print_help("Please specify input file with --input");
goto end;
}
kb_cliargs_get_str(&args, &out_filepath, "output");
if (out_filepath == nullptr) {
print_help("Please specify output file with --output");
goto end;
}
rwops_in = kb_stream_open_file(in_filepath, KB_FILE_MODE_READ);
if (!rwops_in) {
print_help("Unable to open input file");
goto end;
}
rwops_out = kb_stream_open_file(out_filepath, KB_FILE_MODE_WRITE);
if (!rwops_out) {
print_help("Unable to open output file");
goto end;
}
kb_cliargs_get_int(&args, &index_size, "index_size");
if (index_size != 32) {
print_help("Please specify index size with --index_size. Only 32 is supported");
goto end;
}
max_prim_size = ((uint64_t) 1 << index_size) - 1;
geom.index_size = index_size / 8;
export_position = kb_cliargs_has(&args, "position");
export_normal = kb_cliargs_has(&args, "normal");
export_tangent = kb_cliargs_has(&args, "tangent");
export_texcoord = kb_cliargs_has(&args, "texcoord");
export_color = kb_cliargs_has(&args, "color");
export_joints = kb_cliargs_has(&args, "joints");
export_weights = kb_cliargs_has(&args, "weights");
if (!(export_position || export_normal || export_tangent || export_texcoord || export_color || export_joints || export_weights)) {
print_help("Nothing to export");
goto end;
}
// Load
input_size = kb_stream_size(rwops_in);
input_data = KB_DEFAULT_ALLOC(input_size);
kb_stream_read(rwops_in, input_data, 1, input_size);
// Parse GLTF
result = cgltf_parse(&options, input_data, input_size, &gltf_data);
if (result != cgltf_result_success) {
print_help("Unable to parse input file");
goto end;
}
result = cgltf_load_buffers(&options, gltf_data, in_filepath);
if (result != cgltf_result_success) {
print_help("Failed to load buffers");
goto end;
}
geom.node_count = gltf_data->nodes_count;
geom.mesh_count = gltf_data->meshes_count;
geom.material_count = gltf_data->materials_count;
geom.nodes = KB_DEFAULT_ALLOC_TYPE(kb_node_data, geom.node_count);
geom.meshes = KB_DEFAULT_ALLOC_TYPE(kb_mesh_data, geom.mesh_count);
geom.materials = KB_DEFAULT_ALLOC_TYPE(kb_hash, geom.material_count);
parse_meshes = KB_DEFAULT_ALLOC_TYPE(MeshParseData, geom.mesh_count);
//#####################################################################################################################
// Parse
//#####################################################################################################################
{
// TODO: Skins
for (cgltf_size skin_i = 0; skin_i < gltf_data->skins_count; ++skin_i) {
cgltf_skin* src = &gltf_data->skins[skin_i];
}
// TODO: Animations
for (cgltf_size anim_i = 0; anim_i < gltf_data->animations_count; ++anim_i) {
cgltf_animation* src = &gltf_data->animations[anim_i];
}
// Node data
for (cgltf_size node_i = 0; node_i < geom.node_count; ++node_i) {
geom.nodes[node_i] = {};
cgltf_node* src = &gltf_data->nodes[node_i];
kb_node_data* dst = &geom.nodes[node_i];
kb_strcpy(dst->name, src->name);
dst->xform = get_node_xform(src);
dst->mesh = index_from(gltf_data->meshes, src->mesh);
}
// Materials
for (cgltf_size material_i = 0; material_i < geom.material_count; ++material_i) {
cgltf_material* src = &gltf_data->materials[material_i];
geom.materials[material_i] = kb_hash_string(src->name);
}
// Mesh Data
for (cgltf_size mesh_i = 0; mesh_i < geom.mesh_count; ++mesh_i) {
parse_meshes[mesh_i] = {};
geom.meshes[mesh_i] = {};
cgltf_mesh* src = &gltf_data->meshes[mesh_i];
MeshParseData* dst = &parse_meshes[mesh_i];
kb_strcpy(dst->name, src->name);
for (cgltf_size prim_i = 0; prim_i < src->primitives_count; ++prim_i) {
cgltf_primitive* prim = &src->primitives[prim_i];
uint32_t prim_first_triangle_index = vertex_data.triangles.count(); //kb_array_count(&vertex_data.triangles);
uint32_t prim_first_position_index = vertex_data.positions.count(); //kb_array_count(&vertex_data.positions);
uint32_t prim_first_normal_index = vertex_data.normals.count(); //kb_array_count(&vertex_data.normals);
uint32_t prim_first_tangent_index = vertex_data.tangents.count(); //kb_array_count(&vertex_data.tangents);
uint32_t prim_first_texcoord_index = vertex_data.texcoords.count(); //kb_array_count(&vertex_data.texcoords);
uint32_t prim_first_color_index = vertex_data.colors.count(); //kb_array_count(&vertex_data.colors);
uint32_t prim_first_joints_index = vertex_data.joints.count(); //kb_array_count(&vertex_data.joints);
uint32_t prim_first_weights_index = vertex_data.weights.count(); //kb_array_count(&vertex_data.weights);
// Vertex data
for (cgltf_size attrib_i = 0; attrib_i < prim->attributes_count; ++attrib_i) {
cgltf_attribute* attrib = &prim->attributes[attrib_i];
cgltf_accessor* accessor = attrib->data;
cgltf_size accessor_count = accessor->count;
cgltf_size accessor_stride = accessor->stride;
cgltf_size accessor_elem_size = cgltf_num_components(accessor->type);
if (attrib->index > 0) {
printf("ERROR: Only attrib index 0 is currently supported. Sorry!\n");
continue;
}
switch (attrib->type) {
case cgltf_attribute_type_position: {
uint32_t start = vertex_data.positions.count();
vertex_data.positions.resize(start + accessor_count);
for (uint32_t i = 0; i < accessor_count; i++) {
cgltf_accessor_read_float(accessor, i, (cgltf_float*) &vertex_data.positions.at(start + i), accessor_elem_size);
}
} break;
case cgltf_attribute_type_normal: {
uint32_t start = vertex_data.normals.count();
vertex_data.normals.resize(start + accessor_count);
for (uint32_t i = 0; i < accessor_count; i++) {
cgltf_accessor_read_float(accessor, i, (cgltf_float*) &vertex_data.normals.at(start + i), accessor_elem_size);
}
} break;
case cgltf_attribute_type_tangent: {
uint32_t start = vertex_data.tangents.count();
vertex_data.tangents.resize(start + accessor_count);
for (uint32_t i = 0; i < accessor_count; i++) {
cgltf_accessor_read_float(accessor, i, (cgltf_float*) &vertex_data.tangents.at(start + i), accessor_elem_size);
}
} break;
case cgltf_attribute_type_texcoord: {
uint32_t start = vertex_data.texcoords.count();
vertex_data.texcoords.resize(start + accessor_count);
for (uint32_t i = 0; i < accessor_count; i++) {
cgltf_accessor_read_float(accessor, i, (cgltf_float*) &vertex_data.texcoords.at(start + i), accessor_elem_size);
}
} break;
case cgltf_attribute_type_color: {
uint32_t start = vertex_data.colors.count();
vertex_data.colors.resize(start + accessor_count);
for (uint32_t i = 0; i < accessor_count; i++) {
cgltf_accessor_read_float(accessor, i, (cgltf_float*) &vertex_data.colors.at(start + i), accessor_elem_size);
}
} break;
case cgltf_attribute_type_joints: {
uint32_t start = vertex_data.joints.count();
vertex_data.joints.resize(start + accessor_count);
for (uint32_t i = 0; i < accessor_count; i++) {
cgltf_accessor_read_float(accessor, i, (cgltf_float*) &vertex_data.joints.at(start + i), accessor_elem_size);
}
} break;
case cgltf_attribute_type_weights: {
uint32_t start = vertex_data.weights.count();
vertex_data.weights.resize(start + accessor_count);
for (uint32_t i = 0; i < accessor_count; i++) {
cgltf_accessor_read_float(accessor, i, (cgltf_float*) &vertex_data.weights.at(start + i), accessor_elem_size);
}
} break;
default: {} break;
}
}
bool has_position = export_position && prim_first_position_index < vertex_data.positions.count();
bool has_normal = export_normal && prim_first_normal_index < vertex_data.normals.count();
bool has_tangent = export_tangent && prim_first_tangent_index < vertex_data.tangents.count();
bool has_texcoord = export_texcoord && prim_first_texcoord_index < vertex_data.texcoords.count();
bool has_color = export_color && prim_first_color_index < vertex_data.colors.count();
bool has_joints = export_joints && prim_first_joints_index < vertex_data.joints.count();
bool has_weights = export_weights && prim_first_weights_index < vertex_data.weights.count();
// Indices
if (prim->indices) {
cgltf_size index_count = prim->indices->count;
for (cgltf_size i = 0; i < index_count; i += 3) { // Tri
vertex_data.triangles.resize(vertex_data.triangles.count() + 1);
IndexTriangle& tri = vertex_data.triangles.back();
for (int v = 0; v < 3; ++v) {
uint32_t vertex_index = cgltf_accessor_read_index(prim->indices, v + i);
tri.vert[v].position = has_position ? prim_first_position_index + vertex_index : (IndexType) -1;
tri.vert[v].normal = has_normal ? prim_first_normal_index + vertex_index : (IndexType) -1;
tri.vert[v].tangent = has_tangent ? prim_first_tangent_index + vertex_index : (IndexType) -1;
tri.vert[v].texcoords = has_texcoord ? prim_first_texcoord_index + vertex_index : (IndexType) -1;
tri.vert[v].colors = has_color ? prim_first_color_index + vertex_index : (IndexType) -1;
tri.vert[v].joints = has_joints ? prim_first_joints_index + vertex_index : (IndexType) -1;
tri.vert[v].weights = has_weights ? prim_first_weights_index + vertex_index : (IndexType) -1;
}
}
}
// Split to primitives
uint32_t tri_count = vertex_data.triangles.count() - prim_first_triangle_index;
uint32_t tri_ind = 0;
while (tri_ind < tri_count) {
uint32_t tris_remaining = tri_count - tri_ind;
uint32_t prim_tri_count = kb_int_min(tris_remaining, max_prim_size / 3);
uint32_t idx = dst->prim_count++;
dst->prims = KB_DEFAULT_REALLOC_TYPE(PrimitiveParseData, dst->prims, dst->prim_count);
PrimitiveParseData* prim_out = &dst->prims[idx];
prim_out->first_triangle = prim_first_triangle_index + tri_ind;
prim_out->triangle_count = prim_tri_count;
prim_out->material = index_from(gltf_data->materials, prim->material);
tri_ind += prim_tri_count;
}
}
}
}
//#####################################################################################################################
// Process & Optimize
//#####################################################################################################################
{
bool has_position = false;
bool has_normal = false;
bool has_tangent = false;
bool has_texcoord = false;
bool has_color = false;
bool has_joints = false;
bool has_weights = false;
for (uint64_t tri_i = 0; tri_i < vertex_data.triangles.count(); ++tri_i) {
IndexTriangle& tri = vertex_data.triangles.at(tri_i);
for (uint32_t i = 0; i < 3; ++i) {
has_position |= tri.vert[i].position != (IndexType) -1;
has_normal |= tri.vert[i].normal != (IndexType) -1;
has_tangent |= tri.vert[i].tangent != (IndexType) -1;
has_texcoord |= tri.vert[i].texcoords != (IndexType) -1;
has_color |= tri.vert[i].colors != (IndexType) -1;
has_weights |= tri.vert[i].weights != (IndexType) -1;
has_joints |= tri.vert[i].joints != (IndexType) -1;
}
}
int32_t attrib_position = -1;
int32_t attrib_normal = -1;
int32_t attrib_tangent = -1;
int32_t attrib_texcoord = -1;
int32_t attrib_color = -1;
int32_t attrib_joints = -1;
int32_t attrib_weights = -1;
kb_vertex_layout vertex_layout;
kb_vertex_layout_begin(&vertex_layout);
if (has_position) attrib_position = kb_vertex_layout_add(&vertex_layout, KB_ATTRIB_FLOAT, POSITION_COMPONENT_COUNT);
if (has_normal) attrib_normal = kb_vertex_layout_add(&vertex_layout, KB_ATTRIB_FLOAT, NORMAL_COMPONENT_COUNT);
if (has_tangent) attrib_tangent = kb_vertex_layout_add(&vertex_layout, KB_ATTRIB_FLOAT, TANGENT_COMPONENT_COUNT);
if (has_texcoord) attrib_texcoord = kb_vertex_layout_add(&vertex_layout, KB_ATTRIB_FLOAT, TEXCOORD_COMPONENT_COUNT);
if (has_color) attrib_color = kb_vertex_layout_add(&vertex_layout, KB_ATTRIB_FLOAT, COLOR_COMPONENT_COUNT);
if (has_weights) attrib_weights = kb_vertex_layout_add(&vertex_layout, KB_ATTRIB_FLOAT, WEIGHT_COMPONENT_COUNT);
if (has_joints) attrib_joints = kb_vertex_layout_add(&vertex_layout, KB_ATTRIB_FLOAT, JOINT_COMPONENT_COUNT);
kb_vertex_layout_end(&vertex_layout);
uint32_t vertex_stride = kb_vertex_layout_stride(&vertex_layout);
uint64_t max_vertex_count = vertex_data.triangles.count() * 3;
uint64_t max_index_count = vertex_data.triangles.count() * 3;
uint8_t* geom_vert_data = (uint8_t*) KB_DEFAULT_ALLOC(max_vertex_count * vertex_stride);
IndexType* geom_ind_data = (IndexType*) KB_DEFAULT_ALLOC(sizeof(IndexType) * max_index_count);
uint64_t vertex_count = 0;
uint64_t index_count = 0;
for (uint32_t i = 0; i < geom.mesh_count; ++i) {
MeshParseData* mesh = &parse_meshes[i];
// Init output mesh
kb_mesh_data* mesh_out = &geom.meshes[i];
mesh_out->primitive_count = mesh->prim_count;
mesh_out->primitives = KB_DEFAULT_ALLOC_TYPE(kb_primitive_data, mesh_out->primitive_count);
kb_strcpy(mesh_out->name, mesh->name);
for (uint32_t i = 0; i < mesh->prim_count; i++) {
PrimitiveParseData* prim = &mesh->prims[i];
uint64_t prim_vertex_count = prim->triangle_count * 3;
uint64_t prim_index_count = prim->triangle_count * 3;
uint8_t* prim_vert_data = KB_DEFAULT_ALLOC_TYPE(uint8_t, prim_index_count * vertex_stride);
IndexType* prim_ind_data = KB_DEFAULT_ALLOC_TYPE(IndexType, prim_index_count);
uint32_t prim_vert = 0;
uint32_t prim_index = 0;
for (uint32_t tri_i = prim->first_triangle; tri_i < prim->first_triangle + prim->triangle_count; ++tri_i) {
IndexTriangle& tri = vertex_data.triangles.at(tri_i);
for (uint32_t v = 0; v < 3; ++v) {
const VertexIndices& vert = tri.vert[v];
if (has_position) {
uint32_t idx = vert.position == UINT32_MAX ? 0 : vert.position;
uint32_t attrib_size = kb_vertex_layout_size(&vertex_layout, attrib_position);
uint32_t attrib_offset = kb_vertex_layout_offset(&vertex_layout, attrib_position);
kb_memcpy_with_stride(prim_vert_data, &vertex_data.positions.at(idx), attrib_size, prim_vert, vertex_stride, attrib_offset);
}
if (has_normal) {
uint32_t idx = vert.normal == UINT32_MAX ? 0 : vert.normal;
uint32_t attrib_size = kb_vertex_layout_size(&vertex_layout, attrib_normal);
uint32_t attrib_offset = kb_vertex_layout_offset(&vertex_layout, attrib_normal);
kb_memcpy_with_stride(prim_vert_data, &vertex_data.normals.at(idx), attrib_size, prim_vert, vertex_stride, attrib_offset);
}
if (has_tangent) {
uint32_t idx = vert.tangent == UINT32_MAX ? 0 : vert.tangent;
uint32_t attrib_size = kb_vertex_layout_size(&vertex_layout, attrib_tangent);
uint32_t attrib_offset = kb_vertex_layout_offset(&vertex_layout, attrib_tangent);
kb_memcpy_with_stride(prim_vert_data, &vertex_data.tangents.at(idx), attrib_size, prim_vert, vertex_stride, attrib_offset);
}
if (has_texcoord) {
uint32_t idx = vert.texcoords == UINT32_MAX ? 0 : vert.texcoords;
uint32_t attrib_size = kb_vertex_layout_size(&vertex_layout, attrib_texcoord);
uint32_t attrib_offset = kb_vertex_layout_offset(&vertex_layout, attrib_texcoord);
kb_memcpy_with_stride(prim_vert_data, &vertex_data.texcoords.at(idx), attrib_size, prim_vert, vertex_stride, attrib_offset);
}
if (has_color) {
uint32_t idx = vert.colors == UINT32_MAX ? 0 : vert.colors;
uint32_t attrib_size = kb_vertex_layout_size(&vertex_layout, attrib_color);
uint32_t attrib_offset = kb_vertex_layout_offset(&vertex_layout, attrib_color);
kb_memcpy_with_stride(prim_vert_data, &vertex_data.colors.at(idx), attrib_size, prim_vert, vertex_stride, attrib_offset);
}
if (has_weights) {
uint32_t idx = vert.weights == UINT32_MAX ? 0 : vert.weights;
uint32_t attrib_size = kb_vertex_layout_size(&vertex_layout, attrib_weights);
uint32_t attrib_offset = kb_vertex_layout_offset(&vertex_layout, attrib_weights);
kb_memcpy_with_stride(prim_vert_data, &vertex_data.weights.at(idx), attrib_size, prim_vert, vertex_stride, attrib_offset);
}
if (has_joints) {
uint32_t idx = vert.joints == UINT32_MAX ? 0 : vert.joints;
uint32_t attrib_size = kb_vertex_layout_size(&vertex_layout, attrib_joints);
uint32_t attrib_offset = kb_vertex_layout_offset(&vertex_layout, attrib_joints);
kb_memcpy_with_stride(prim_vert_data, &vertex_data.joints.at(idx), attrib_size, prim_vert, vertex_stride, attrib_offset);
}
prim_ind_data[prim_index++] = prim_vert;
prim_vert++;
}
}
// Optimize primitive
uint64_t opt_start_time = kb_time_get_raw();
uint32_t* remap = KB_DEFAULT_ALLOC_TYPE(uint32_t, prim_vertex_count * 3);
uint32_t opt_vertex_count = meshopt_generateVertexRemap(remap, prim_ind_data, prim_index_count, prim_vert_data, prim_vertex_count, vertex_stride);
uint8_t* opt_vert_data = KB_DEFAULT_ALLOC_TYPE(uint8_t, opt_vertex_count * vertex_stride);
IndexType* opt_ind_data = KB_DEFAULT_ALLOC_TYPE(IndexType, prim_index_count);
meshopt_remapIndexBuffer (opt_ind_data, prim_ind_data, prim_index_count, remap);
meshopt_remapVertexBuffer (opt_vert_data, prim_vert_data, prim_vertex_count, vertex_stride, remap);
meshopt_optimizeVertexCache (opt_ind_data, opt_ind_data, prim_index_count, prim_vertex_count);
meshopt_optimizeOverdraw (opt_ind_data, opt_ind_data, prim_index_count, (float*) opt_vert_data, prim_vertex_count, vertex_stride, 1.05f);
meshopt_optimizeVertexFetch (opt_vert_data, opt_ind_data, prim_index_count, opt_vert_data, opt_vertex_count, vertex_stride);
total_optim_time += kb_time_get_raw() - opt_start_time;
mesh_out->primitives[i] = {};
mesh_out->primitives[i].first_vertex = vertex_count;
mesh_out->primitives[i].first_index = index_count;
mesh_out->primitives[i].vertex_count = opt_vertex_count;
mesh_out->primitives[i].index_count = prim_index_count;
mesh_out->primitives[i].material = prim->material;
// Copy data to main buffers
kb_memcpy(geom_ind_data + index_count , opt_ind_data , prim_index_count * sizeof(IndexType));
kb_memcpy(geom_vert_data + vertex_count * vertex_stride , opt_vert_data , opt_vertex_count * vertex_stride);
vertex_count += opt_vertex_count;
index_count += prim_index_count;
KB_DEFAULT_FREE(opt_vert_data);
KB_DEFAULT_FREE(opt_ind_data);
KB_DEFAULT_FREE(remap);
KB_DEFAULT_FREE(prim_vert_data);
KB_DEFAULT_FREE(prim_ind_data);
}
}
// Copy data to geom
geom.vertex_data_size = vertex_count * vertex_stride;
geom.index_data_size = index_count * sizeof(IndexType);
geom.vertex_data = KB_DEFAULT_ALLOC(geom.vertex_data_size);
geom.index_data = KB_DEFAULT_ALLOC(geom.index_data_size);
kb_memset(geom.vertex_data, '\0', geom.vertex_data_size);
kb_memset(geom.index_data, '\0', geom.index_data_size);
kb_memcpy(geom.vertex_data, geom_vert_data, geom.vertex_data_size);
kb_memcpy(geom.index_data, geom_ind_data, geom.index_data_size);
KB_DEFAULT_FREE(geom_vert_data);
KB_DEFAULT_FREE(geom_ind_data);
}
printf("All done! Total optimization time: %f\n", double(total_optim_time) / double(kb_time_get_frequency()));
//#####################################################################################################################
// Export
//#####################################################################################################################
kb_geometry_data_write(&geom, rwops_out);
exit_val = EXIT_SUCCESS;
end:
kb_stream_close(rwops_in);
kb_stream_close(rwops_out);
kb_geometry_data_destroy(&geom);
KB_DEFAULT_FREE(input_data);
kb_array_destroy(&vertex_data.positions);
kb_array_destroy(&vertex_data.normals);
kb_array_destroy(&vertex_data.tangents);
kb_array_destroy(&vertex_data.texcoords);
kb_array_destroy(&vertex_data.colors);
kb_array_destroy(&vertex_data.joints);
kb_array_destroy(&vertex_data.weights);
kb_array_destroy(&vertex_data.triangles);
return exit_val;
}
| 39.965909 | 156 | 0.634987 | tonipes |
20a308d486b7a79728cd79ccd05269545e2bae92 | 8,630 | cpp | C++ | src/GreenThumbFrame.cpp | captain-igloo/greenthumb | 39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72 | [
"MIT"
] | 3 | 2019-04-08T19:17:51.000Z | 2019-05-21T01:01:29.000Z | src/GreenThumbFrame.cpp | captain-igloo/greenthumb | 39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72 | [
"MIT"
] | 1 | 2019-04-30T23:39:06.000Z | 2019-07-27T00:07:20.000Z | src/GreenThumbFrame.cpp | captain-igloo/greenthumb | 39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72 | [
"MIT"
] | 1 | 2019-02-28T09:22:18.000Z | 2019-02-28T09:22:18.000Z | /**
* Copyright 2019 Colin Doig. Distributed under the MIT license.
*/
#include <time.h>
#include <wx/wx.h>
#include <wx/menu.h>
#include <wx/sizer.h>
#include <wx/treectrl.h>
#include "dialog/LoginDialog.h"
#include "dialog/Settings.h"
#include "entity/Config.h"
#include "worker/GetAccountDetails.h"
#include "worker/ListMarketCatalogue.h"
#include "worker/Login.h"
#include "ArtProvider.h"
#include "MenuTreeData.h"
#include "GreenThumb.h"
#include "GreenThumbFrame.h"
#include "MarketPanel.h"
#include "Util.h"
namespace greenthumb {
const wxString GreenThumbFrame::VIEW_ACCOUNT = "account";
const wxString GreenThumbFrame::VIEW_BETTING = "betting";
const uint32_t GreenThumbFrame::MAX_SESSION_AGE_SECONDS = 86400;
GreenThumbFrame::GreenThumbFrame()
: wxFrame(NULL, wxID_ANY, _T("Green Thumb"),
wxDefaultPosition, wxDefaultSize,
wxDEFAULT_FRAME_STYLE | wxNO_FULL_REPAINT_ON_RESIZE | wxMAXIMIZE),
workerManager(this), betfairMarkets(100) {
wxIcon greenthumbIcon;
greenthumbIcon.CopyFromBitmap(ArtProvider::GetBitmap(ArtProvider::IconId::GREENTHUMB));
SetIcon(greenthumbIcon);
mainView = entity::Config::GetConfigValue<wxString>("mainView", VIEW_BETTING);
CreateMenuBar();
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
SetSizer(sizer);
bettingPanel = new wxSplitterWindow(this, wxID_ANY);
bettingPanel->SetSashGravity(0.0);
bettingPanel->SetMinimumPaneSize(200);
wxPanel* eventTreePanel = new wxPanel(bettingPanel, wxID_ANY);
wxBoxSizer* eventTreeSizer = new wxBoxSizer(wxVERTICAL);
eventTree = new greenthumb::EventTree(eventTreePanel, wxID_ANY,
wxDefaultPosition, wxDefaultSize, wxTR_DEFAULT_STYLE);
eventTree->SetBetfairMarketsCache(&betfairMarkets);
eventTreeSizer->Add(eventTree, 1, wxEXPAND, 0);
eventTreePanel->SetSizer(eventTreeSizer);
eventTreePanel->SetInitialSize(wxSize(400, -1));
marketsPanel = new MarketPanels(bettingPanel, wxID_ANY);
marketsPanel->FitInside();
marketsPanel->SetScrollRate(5, 5);
wxBoxSizer* marketsSizer = new wxBoxSizer(wxVERTICAL);
marketsPanel->SetSizer(marketsSizer);
bettingPanel->SplitVertically(eventTreePanel, marketsPanel, 200);
accountPanel = new AccountPanel(this, wxID_ANY);
accountPanel->SetBetfairMarketsCache(&betfairMarkets);
if (mainView == VIEW_ACCOUNT) {
bettingPanel->Show(false);
} else {
accountPanel->Show(false);
}
sizer->Add(bettingPanel, 1, wxEXPAND, 0);
sizer->Add(accountPanel, 1, wxEXPAND, 0);
Bind(wxEVT_TREE_ITEM_ACTIVATED, &GreenThumbFrame::OnItemActivated, this, wxID_ANY);
workerManager.Bind(worker::GET_ACCOUNT_DETAILS);
workerManager.Bind(worker::LIST_MARKET_CATALOGUE);
Bind(worker::LIST_MARKET_CATALOGUE, &GreenThumbFrame::OnListMarketCatalogue, this, wxID_ANY);
CreateStatusBar(1);
}
void GreenThumbFrame::OpenLoginDialog() {
dialog::LoginDialog loginDialog(NULL, wxID_ANY, "Login");
if (loginDialog.ShowModal() == wxID_OK) {
eventTree->SyncMenu(false);
// get account currency if we don't already have it.
wxString currencySymbol = GetCurrencySymbol(
entity::Config::GetConfigValue<wxString>("accountCurrency", "?")
);
if (currencySymbol == "?") {
workerManager.RunWorker(new worker::GetAccountDetails(&workerManager));
}
}
}
void GreenThumbFrame::Login() {
wxString ssoid = entity::Config::GetConfigValue<wxString>("ssoid", "");
int64_t loginTime = entity::Config::GetConfigValue<int64_t>("loginTime", 0);
wxString appKey = greenthumb::entity::Config::GetConfigValue<wxString>("applicationKey", "");
if (appKey == "" || ssoid == "" || (time(NULL) - loginTime > MAX_SESSION_AGE_SECONDS)) {
OpenLoginDialog();
} else {
GreenThumb::GetBetfairApi().setApplicationKey(appKey.ToStdString());
GreenThumb::GetBetfairApi().setSsoid(ssoid.ToStdString());
}
}
void GreenThumbFrame::CreateMenuBar() {
wxMenuBar* menu = new wxMenuBar();
wxMenu* fileMenu = new wxMenu();
wxWindowID menuFileLoginId = wxWindow::NewControlId();
fileMenu->Append(menuFileLoginId, _("Log &in..."));
wxWindowID menuFileLogoutId = wxWindow::NewControlId();
fileMenu->Append(menuFileLogoutId, _("Log &out"));
wxWindowID menuFileRefreshMenuId = wxWindow::NewControlId();
fileMenu->Append(menuFileRefreshMenuId, _("Refresh &menu"));
wxWindowID menuFileSettingsId = wxWindow::NewControlId();
fileMenu->Append(menuFileSettingsId, _("&Settings..."));
fileMenu->Append(wxID_EXIT, _("E&xit"));
menu->Append(fileMenu, _("&File"));
Bind(wxEVT_MENU, &GreenThumbFrame::OnMenuFileExit, this, wxID_EXIT);
wxMenu* viewMenu = new wxMenu();
wxWindowID menuViewAccountId = wxWindow::NewControlId();
wxMenuItem* accountMenuItem = viewMenu->AppendRadioItem(menuViewAccountId, wxT("&Account"));
wxWindowID menuViewBettingId = wxWindow::NewControlId();
wxMenuItem* bettingMenuItem = viewMenu->AppendRadioItem(menuViewBettingId, wxT("&Betting"));
if (mainView == VIEW_ACCOUNT) {
accountMenuItem->Check();
} else {
bettingMenuItem->Check();
}
menu->Append(viewMenu, _("&View"));
wxMenu* helpMenu = new wxMenu();
helpMenu->Append(wxID_ABOUT, _("&About"));
menu->Append(helpMenu, _("&Help"));
SetMenuBar(menu);
Bind(wxEVT_MENU, &GreenThumbFrame::OnMenuFileLogin, this, menuFileLoginId);
Bind(wxEVT_MENU, &GreenThumbFrame::OnMenuFileLogout, this, menuFileLogoutId);
Bind(wxEVT_MENU, &GreenThumbFrame::OnMenuFileRefreshMenu, this, menuFileRefreshMenuId);
Bind(wxEVT_MENU, &GreenThumbFrame::OnMenuFileSettings, this, menuFileSettingsId);
Bind(wxEVT_MENU, &GreenThumbFrame::OnMenuViewAccount, this, menuViewAccountId);
Bind(wxEVT_MENU, &GreenThumbFrame::OnMenuViewBetting, this, menuViewBettingId);
Bind(wxEVT_MENU, &GreenThumbFrame::OnMenuHelpAbout, this, wxID_ABOUT);
}
void GreenThumbFrame::OnMenuFileLogin(const wxCommandEvent& menuEvent) {
OpenLoginDialog();
}
void GreenThumbFrame::OnMenuFileLogout(const wxCommandEvent& menuEvent) {
GreenThumb::GetBetfairApi().logout();
}
void GreenThumbFrame::OnMenuFileRefreshMenu(const wxCommandEvent& menuEvent) {
eventTree->SyncMenu();
}
void GreenThumbFrame::OnMenuFileSettings(const wxCommandEvent& menuEvent) {
dialog::Settings settings(NULL, wxID_ANY, "Settings");
settings.ShowModal();
}
void GreenThumbFrame::OnMenuFileExit(const wxCommandEvent& menuEvent) {
Close(true);
}
void GreenThumbFrame::OnMenuViewAccount(const wxCommandEvent& menuEvent) {
bettingPanel->Show(false);
accountPanel->Show(true);
Layout();
entity::Config::SetConfigValue("mainView", VIEW_ACCOUNT);
}
void GreenThumbFrame::OnMenuViewBetting(const wxCommandEvent& menuEvent) {
accountPanel->Show(false);
bettingPanel->Show(true);
Layout();
entity::Config::SetConfigValue("mainView", VIEW_BETTING);
}
void GreenThumbFrame::OnMenuHelpAbout(const wxCommandEvent& menuEvent) {
(void) wxMessageBox(_("Green Thumb\n(c) 2017 Colin Doig"),
_("Green Thumb"),
wxOK | wxICON_INFORMATION);
}
void GreenThumbFrame::OnItemActivated(const wxTreeEvent& treeEvent) {
wxTreeItemId itemId = treeEvent.GetItem();
MenuTreeData* data = dynamic_cast<MenuTreeData*>(eventTree->GetItemData(itemId));
if (data && data->valid && data->node.getType() == greentop::menu::Node::Type::MARKET) {
marketsPanel->AddMarket(data->node);
if (betfairMarkets.exists(data->node.getId())) {
marketsPanel->SetMarket(betfairMarkets.get(data->node.getId()));
} else {
if (!eventTree->ListMarketCatalogueInProgress()) {
std::set<std::string> marketIds = { data->node.getId() };
workerManager.RunWorker(
new worker::ListMarketCatalogue(&workerManager, marketIds)
);
}
}
}
}
void GreenThumbFrame::OnListMarketCatalogue(const wxThreadEvent& event) {
try {
std::map<std::string, entity::Market> markets =
event.GetPayload<std::map<std::string, entity::Market>>();
for (auto it = markets.begin(); it != markets.end(); ++it) {
if (it->second.HasMarketCatalogue()) {
betfairMarkets.put(it->second.GetMarketCatalogue().getMarketId(), it->second);
marketsPanel->SetMarket(it->second);
}
}
} catch (const std::exception& e) {
wxLogStatus(e.what());
}
}
}
| 33.710938 | 97 | 0.696524 | captain-igloo |
20a3608d9b8d9ca4382e05da72b8563d06559736 | 1,880 | cpp | C++ | C++/03-currying_lambda.cpp | duinomaker/LearningStuff | 34f8e3338dd2322013d519c19230c12fcb7897d4 | [
"CC0-1.0"
] | null | null | null | C++/03-currying_lambda.cpp | duinomaker/LearningStuff | 34f8e3338dd2322013d519c19230c12fcb7897d4 | [
"CC0-1.0"
] | null | null | null | C++/03-currying_lambda.cpp | duinomaker/LearningStuff | 34f8e3338dd2322013d519c19230c12fcb7897d4 | [
"CC0-1.0"
] | null | null | null | #include <deque>
#include <functional>
#include <iostream>
#include <iterator>
using namespace std;
// Automatic Currying
template<typename Ret, typename Arg>
auto curry_(function<Ret(Arg)> f) {
return f;
}
template<typename Ret, typename Arg, typename ...Args>
auto curry_(function<Ret(Arg, Args...)> f) {
return [=](Arg arg) {
function<Ret(Args...)> rest = [=](Args ...args) -> Ret {
return f(arg, args...);
};
return curry_(rest);
};
}
template<typename Ret, typename ...Args>
function<Ret(Args...)> make_func(Ret(*f)(Args...)) {
return f;
}
template<typename F>
auto curry(F f) {
return curry_(make_func(f));
}
// C#-Func-delegate-like `Func` template
template<typename Arg, typename ...Args>
struct Func_ {
using type = function<typename Func_<Args...>::type(Arg)>;
};
template<typename Arg>
struct Func_<Arg> {
using type = Arg;
};
template<typename ...Args>
using Func = typename Func_<Args...>::type;
// List-like operations
template<typename A>
deque<A> prepend(A x, deque<A> l) {
auto lp = l;
lp.push_front(x);
return lp;
}
// Functional utilities
template<typename F, typename G>
auto compose(F f, G g) {
return [=](auto x) { return f(g(x)); };
}
template<typename A, typename B>
B reduce(Func<A, B, B> f, B r, deque<A> l) {
if (l.empty()) {
return r;
}
auto rest = l;
auto first = rest.back();
rest.pop_back();
return reduce(f, f(first)(r), rest);
}
template<typename A, typename B>
auto map(Func<A, B> f) {
return curry(reduce<A, deque<B>>)(compose(curry(prepend<B>), f))({});
}
// Experiments
int main() {
auto f = [](int x) -> int { return x * 2; };
auto lst = deque<int>{1, 2, 3, 4, 5};
auto result = map<int, int>(f)(lst);
copy(result.begin(), result.end(), ostream_iterator<int>(cout, " "));
cout << endl;
}
| 20.659341 | 73 | 0.605319 | duinomaker |
20a736689f90c32671db6c5206d35bb451770a23 | 11,784 | cpp | C++ | src/interpreter.cpp | mujido/moove | 380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b | [
"Apache-2.0"
] | null | null | null | src/interpreter.cpp | mujido/moove | 380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b | [
"Apache-2.0"
] | null | null | null | src/interpreter.cpp | mujido/moove | 380fd0ea2eb2ad59b62a27bb86079ecb8c5b783b | [
"Apache-2.0"
] | null | null | null | #include "interpreter.hpp"
#include "reply.hpp"
#include "except.hpp"
#include "exec_state.hpp"
#include "opcodes.hpp"
#include "op_map.hpp"
#include "op_package.hpp"
#include "type_registry.hpp"
#include "listvar.hpp"
#include "strvar.hpp"
#include "intvar.hpp"
#include "realvar.hpp"
#include <iostream>
namespace Moove {
void Interpreter::clearTemps()
{
m_temps.clear();
}
void Interpreter::defineVariables(VariableDefMap& varDefs)
{
MOOVE_ASSERT(m_bcDebug, "cannot set variables in a non-debug compilation");
// make sure that the variable "args" has a value even if not defined in varDefs
std::string argsStr("args");
if (varDefs.find(argsStr) == varDefs.end()) {
ListVar::Container contents;
varDefs.emplace(argsStr, m_execState->listFactory().createList(contents));
}
for (auto& def : varDefs) {
// if this variable exists (has a defined symbol), set the value
Symbol varSym = m_bcDebug->varSymTable().findSymbol(def.first);
if(varSym) {
CodeVector::Word tempID = m_bcDebug->varIDBySymbol(varSym);
m_temps[tempID] = std::move(def.second);
}
}
}
bool Interpreter::execFinished()const
{
return m_retVal.get() != 0;
}
void Interpreter::execBuiltin()
{
std::unique_ptr<ListVar> args(popStack<ListVar>());
std::unique_ptr<StrVar> name(popStack<StrVar>());
Reply reply;
BuiltinRegistry::Function builtinFunc = m_execState->builtinRegistry().findFunction(name->value());
if(!builtinFunc) {
if(name->value() == "self") {
VariableDefMap recurseVarDefs;
std::string argsName("args");
recurseVarDefs.emplace(argsName, std::move(args));
reply.reset(Reply::NORMAL, m_execState->call(*m_bcDebug, recurseVarDefs, m_traceFlag));
} else
MOOVE_THROW("invalid builtin function: " + name->value());
} else
reply = builtinFunc(*m_execState, std::move(args));
// if at this point, a builtin was executed that does not return a value. return a bogus value
if (reply.normal() && reply.value())
m_stack.push_back(std::move(reply.value()));
else
m_stack.emplace_back(m_execState->intFactory().createValue(0));
}
void Interpreter::lengthList()
{
std::unique_ptr<ListVar> listVar = popStack<ListVar>();
IntVar::value_type size = listVar->contents()->size();
pushStack(std::move(listVar));
pushStack(std::unique_ptr<Variant>(m_execState->intFactory().createValue(size)));
}
void Interpreter::appendList()
{
boost::shared_ptr<Variant> valueVar(popStack<Variant>().release());
std::unique_ptr<ListVar> listVar(popStack<ListVar>());
listVar->appendValue(valueVar);
pushStack(std::move(listVar));
}
void Interpreter::indexList()
{
std::unique_ptr<IntVar> indexVar(popStack<IntVar>());
std::unique_ptr<ListVar> listVar(popStack<ListVar>());
MOOVE_ASSERT(indexVar->value() >= 1 && indexVar->value() <= listVar->contents()->size(), "index out of range");
pushStack(std::unique_ptr<Variant>((*listVar->contents())[indexVar->value() - 1]->clone()));
}
void Interpreter::setIndexList()
{
std::unique_ptr<Variant> valueVar = popStack<Variant>();
std::unique_ptr<IntVar> indexVar = popStack<IntVar>();
std::unique_ptr<ListVar> listVar = popStack<ListVar>();
MOOVE_ASSERT(indexVar->value() >= 1 && indexVar->value() <= listVar->contents()->size(), "index out of range");
listVar->setIndex(indexVar->value() - 1, boost::shared_ptr<Variant>(std::move(valueVar)));
pushStack(std::move(listVar));
}
void Interpreter::rangeList()
{
std::unique_ptr<IntVar> endVar(popStack<IntVar>());
std::unique_ptr<IntVar> startVar(popStack<IntVar>());
std::unique_ptr<ListVar> listVar(popStack<ListVar>());
MOOVE_ASSERT(startVar->value() >= 1 && startVar->value() <= listVar->contents()->size(), "index out of range");
MOOVE_ASSERT(endVar->value() >= startVar->value() && endVar->value() <= listVar->contents()->size(), "index out of range");
ListVar::Container range;
for(ListVar::Container::size_type i = startVar->value() - 1; i < endVar->value(); ++i)
range.push_back(boost::shared_ptr<Variant>((*listVar->contents())[i]->clone()));
pushStack(std::unique_ptr<Variant>(m_execState->listFactory().createList(range)));
}
void Interpreter::spliceList()
{
std::unique_ptr<ListVar> srcListVar(popStack<ListVar>());
std::unique_ptr<ListVar> destListVar(popStack<ListVar>());
ListVar::Container contents(*destListVar->contents());
contents.insert(contents.end(), srcListVar->contents()->begin(), srcListVar->contents()->end());
destListVar->setContents(contents);
pushStack(std::move(destListVar));
}
void Interpreter::stepInstruction()
{
assert(m_execState);
try {
MOOVE_ASSERT(m_curVect != 0, "NULL current CodeVector");
if(!execFinished()) {
Reply reply;
Opcode op = static_cast<Opcode>(*m_execPos++);
MOOVE_ASSERT(OpcodeInfo::validOp(op), "invalid opcode");
const OpcodeInfo::Op& opInfo = OpcodeInfo::getOp(op);
if(opInfo.isUnaryOp()) {
std::unique_ptr<Variant> operand(popStack<Variant>());
OperatorMap::UnaryDispatch dispatch = m_execState->operatorMap().findUnary(operand->factory().regEntry());
MOOVE_ASSERT(dispatch != 0, "unhandled unary operation");
reply = dispatch(op, std::move(operand));
MOOVE_ASSERT(reply.normal(), "error occured in unary operation");
pushStack(std::unique_ptr<Variant>(reply.value()->clone()));
} else if(opInfo.isBinaryOp()) {
std::unique_ptr<Variant> rightOperand(popStack<Variant>());
std::unique_ptr<Variant> leftOperand(popStack<Variant>());
OperatorMap::BinaryDispatch dispatch = m_execState->operatorMap().findBinary(leftOperand->factory().regEntry(),
rightOperand->factory().regEntry());
MOOVE_ASSERT(dispatch != 0, "unhandled binary operation");
reply = dispatch(op, std::move(leftOperand), std::move(rightOperand));
MOOVE_ASSERT(reply.normal(), "error occured in binary operation");
pushStack(std::unique_ptr<Variant>(reply.value()->clone()));
} else {
CodeVector::Word imm;
if (opInfo.hasImmediate()) {
if (opInfo.immediateType() == ImmediateValue::LABEL) {
imm = m_curVect->unpackWord(m_execPos, m_curVect->labelSize());
m_execPos += m_curVect->labelSize();
} else {
imm = m_curVect->unpackWord(m_execPos, m_bc->immediateSize(opInfo.immediateType()));
m_execPos += m_bc->immediateSize(opInfo.immediateType());
}
}
switch(op) {
case OP_DONE:
m_retVal.reset(m_execState->intFactory().createValue(0));
break;
case OP_JUMP_FALSE:
{
std::unique_ptr<Variant> testVar = popStack<Variant>();
if(testVar->truthValue()) {
// value is true, continue executing next instruction
break;
}
[[fallthrough]];
}
case OP_JUMP:
m_execPos = m_curVect->begin() + imm;
break;
case OP_RETURN:
m_retVal = popStack<Variant>();
break;
case OP_PUSH_LITERAL:
// don't push a value if it will be immediately popped
if (execFinished() || *m_execPos != OP_POP) {
pushStack(std::unique_ptr<Variant>(m_bc->literal(imm).clone()));
} else {
// skip OP_POP
++m_execPos;
}
break;
case OP_PUSH:
MOOVE_ASSERT(imm < m_temps.size(), "temporary ID out of range");
MOOVE_ASSERT(m_temps[imm] != nullptr, "undefined variable");
// don't push a value if it will be immediately popped
if (execFinished() || *m_execPos != OP_POP) {
pushStack(std::unique_ptr<Variant>(m_temps[imm]->clone()));
} else {
// skip OP_POP
++m_execPos;
}
break;
case OP_PUT:
{
MOOVE_ASSERT(imm < m_temps.size(), "temporary ID out of range");
if (!execFinished() && *m_execPos == OP_POP)
{
m_temps[imm] = popStack<Variant>();
++m_execPos;
}
else
m_temps[imm].reset(m_stack.back()->clone());
}
break;
case OP_POP:
popStack<Variant>();
break;
case OP_INDEX:
indexList();
break;
case OP_INDEX_SET:
setIndexList();
break;
case OP_RANGE:
rangeList();
break;
case OP_SPLICE:
spliceList();
break;
case OP_LENGTH:
lengthList();
break;
case OP_APPEND_LIST:
appendList();
break;
case OP_CALL_BUILTIN:
execBuiltin();
break;
default:
MOOVE_THROW((std::string)"not yet implemented: " + opInfo.name());
}
}
if (m_traceFlag) {
std::cerr << opInfo.name() << std::endl;
dumpStack(std::cerr);
}
}
} catch (...) {
std::cerr << "Error occured at BC position " << (m_execPos - m_curVect->begin()) << std::endl;
std::cerr << "\nStack dump:\n";
dumpStack(std::cerr);
throw;
}
}
Interpreter::Interpreter(const DebugBytecodeProgram& bc) : m_execState(0), m_curVect(0), m_traceFlag(false)
{
m_bc.reset(m_bcDebug = new DebugBytecodeProgram(bc));
// Setup with correct number of NULL initial values
for(TemporaryValues::size_type i = 0; i < 1000; ++i)
m_temps.push_back(0);
}
std::unique_ptr<Variant> Interpreter::run(ExecutionState& execState,
VariableDefMap& varDefs,
bool traceFlag)
{
m_retVal.reset();
m_stack.clear();
m_execState = &execState;
m_curVect = &m_bc->forkVector(0);
m_execPos = m_curVect->begin();
m_traceFlag = traceFlag;
defineVariables(varDefs);
while(!execFinished())
stepInstruction();
MOOVE_ASSERT(m_retVal.get() != 0, "no return value");
return std::move(m_retVal);
}
} // namespace Moove
| 34.761062 | 129 | 0.535048 | mujido |
20a7c5edda5c2d6f6d9acd98ea6904ba7f25d77c | 1,488 | cpp | C++ | 318-1.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 318-1.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | 318-1.cpp | Alex-Amber/LeetCode | c8d09e86cee52648f84ca2afed8dd0f13e51ab58 | [
"MIT"
] | null | null | null | class UnionFind {
private:
vector<int> p, size;
public:
UnionFind(int N) {
p.assign(N, 0);
size.assign(N, 1);
for (int i = 0; i < N; i++)
p[i] = i;
}
int findSet(int u) {
return p[u] == u ? u : p[u] = findSet(p[u]);
}
bool isSameSet(int u, int v) {
return findSet(u) == findSet(v);
}
void unionSet(int u, int v) {
if (!isSameSet(u, v)) {
int x = findSet(u), y = findSet(v);
if (size[x] > size[y]) {
p[y] = x;
size[x] += size[y];
}
else {
p[x] = y;
size[y] += size[x];
}
}
return;
}
};
class Solution {
public:
int maxProduct(vector<string>& words) {
int n = words.size();
vector<UnionFind> conns(26, UnionFind(n + 1));
for (int i = 0; i < n; i++) {
for (int j = 0; j < words[i].size(); j++) {
int ch = words[i][j] - 'a';
conns[ch].unionSet(i, n);
}
}
int res = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
bool share = false;
for (int k = 0; k < 26; k++)
share = share || conns[k].isSameSet(i, j);
if (!share)
res = max(res, (int)(words[i].size() * words[j].size()));
}
}
return res;
}
};
| 26.105263 | 77 | 0.373656 | Alex-Amber |
20acd4d87ed9f4c983a4b3ad07a07fe5507edbb5 | 563 | cpp | C++ | problem solving/bear-and-steady-gene.cpp | blog-a1/hackeRRank | 72923ee08c8759bd5a10ba6c390b6755fe2bd2e2 | [
"MIT"
] | 1 | 2021-01-13T11:52:27.000Z | 2021-01-13T11:52:27.000Z | problem solving/bear-and-steady-gene.cpp | blog-a1/hackeRRank | 72923ee08c8759bd5a10ba6c390b6755fe2bd2e2 | [
"MIT"
] | null | null | null | problem solving/bear-and-steady-gene.cpp | blog-a1/hackeRRank | 72923ee08c8759bd5a10ba6c390b6755fe2bd2e2 | [
"MIT"
] | null | null | null | #include<iostream>
#include<vector>
#include<algorithm>
#define INT_MAX 1000000000
using namespace std;
int main()
{
int len;
string s;cin>>len>>s;
int n=s.size(),a=n/4,b=0,c=0,d=0,gene=INT_MAX;
vector<int>m(128,0);
for(auto i:s) m[i]++;
for(int &i:m)
{
i=max(0,i-a);b+=i;
}
while(d<n)
{
if(m[s[d++]]-->0) b--;
while(b==0)
{
gene=min(gene,d-c);
if(++m[s[c++]]>0) b++;
}
}
cout<<gene<<endl;
return 0;
} | 20.107143 | 51 | 0.42984 | blog-a1 |
20acd8cb9b1b1f66f72c62cb38837fc199432b63 | 22,041 | cpp | C++ | fileformats/DFFaceTex.cpp | Pickle/XLEngine | c1aa5cf4584cb1940373505e4350336662fecf43 | [
"MIT"
] | 179 | 2018-04-04T12:35:07.000Z | 2021-11-28T03:53:30.000Z | fileformats/DFFaceTex.cpp | Pickle/XLEngine | c1aa5cf4584cb1940373505e4350336662fecf43 | [
"MIT"
] | 34 | 2018-04-04T17:15:40.000Z | 2021-11-28T03:01:22.000Z | fileformats/DFFaceTex.cpp | Pickle/XLEngine | c1aa5cf4584cb1940373505e4350336662fecf43 | [
"MIT"
] | 25 | 2018-04-04T23:49:46.000Z | 2022-02-05T01:02:58.000Z | /*===========================================================================
*
* File: DF_3DSTex.CPP
* Author: Dave Humphrey (uesp@m0use.net)
* Created On: Friday, March 22, 2002
*
* Implements 3DS specific texture and material related export functions
* for Daggerfall 3D objects.
*
*=========================================================================*/
/*
* This version modified on 07/05/2002 by Gavin Clayton for Daggerfall Explorer.
* For the original version of this file, please go to http://m0use.net/~uesp
* and download DFTo3DS by Dave Humprey.
*
*/
/* Include Files */
#include "DFFaceTex.h"
/*===========================================================================
*
* Local Function - boolean l_ComputeDFUVMatrixXY (Matrix, Params);
*
* Computes the UV conversion parameters from the given input based on
* the formula:
* U = AX + BY + D
*
* Returns FALSE on any error. For use on faces with 0 Z-coordinates.
*
*=========================================================================*/
bool DFFaceTex::l_ComputeDFUVMatrixXY(df3duvmatrix& Matrix, const df3duvparams_l& Params)
{
float Determinant;
float Xi[3], Yi[3], Zi[3];
/* Compute the determinant of the coefficient matrix */
Determinant = Params.X[0]*Params.Y[1] + Params.Y[0]*Params.X[2] +
Params.X[1]*Params.Y[2] - Params.Y[1]*Params.X[2] -
Params.Y[0]*Params.X[1] - Params.X[0]*Params.Y[2];
/* Check for a singular matrix indicating no valid solution */
if (Determinant == 0)
return (false);
/* Compute parameters of the the inverted XYZ matrix */
Xi[0] = ( Params.Y[1] - Params.Y[2]) / Determinant;
Xi[1] = (-Params.X[1] + Params.X[2]) / Determinant;
Xi[2] = ( Params.X[1]*Params.Y[2] - Params.X[2]*Params.Y[1]) / Determinant;
Yi[0] = (-Params.Y[0] + Params.Y[2]) / Determinant;
Yi[1] = ( Params.X[0] - Params.X[2]) / Determinant;
Yi[2] = (-Params.X[0]*Params.Y[2] + Params.X[2]*Params.Y[0]) / Determinant;
Zi[0] = ( Params.Y[0] - Params.Y[1]) / Determinant;
Zi[1] = (-Params.X[0] + Params.X[1]) / Determinant;
Zi[2] = ( Params.X[0]*Params.Y[1] - Params.X[1]*Params.Y[0]) / Determinant;
/* Compute the UV conversion parameters */
Matrix.UA = (Params.U[0]*Xi[0] + Params.U[1]*Yi[0] + Params.U[2]*Zi[0]);
Matrix.UB = (Params.U[0]*Xi[1] + Params.U[1]*Yi[1] + Params.U[2]*Zi[1]);
Matrix.UC = 0.0f;
Matrix.UD = (Params.U[0]*Xi[2] + Params.U[1]*Yi[2] + Params.U[2]*Zi[2]);;
Matrix.VA = (Params.V[0]*Xi[0] + Params.V[1]*Yi[0] + Params.V[2]*Zi[0]);
Matrix.VB = (Params.V[0]*Xi[1] + Params.V[1]*Yi[1] + Params.V[2]*Zi[1]);
Matrix.VC = 0.0f;
Matrix.VD = (Params.V[0]*Xi[2] + Params.V[1]*Yi[2] + Params.V[2]*Zi[2]);
return (true);
}
/*===========================================================================
* End of Function l_ComputeDFUVMatrixXY()
*=========================================================================*/
/*===========================================================================
*
* Local Function - boolean l_ComputeDFUVMatrixXZ (Matrix, Params);
*
* Computes the UV conversion parameters from the given input based on
* the formula:
* U = AX + CZ + D
*
* Returns FALSE on any error. For use on faces with 0 Y-coordinates.
*
*=========================================================================*/
bool DFFaceTex::l_ComputeDFUVMatrixXZ(df3duvmatrix& Matrix, const df3duvparams_l& Params)
{
float Determinant;
float Xi[3], Yi[3], Zi[3];
/* Compute the determinant of the coefficient matrix */
Determinant = Params.X[0]*Params.Z[2] + Params.Z[1]*Params.X[2] +
Params.Z[0]*Params.X[1] - Params.Z[0]*Params.X[2] -
Params.X[1]*Params.Z[2] - Params.X[0]*Params.Z[1];
/* Check for a singular matrix indicating no valid solution */
if (Determinant == 0)
return (false);
/* Compute parameters of the the inverted XYZ matrix */
Xi[0] = ( Params.Z[2] - Params.Z[1]) / Determinant;
Xi[1] = (-Params.X[1]*Params.Z[2] + Params.X[2]*Params.Z[1]) / Determinant;
Xi[2] = ( Params.X[1] - Params.X[2]) / Determinant;
Yi[0] = (-Params.Z[2] + Params.Z[0]) / Determinant;
Yi[1] = ( Params.X[0]*Params.Z[2] - Params.X[2]*Params.Z[0]) / Determinant;
Yi[2] = (-Params.X[0] + Params.X[2]) / Determinant;
Zi[0] = ( Params.Z[1] - Params.Z[0]) / Determinant;
Zi[1] = (-Params.X[0]*Params.Z[1] + Params.X[1]*Params.Z[0]) / Determinant;
Zi[2] = ( Params.X[0] - Params.X[1]) / Determinant;
/* Compute the UV conversion parameters */
Matrix.UA = (Params.U[0]*Xi[0] + Params.U[1]*Yi[0] + Params.U[2]*Zi[0]);
Matrix.UB = 0.0f;
Matrix.UC = (Params.U[0]*Xi[2] + Params.U[1]*Yi[2] + Params.U[2]*Zi[2]);
Matrix.UD = (Params.U[0]*Xi[1] + Params.U[1]*Yi[1] + Params.U[2]*Zi[1]);
Matrix.VA = (Params.V[0]*Xi[0] + Params.V[1]*Yi[0] + Params.V[2]*Zi[0]);
Matrix.VB = 0.0f;
Matrix.VC = (Params.V[0]*Xi[2] + Params.V[1]*Yi[2] + Params.V[2]*Zi[2]);
Matrix.VD = (Params.V[0]*Xi[1] + Params.V[1]*Yi[1] + Params.V[2]*Zi[1]);
return (true);
}
/*===========================================================================
* End of Function l_ComputeDFUVMatrixXZ()
*=========================================================================*/
/*===========================================================================
*
* Local Function - boolean l_ComputeDFUVMatrixYZ (Matrix, Params);
*
* Computes the UV conversion parameters from the given input based on
* the formula:
* U = BY + CZ + D
*
* Returns FALSE on any error. For use on faces with 0 X-coordinates.
*
*=========================================================================*/
bool DFFaceTex::l_ComputeDFUVMatrixYZ(df3duvmatrix& Matrix, const df3duvparams_l& Params)
{
float Determinant;
float Xi[3], Yi[3], Zi[3];
/* Compute the determinant of the coefficient matrix */
Determinant = Params.Y[1]*Params.Z[2] + Params.Y[0]*Params.Z[1] +
Params.Z[0]*Params.Y[2] - Params.Z[0]*Params.Y[1] -
Params.Y[0]*Params.Z[2] - Params.Z[1]*Params.Y[2];
/* Check for a singular matrix indicating no valid solution */
if (Determinant == 0)
return (false);
/* Compute parameters of the the inverted XYZ matrix */
Xi[0] = ( Params.Y[1]*Params.Z[2] - Params.Y[2]*Params.Z[1]) / Determinant;
Xi[1] = (-Params.Z[2] + Params.Z[1]) / Determinant;
Xi[2] = ( Params.Y[2] - Params.Y[1]) / Determinant;
Yi[0] = (-Params.Y[0]*Params.Z[2] + Params.Y[2]*Params.Z[0]) / Determinant;
Yi[1] = ( Params.Z[2] - Params.Z[0]) / Determinant;
Yi[2] = (-Params.Y[2] + Params.Y[0]) / Determinant;
Zi[0] = ( Params.Y[0]*Params.Z[1] - Params.Y[1]*Params.Z[0]) / Determinant;
Zi[1] = (-Params.Z[1] + Params.Z[0]) / Determinant;
Zi[2] = ( Params.Y[1] - Params.Y[0]) / Determinant;
/* Compute the UV conversion parameters */
Matrix.UA = 0.0f;
Matrix.UB = (Params.U[0]*Xi[1] + Params.U[1]*Yi[1] + Params.U[2]*Zi[1]);
Matrix.UC = (Params.U[0]*Xi[2] + Params.U[1]*Yi[2] + Params.U[2]*Zi[2]);
Matrix.UD = (Params.U[0]*Xi[0] + Params.U[1]*Yi[0] + Params.U[2]*Zi[0]);
Matrix.VA = 0.0f;
Matrix.VB = (Params.V[0]*Xi[1] + Params.V[1]*Yi[1] + Params.V[2]*Zi[1]);
Matrix.VC = (Params.V[0]*Xi[2] + Params.V[1]*Yi[2] + Params.V[2]*Zi[2]);
Matrix.VD = (Params.V[0]*Xi[0] + Params.V[1]*Yi[0] + Params.V[2]*Zi[0]);
return (true);
}
/*===========================================================================
* End of Function l_ComputeDFUVMatrixYZ()
*=========================================================================*/
/*===========================================================================
*
* Local Function - boolean l_ComputeDFUVMatrixXYZ (Matrix, Params);
*
* Computes the UV conversion parameters from the given input based on
* the formula:
* U = AX + BY + CZ
*
* Returns FALSE on any error.
*
*=========================================================================*/
bool DFFaceTex::l_ComputeDFUVMatrixXYZ(df3duvmatrix& Matrix, const df3duvparams_l& Params)
{
float Determinant;
float Xi[3], Yi[3], Zi[3];
/* Compute the determinant of the coefficient matrix */
Determinant = Params.X[0]*Params.Y[1]*Params.Z[2] +
Params.Y[0]*Params.Z[1]*Params.X[2] +
Params.Z[0]*Params.X[1]*Params.Y[2] -
Params.Z[0]*Params.Y[1]*Params.X[2] -
Params.Y[0]*Params.X[1]*Params.Z[2] -
Params.X[0]*Params.Z[1]*Params.Y[2];
/* Check for a singular matrix indicating no valid solution */
if (Determinant == 0)
{
//try a test...
float Max[3]={-1000000,-1000000,-1000000}, Min[3]={1000000,1000000,1000000};
for (int i=0; i<3; i++)
{
if (Params.X[i] < Min[0]) Min[0]= Params.X[i];
if (Params.Y[i] < Min[1]) Min[1]= Params.Y[i];
if (Params.Z[i] < Min[2]) Min[2]= Params.Z[i];
if (Params.X[i] > Max[0]) Max[0]= Params.X[i];
if (Params.Y[i] > Max[1]) Max[1]= Params.Y[i];
if (Params.Z[i] > Max[2]) Max[2]= Params.Z[i];
}
float dx = Max[0] - Min[0];
float dy = Max[1] - Min[1];
float dz = Max[2] - Min[2];
if ( dx <= dy && dx <= dz )
{
bool bYZ = l_ComputeDFUVMatrixYZ(Matrix, Params);
if ( bYZ == false )
{
bool bXZ = l_ComputeDFUVMatrixXZ(Matrix, Params);
if ( bXZ == false )
{
return l_ComputeDFUVMatrixXY(Matrix, Params);
}
else
{
return true;
}
}
else return true;
}
else if ( dy <= dx && dy <= dz )
{
bool bXZ = l_ComputeDFUVMatrixXZ(Matrix, Params);
if ( bXZ == false )
{
bool bYZ = l_ComputeDFUVMatrixYZ(Matrix, Params);
if ( bYZ == false )
{
return l_ComputeDFUVMatrixXY(Matrix, Params);
}
else return true;
}
else return true;
}
else
{
bool bXY = l_ComputeDFUVMatrixXY(Matrix, Params);
if ( bXY == false )
{
bool bXZ = l_ComputeDFUVMatrixXZ(Matrix, Params);
if ( bXZ == false )
{
return l_ComputeDFUVMatrixYZ(Matrix, Params);
}
else return true;
}
else return true;
}
}
/* Compute values of the the inverted XYZ matrix */
Xi[0] = ( Params.Y[1]*Params.Z[2] - Params.Y[2]*Params.Z[1]) / Determinant;
Xi[1] = (-Params.X[1]*Params.Z[2] + Params.X[2]*Params.Z[1]) / Determinant;
Xi[2] = ( Params.X[1]*Params.Y[2] - Params.X[2]*Params.Y[1]) / Determinant;
Yi[0] = (-Params.Y[0]*Params.Z[2] + Params.Y[2]*Params.Z[0]) / Determinant;
Yi[1] = ( Params.X[0]*Params.Z[2] - Params.X[2]*Params.Z[0]) / Determinant;
Yi[2] = (-Params.X[0]*Params.Y[2] + Params.X[2]*Params.Y[0]) / Determinant;
Zi[0] = ( Params.Y[0]*Params.Z[1] - Params.Y[1]*Params.Z[0]) / Determinant;
Zi[1] = (-Params.X[0]*Params.Z[1] + Params.X[1]*Params.Z[0]) / Determinant;
Zi[2] = ( Params.X[0]*Params.Y[1] - Params.X[1]*Params.Y[0]) / Determinant;
/* Compute the UV conversion parameters */
Matrix.UA = (Params.U[0]*Xi[0] + Params.U[1]*Yi[0] + Params.U[2]*Zi[0]);
Matrix.UB = (Params.U[0]*Xi[1] + Params.U[1]*Yi[1] + Params.U[2]*Zi[1]);
Matrix.UC = (Params.U[0]*Xi[2] + Params.U[1]*Yi[2] + Params.U[2]*Zi[2]);
Matrix.UD = 0.0f;
Matrix.VA = (Params.V[0]*Xi[0] + Params.V[1]*Yi[0] + Params.V[2]*Zi[0]);
Matrix.VB = (Params.V[0]*Xi[1] + Params.V[1]*Yi[1] + Params.V[2]*Zi[1]);
Matrix.VC = (Params.V[0]*Xi[2] + Params.V[1]*Yi[2] + Params.V[2]*Zi[2]);
Matrix.VD = 0.0f;
return (true);
}
/*===========================================================================
* End of Function l_ComputeDFUVMatrixXYZ()
*=========================================================================*/
/*===========================================================================
*
* Local Function - boolean l_ComputeDFUVMatrixXYZ1 (Matrix, Params);
*
* Computes the UV conversion parameters from the given input based on
* the formula:
* U = AX + BY + CZ + D
*
* Returns FALSE on any error. Only valid for faces that have more than
* 3 points.
*
*=========================================================================*/
bool DFFaceTex::l_ComputeDFUVMatrixXYZ1(df3duvmatrix& Matrix, const df3duvparams_l& Params)
{
float Determinant;
float Xi[4], Yi[4], Zi[4], Ai[4];
/* Compute the determinant of the coefficient matrix */
Determinant = Params.X[0]*Params.Y[1]*Params.Z[2]-Params.X[0]*Params.Y[1]*Params.Z[3]
+Params.X[0]*Params.Z[1]*Params.Y[3]-Params.X[0]*Params.Z[1]*Params.Y[2]
+Params.X[0]*Params.Y[2]*Params.Z[3]-Params.X[0]*Params.Z[2]*Params.Y[3]
-Params.Y[0]*Params.Z[1]*Params.X[3]+Params.Y[0]*Params.Z[1]*Params.X[2]
-Params.Y[0]*Params.X[2]*Params.Z[3]+Params.Y[0]*Params.Z[2]*Params.X[3]
-Params.Y[0]*Params.X[1]*Params.Z[2]+Params.Y[0]*Params.X[1]*Params.Z[3]
+Params.Z[0]*Params.X[2]*Params.Y[3]-Params.Z[0]*Params.Y[2]*Params.X[3]
+Params.Z[0]*Params.X[1]*Params.Y[2]-Params.Z[0]*Params.X[1]*Params.Y[3]
+Params.Z[0]*Params.Y[1]*Params.X[3]-Params.Z[0]*Params.Y[1]*Params.X[2]
-Params.X[1]*Params.Y[2]*Params.Z[3]+Params.X[1]*Params.Z[2]*Params.Y[3]
-Params.Y[1]*Params.Z[2]*Params.X[3]+Params.Y[1]*Params.X[2]*Params.Z[3]
-Params.Z[1]*Params.X[2]*Params.Y[3]+Params.Z[1]*Params.Y[2]*Params.X[3];
/* Check for a singular matrix indicating no valid solution */
if (Determinant == 0)
return (false);
/* Compute values of the the inverted XYZ matrix */
Xi[0] = Params.Y[1]*Params.Z[2] + Params.Z[1]*Params.Y[3] + Params.Y[2]*Params.Z[3] -
Params.Y[3]*Params.Z[2] - Params.Y[2]*Params.Z[1] - Params.Y[1]*Params.Z[3];
Xi[1] =-Params.X[1]*Params.Z[2] - Params.Z[1]*Params.X[3] - Params.X[2]*Params.Z[3] +
Params.X[3]*Params.Z[2] + Params.X[2]*Params.Z[1] + Params.X[1]*Params.Z[3];
Xi[2] = Params.X[1]*Params.Y[2] + Params.Y[1]*Params.X[3] + Params.X[2]*Params.Y[3] -
Params.X[3]*Params.Y[2] - Params.X[2]*Params.Y[1] - Params.X[1]*Params.Y[3];
Xi[3] =-Params.X[1]*Params.Y[2]*Params.Z[3] - Params.Y[1]*Params.Z[2]*Params.X[3] - Params.Z[1]*Params.X[2]*Params.Y[3] +
Params.X[3]*Params.Y[2]*Params.Z[1] + Params.X[2]*Params.Y[1]*Params.Z[3] + Params.X[1]*Params.Y[3]*Params.Z[2];
Yi[0] =-Params.Y[0]*Params.Z[2] - Params.Z[0]*Params.Y[3] - Params.Y[2]*Params.Z[3] +
Params.Y[3]*Params.Z[2] + Params.Y[2]*Params.Z[0] + Params.Y[0]*Params.Z[3];
Yi[1] = Params.X[0]*Params.Z[2] + Params.Z[0]*Params.X[3] + Params.X[2]*Params.Z[3] -
Params.X[3]*Params.Z[2] - Params.X[2]*Params.Z[0] - Params.X[0]*Params.Z[3];
Yi[2] =-Params.X[0]*Params.Y[2] - Params.Y[0]*Params.X[3] - Params.X[2]*Params.Y[3] +
Params.X[3]*Params.Y[2] + Params.X[2]*Params.Y[0] + Params.X[0]*Params.Y[3];
Yi[3] = Params.X[0]*Params.Y[2]*Params.Z[3] + Params.Y[0]*Params.Z[2]*Params.X[3] + Params.Z[0]*Params.X[2]*Params.Y[3] -
Params.X[3]*Params.Y[2]*Params.Z[0] - Params.X[2]*Params.Y[0]*Params.Z[3] - Params.X[0]*Params.Y[3]*Params.Z[2];
Zi[0] = Params.Y[0]*Params.Z[1] + Params.Z[0]*Params.Y[3] + Params.Y[1]*Params.Z[3]
-Params.Y[3]*Params.Z[1] - Params.Y[0]*Params.Z[0] - Params.Y[0]*Params.Z[3];
Zi[1] =-Params.X[0]*Params.Z[1] - Params.Z[0]*Params.Y[3] - Params.X[1]*Params.Z[3] +
Params.X[3]*Params.Z[1] + Params.X[1]*Params.Z[0] + Params.X[0]*Params.Z[3];
Zi[2] = Params.X[0]*Params.Y[1] + Params.Y[0]*Params.X[3] + Params.X[1]*Params.Y[3] -
Params.X[3]*Params.Y[1] - Params.X[1]*Params.Y[0] - Params.X[0]*Params.Y[3];
Zi[3] =-Params.X[0]*Params.Y[1]*Params.Z[3] - Params.Y[0]*Params.Z[1]*Params.X[3] - Params.Z[0]*Params.X[1]*Params.Y[3] +
Params.X[3]*Params.Y[1]*Params.Z[0] + Params.Z[1]*Params.Y[0]*Params.Z[3] + Params.X[0]*Params.Y[3]*Params.Z[1];
Ai[0] =-Params.Y[0]*Params.Z[1] - Params.Z[0]*Params.Y[2] - Params.Y[1]*Params.Z[2] +
Params.Y[2]*Params.Z[1] + Params.Y[1]*Params.Z[0] + Params.Y[0]*Params.Z[2];
Ai[1] = Params.X[0]*Params.Z[1] + Params.Z[0]*Params.X[2] + Params.X[1]*Params.Z[2] -
Params.X[1]*Params.Z[1] - Params.X[1]*Params.Z[0] - Params.X[0]*Params.Z[2];
Ai[2] =-Params.X[0]*Params.Y[1] - Params.Y[0]*Params.X[2] - Params.X[1]*Params.Y[2] +
Params.X[2]*Params.Y[1] + Params.X[1]*Params.Y[0] + Params.X[0]*Params.Y[2];
Ai[3] = Params.X[0]*Params.Y[1]*Params.Z[2] + Params.Y[0]*Params.Z[1]*Params.X[2] + Params.Z[0]*Params.X[1]*Params.Y[2] -
Params.X[2]*Params.Y[1]*Params.Z[0] - Params.X[1]*Params.Y[0]*Params.Z[2] - Params.X[0]*Params.Y[2]*Params.Z[1];
/* Compute the UV conversion parameters */
Matrix.UA = (Params.U[0]*Xi[0] + Params.U[1]*Yi[0] + Params.U[2]*Zi[0] + Params.U[3]*Ai[0]) / Determinant;
Matrix.UB = (Params.U[0]*Xi[1] + Params.U[1]*Yi[1] + Params.U[2]*Zi[1] + Params.U[3]*Ai[1]) / Determinant;
Matrix.UC = (Params.U[0]*Xi[2] + Params.U[1]*Yi[2] + Params.U[2]*Zi[2] + Params.U[3]*Ai[2]) / Determinant;
Matrix.UD = (Params.U[0]*Xi[3] + Params.U[1]*Yi[3] + Params.U[2]*Zi[3] + Params.U[3]*Ai[3]) / Determinant;
Matrix.VA = (Params.V[0]*Xi[0] + Params.V[1]*Yi[0] + Params.V[2]*Zi[0] + Params.V[3]*Ai[0]) / Determinant;
Matrix.VB = (Params.V[0]*Xi[1] + Params.V[1]*Yi[1] + Params.V[2]*Zi[1] + Params.V[3]*Ai[1]) / Determinant;
Matrix.VC = (Params.V[0]*Xi[2] + Params.V[1]*Yi[2] + Params.V[2]*Zi[2] + Params.V[3]*Ai[2]) / Determinant;
Matrix.VD = (Params.V[0]*Xi[3] + Params.V[1]*Yi[3] + Params.V[2]*Zi[3] + Params.V[3]*Ai[3]) / Determinant;
return (true);
}
/*===========================================================================
* End of Function l_ComputeDFUVMatrixXYZ1()
*=========================================================================*/
/*===========================================================================
*
* Function - boolean ComputeDFFaceTextureUVMatrix (Matrix, Face, Object);
*
* Calculates the transformation parameters to convert the face XYZ coordinates
* to texture UV coordinates for the given face, storing in the given matrix.
* Returns FALSE on any error. The function computes the A, B...F parameters
* for the equations:
* U = AX + BY + CZ
* V = DX + EY + FZ
*
*=========================================================================*/
bool DFFaceTex::ComputeDFFaceTextureUVMatrix( df3duvmatrix& Matrix, ObjVertex *pFaceVerts )
{
df3duvparams_l Params;
bool Result;
/* Initialize the conversion matrix */
Matrix.UA = 1.0f;
Matrix.UB = 0.0f;
Matrix.UC = 0.0f;
Matrix.UD = 0.0f;
Matrix.VA = 0.0f;
Matrix.VB = 1.0f;
Matrix.VC = 0.0f;
Matrix.UD = 0.0f;
/* Store the first 3 points of texture coordinates */
Params.U[0] = pFaceVerts[0].tu;
Params.U[1] = pFaceVerts[1].tu;
Params.U[2] = pFaceVerts[2].tu;
Params.V[0] = pFaceVerts[0].tv;
Params.V[1] = pFaceVerts[1].tv;
Params.V[2] = pFaceVerts[2].tv;
/* Get and store the 1st point coordinates in face */
Params.X[0] = pFaceVerts[0].pos.x;
Params.Y[0] = pFaceVerts[0].pos.y;
Params.Z[0] = pFaceVerts[0].pos.z;
/* Get and store the 2nd point coordinates in face */
Params.X[1] = pFaceVerts[1].pos.x;
Params.Y[1] = pFaceVerts[1].pos.y;
Params.Z[1] = pFaceVerts[1].pos.z;
/* Get and store the 3rd point coordinates in face */
Params.X[2] = pFaceVerts[2].pos.x;
Params.Y[2] = pFaceVerts[2].pos.y;
Params.Z[2] = pFaceVerts[2].pos.z;
/* get and store the 4th store coordinates, if any */
// NOTE: CDaggerTool::SetFaceUV has already accounted for presence/absence of 4th point
Params.X[3] = pFaceVerts[3].pos.x;
Params.Y[3] = pFaceVerts[3].pos.y;
Params.Z[3] = pFaceVerts[3].pos.z;
Vector3 S = pFaceVerts[1].pos - pFaceVerts[0].pos;
Vector3 T = pFaceVerts[2].pos - pFaceVerts[0].pos;
Vector3 N;
N.CrossAndNormalize(S, T);
/* Compute the solution using an XZ linear equation */
if ( fabsf(N.y) >= fabsf(N.x) && fabsf(N.y) >= fabsf(N.z) )//Params.Y[0] == Params.Y[1] && Params.Y[1] == Params.Y[2])
{
Result = l_ComputeDFUVMatrixXZ(Matrix, Params);
}
/* Compute the solution using an XY linear equation */
else if ( fabsf(N.z) >= fabsf(N.x) && fabsf(N.z) >= fabsf(N.y) )//if (Params.Z[0] == Params.Z[1] && Params.Z[1] == Params.Z[2])
{
Result = l_ComputeDFUVMatrixXY(Matrix, Params);
}
/* Compute the solution using an YZ linear equation */
else// if (Params.X[0] == Params.X[1] && Params.X[1] == Params.X[2])
{
Result = l_ComputeDFUVMatrixYZ(Matrix, Params);
}
/* Compute the solution using an XYZ linear equation */
/*else
{
Result = l_ComputeDFUVMatrixXYZ(Matrix, Params);
}*/
/* Attempt to use a 4x4 matrix solution if the previous ones failed */
if (!Result)
{
Result = l_ComputeDFUVMatrixXYZ1(Matrix, Params);
}
return (Result);
}
/*===========================================================================
* End of Function ComputeDFFaceTextureUVMatrix()
*=========================================================================*/
| 44.89002 | 132 | 0.517581 | Pickle |
20acef1fd0a9644eaf0ffa1eb7422fe27bc42720 | 1,098 | hpp | C++ | ringOS-Beta17/src/interrupts/interrupts.hpp | ElectroBoy404NotFound/ringOS | 9c109828363f3dc8b957dc58ecdfd5bc8d81e1a4 | [
"MIT"
] | 1 | 2021-12-05T15:49:40.000Z | 2021-12-05T15:49:40.000Z | ringOS-Beta17/src/interrupts/interrupts.hpp | ElectroBoy404NotFound/ringOS | 9c109828363f3dc8b957dc58ecdfd5bc8d81e1a4 | [
"MIT"
] | null | null | null | ringOS-Beta17/src/interrupts/interrupts.hpp | ElectroBoy404NotFound/ringOS | 9c109828363f3dc8b957dc58ecdfd5bc8d81e1a4 | [
"MIT"
] | null | null | null | #pragma once
#include "../BasicRenderer.hpp"
#include "../userinput/mouse.hpp"
#define PIC1_COMMAND 0x20
#define PIC1_DATA 0x21
#define PIC2_COMMAND 0xA0
#define PIC2_DATA 0xA1
#define PIC_EOI 0x20
#define ICW1_INIT 0x10
#define ICW1_ICW4 0x01
#define ICW4_8086 0x01
struct interrupt_frame;
__attribute__((interrupt)) void PageFault_Handler(interrupt_frame* frame, unsigned long int error_code);
__attribute__((interrupt)) void DoubleFault_Handler(interrupt_frame* frame, unsigned long int error_code);
__attribute__((interrupt)) void GPFault_Handler(interrupt_frame* frame, unsigned long int error_code);
__attribute__((interrupt)) void TSSFault_Handler(interrupt_frame* frame, unsigned long int error_code);
__attribute__((interrupt)) void DebugFault_Handler(interrupt_frame* frame);
__attribute__((interrupt)) void KeyboardInt_Handler(interrupt_frame* frame);
__attribute__((interrupt)) void MouseInt_Handler(interrupt_frame* frame);
__attribute__((interrupt)) void PITInt_Handler(interrupt_frame* frame);
void RemapPIC();
void PIC_EndMaster();
void PIC_EndSlave(); | 40.666667 | 107 | 0.802368 | ElectroBoy404NotFound |
20ad6d8357f4d99a588a0298105fb3ee24537be7 | 2,009 | cpp | C++ | Button.cpp | Loptt/pong-game | 6f3d2c561b75444ec0a7c39edd553a249168ec22 | [
"MIT"
] | null | null | null | Button.cpp | Loptt/pong-game | 6f3d2c561b75444ec0a7c39edd553a249168ec22 | [
"MIT"
] | null | null | null | Button.cpp | Loptt/pong-game | 6f3d2c561b75444ec0a7c39edd553a249168ec22 | [
"MIT"
] | null | null | null | //
// Created by charles on 6/02/18.
//
#include "Button.h"
#include <iostream>
Button::Button()
{
}
Button::Button(sf::Vector2f size, sf::Vector2f position, sf::Color color)
{
body.setPosition(position);
body.setSize(size);
body.setFillColor(color);
font.loadFromFile("Fonts/arial.ttf");
text.setFont(font);
text.setCharacterSize(20);
}
Button::~Button()
{
}
void Button::setSize(sf::Vector2f size)
{
body.setSize(size);
}
void Button::setPosition(sf::Vector2f pos)
{
body.setPosition(pos);
}
void Button::setPosition(int x, int y)
{
body.setPosition(x,y);
}
void Button::setText(std::string message)
{
text.setString(message);
}
void Button::setColor(sf::Color color)
{
body.setFillColor(color);
}
void Button::draw(sf::RenderWindow *window)
{
window->draw(body);
window->draw(text);
}
bool Button::isButtonClicked(sf::Vector2i mousePos)
{
if(mousePos.x > body.getPosition().x && mousePos.x < body.getPosition().x + body.getSize().x)
{
if (mousePos.y > body.getPosition().y && mousePos.y < body.getPosition().y + body.getSize().y)
{
return true;
}
}
return false;
}
void Button::updateButton()
{
sf::Vector2f position = body.getPosition();
sf::Vector2f size = body.getSize();
sf::FloatRect textRect = text.getLocalBounds();
text.setOrigin(textRect.left + textRect.width/2.0f, textRect.top + textRect.height/2.0f);
text.setPosition(sf::Vector2f(position.x+(size.x/2.0f),position.y+(size.y/2.0f)));
}
void Button::setFontFile(std::string fileName)
{
font.loadFromFile(fileName);
text.setFont(font);
}
void Button::setTextColor(sf::Color color)
{
text.setColor(color);
}
void Button::setTextSize(int size)
{
text.setCharacterSize(size);
}
void Button::configureText(std::string message, sf::Color color, int size, sf::Font *font)
{
text.setFont(*font);
text.setColor(color);
text.setCharacterSize(size);
text.setString(message);
}
| 18.775701 | 102 | 0.661025 | Loptt |
20aebcce7681a909e03b5a3d14bc64bdaf1bb9f7 | 4,333 | cpp | C++ | Src/Assets/BVHLoader.cpp | NauhWuun/GPU-Pathtracer | ffd0107ee58c489248b878ce8a7a09a17bb606df | [
"MIT"
] | 1 | 2021-08-07T08:24:48.000Z | 2021-08-07T08:24:48.000Z | Src/Assets/BVHLoader.cpp | NauhWuun/GPU-Pathtracer | ffd0107ee58c489248b878ce8a7a09a17bb606df | [
"MIT"
] | null | null | null | Src/Assets/BVHLoader.cpp | NauhWuun/GPU-Pathtracer | ffd0107ee58c489248b878ce8a7a09a17bb606df | [
"MIT"
] | null | null | null | #include "BVHLoader.h"
#include "Util/Util.h"
struct BVHFileHeader {
char filetype_identifier[4];
char filetype_version;
// Store settings with which the BVH was created
char underlying_bvh_type;
bool bvh_is_optimized;
int max_primitives_in_leaf;
float sah_cost_node;
float sah_cost_leaf;
int num_triangles;
int num_nodes;
int num_indices;
};
bool BVHLoader::try_to_load(const char * filename, MeshData & mesh_data, BVH & bvh) {
int bvh_filename_size = strlen(filename) + strlen(BVH_FILE_EXTENSION) + 1;
char * bvh_filename = MALLOCA(char, bvh_filename_size);
if (!bvh_filename) return false;
strcpy_s(bvh_filename, bvh_filename_size, filename);
strcat_s(bvh_filename, bvh_filename_size, BVH_FILE_EXTENSION);
// If the BVH file doesn't exist or is outdated return false
if (!Util::file_exists(bvh_filename) || !Util::file_is_newer(filename, bvh_filename)) {
FREEA(bvh_filename);
return false;
}
FILE * file; fopen_s(&file, bvh_filename, "rb");
BVHFileHeader header = { };
bool success = false;
if (!file) {
printf("WARNING: Unable to open BVH file '%s'!\n", bvh_filename);
goto exit;
}
fread(reinterpret_cast<char *>(&header), sizeof(header), 1, file);
if (strcmp(header.filetype_identifier, "BVH") != 0) {
printf("WARNING: BVH file '%s' has an invalid header!\n", bvh_filename);
goto exit;
}
if (header.filetype_version != BVH_FILETYPE_VERSION) goto exit;
// Check if the settings used to create the BVH file are the same as the current settings
if (header.underlying_bvh_type != UNDERLYING_BVH_TYPE ||
header.bvh_is_optimized != BVH_ENABLE_OPTIMIZATION ||
header.max_primitives_in_leaf != MAX_PRIMITIVES_IN_LEAF ||
header.sah_cost_node != SAH_COST_NODE ||
header.sah_cost_leaf != SAH_COST_LEAF
) {
printf("BVH file '%s' was created with different settings, rebuiling BVH from scratch.\n", bvh_filename);
goto exit;
}
mesh_data.triangle_count = header.num_triangles;
bvh.node_count = header.num_nodes;
bvh.index_count = header.num_indices;
mesh_data.triangles = new Triangle[mesh_data.triangle_count];
bvh.nodes = new BVHNode[bvh.node_count];
bvh.indices = new int [bvh.index_count];
fread(reinterpret_cast<char *>(mesh_data.triangles), sizeof(Triangle), mesh_data.triangle_count, file);
fread(reinterpret_cast<char *>(bvh.nodes), sizeof(BVHNode), bvh.node_count, file);
fread(reinterpret_cast<char *>(bvh.indices), sizeof(int), bvh.index_count, file);
printf("Loaded BVH %s from disk\n", bvh_filename);
success = true;
exit:
if (file) fclose(file);
FREEA(bvh_filename);
return success;
}
bool BVHLoader::save(const char * filename, MeshData & mesh_data, BVH & bvh) {
int bvh_filename_length = strlen(filename) + strlen(BVH_FILE_EXTENSION) + 1;
char * bvh_filename = MALLOCA(char, bvh_filename_length);
if (!bvh_filename) return false;
strcpy_s(bvh_filename, bvh_filename_length, filename);
strcat_s(bvh_filename, bvh_filename_length, BVH_FILE_EXTENSION);
FILE * file; fopen_s(&file, bvh_filename, "wb");
if (!file) {
printf("WARNING: Unable to save BVH to file %s!\n", bvh_filename);
FREEA(bvh_filename);
return false;
}
BVHFileHeader header = { };
header.filetype_identifier[0] = 'B';
header.filetype_identifier[1] = 'V';
header.filetype_identifier[2] = 'H';
header.filetype_identifier[3] = '\0';
header.filetype_version = BVH_FILETYPE_VERSION;
header.underlying_bvh_type = UNDERLYING_BVH_TYPE;
header.bvh_is_optimized = BVH_ENABLE_OPTIMIZATION;
header.max_primitives_in_leaf = MAX_PRIMITIVES_IN_LEAF;
header.sah_cost_node = SAH_COST_NODE;
header.sah_cost_leaf = SAH_COST_LEAF;
header.num_triangles = mesh_data.triangle_count;
header.num_nodes = bvh.node_count;
header.num_indices = bvh.index_count;
fwrite(reinterpret_cast<const char *>(&header), sizeof(header), 1, file);
fwrite(reinterpret_cast<const char *>(mesh_data.triangles), sizeof(Triangle), mesh_data.triangle_count, file);
fwrite(reinterpret_cast<const char *>(bvh.nodes), sizeof(BVHNode), bvh.node_count, file);
fwrite(reinterpret_cast<const char *>(bvh.indices), sizeof(int), bvh.index_count, file);
fclose(file);
FREEA(bvh_filename);
return true;
}
| 31.860294 | 111 | 0.720286 | NauhWuun |
20b00b18fb23b183cfc82e65db9b907c4feb165d | 755 | hpp | C++ | baselines/ck-pir/src/puncprf.hpp | eniac/incpir | a7d1bcf45b1bd5a3e98bcb421276ecd09c6eebdd | [
"MIT"
] | 3 | 2021-11-21T05:58:38.000Z | 2022-03-19T15:47:40.000Z | baselines/ck-pir/src/puncprf.hpp | eniac/incpir | a7d1bcf45b1bd5a3e98bcb421276ecd09c6eebdd | [
"MIT"
] | null | null | null | baselines/ck-pir/src/puncprf.hpp | eniac/incpir | a7d1bcf45b1bd5a3e98bcb421276ecd09c6eebdd | [
"MIT"
] | null | null | null | #pragma once
#ifndef _PUNCPRF
#define _PUNCPRF
#include <vector>
#include <bitset>
#include <set>
#include <array>
#include <tuple>
#include <cstring>
#include "pir.hpp"
using namespace std;
#define KeyLen 16
typedef std::array<uint8_t, KeyLen> Key;
typedef struct {
int height;
uint32_t bitvec = 0; // starting from right most bit
vector<Key> keys;
} PuncKeys;
void print_key(uint8_t *key);
tuple<Key, Key> PRG (Key key);
vector<uint32_t> BreadthEval(Key rootkey, int low, int high,
uint32_t lgn, uint32_t range);
uint32_t Eval (Key key, uint32_t x, uint32_t lgn, uint32_t range);
int EvalPunc (PuncKeys punc_keys, uint32_t x, uint32_t lgn, uint32_t range);
PuncKeys Punc(Key key, uint32_t punc_x, uint32_t lgn);
#endif
| 18.414634 | 76 | 0.72053 | eniac |
20b3b3b5c4ec4e5b3633641a674be51d8ea7cd2b | 16,421 | cpp | C++ | OpenGL/src/tests/TestAdvanced.cpp | ilkeraktug/OpenGL | ddf639166e75c96e02864dd92aea7a562cf36a72 | [
"MIT"
] | null | null | null | OpenGL/src/tests/TestAdvanced.cpp | ilkeraktug/OpenGL | ddf639166e75c96e02864dd92aea7a562cf36a72 | [
"MIT"
] | null | null | null | OpenGL/src/tests/TestAdvanced.cpp | ilkeraktug/OpenGL | ddf639166e75c96e02864dd92aea7a562cf36a72 | [
"MIT"
] | null | null | null | #include "TestAdvanced.h"
#include "VertexBufferLayout.h"
namespace test {
TestAdvanced::TestAdvanced()
: camera(&m_Proj, &m_View, 1280.0f, 768.0f)
{
GLCall(glEnable(GL_DEPTH_TEST));
GLCall(glDepthFunc(GL_LESS));
/* glEnable(GL_PROGRAM_POINT_SIZE);
GLCall(glEnable(GL_CULL_FACE));
GLCall(glCullFace(GL_BACK));
GLCall(glFrontFace(GL_CW));*/
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
m_CubeVAO = std::make_unique<VertexArray>();
m_PlaneVAO = std::make_unique<VertexArray>();
m_SkyboxVAO = std::make_unique<VertexArray>();
m_QuadVAO = std::make_unique<VertexArray>();
float cubeVertices[] = {
-1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // bottom-left
1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right
1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, // bottom-right
1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, // top-right
-1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, // bottom-left
-1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, // top-left
// front face
-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left
1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, // bottom-right
1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right
1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, // top-right
-1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, // top-left
-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // bottom-left
// left face
-1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right
-1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-left
-1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left
-1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-left
-1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-right
-1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-right
// right face
1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left
1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right
1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // top-right
1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, // bottom-right
1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, // top-left
1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, // bottom-left
// bottom face
-1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right
1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, // top-left
1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left
1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, // bottom-left
-1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, // bottom-right
-1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, // top-right
// top face
-1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left
1.0f, 1.0f , 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right
1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, // top-right
1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // bottom-right
-1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-left
-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f // bottom-left
};
float planeVertices[] = {
// positions // normals // texcoords
10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 0.0f,
-10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 10.0f,
10.0f, -0.5f, 10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 0.0f,
-10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 10.0f,
10.0f, -0.5f, -10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 10.0f
};
float skyboxVertices[] = {
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f
};
float quadVertices[] = {
// positions // texture Coords
-1.0f, 1.0f, 0.0f, 0.0f, 1.0f,
-1.0f, -1.0f, 0.0f, 0.0f, 0.0f,
1.0f, 1.0f, 0.0f, 1.0f, 1.0f,
1.0f, -1.0f, 0.0f, 1.0f, 0.0f,
};
int index = 0;
float offset = 0.1f;
for (int y = -10; y < 10; y += 2)
{
for (int x = -10; x < 10; x += 2)
{
glm::vec2 translation;
translation.x = (float)x / 10.0f + offset;
translation.y = (float)y / 10.0f + offset;
translations[index++] = translation;
}
}
m_QuadVAO->Bind();
m_QuadVBO = std::make_unique<VertexBuffer>(quadVertices, sizeof(quadVertices));
VertexBufferLayout other;
other.Push<float>(3);
other.Push<float>(3);
other.Push<float>(2);
m_QuadVAO->AddBuffer(*m_QuadVBO, other);
unsigned int instanceVBO;
glGenBuffers(1, &instanceVBO);
glBindBuffer(GL_ARRAY_BUFFER, instanceVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * 100, &translations[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), (void*)0);
glVertexAttribDivisor(2, 1);
m_QuadVAO->Unbind();
m_SkyboxVAO->Bind();
m_SkyboxVBO = std::make_unique<VertexBuffer>(skyboxVertices, sizeof(skyboxVertices));
VertexBufferLayout layout;
layout.Push<float>(3);
m_SkyboxVAO->AddBuffer(*m_SkyboxVBO, layout);
m_SkyboxVAO->Unbind();
m_CubeVAO->Bind();
m_CubeVBO = std::make_unique<VertexBuffer>(cubeVertices, sizeof(cubeVertices));
layout.Push<float>(2);
m_CubeVAO->AddBuffer(*m_CubeVBO, other);
m_CubeVAO->Unbind();
m_PlaneVAO->Bind();
m_PlaneVBO = std::make_unique<VertexBuffer>(planeVertices, sizeof(planeVertices));
m_PlaneVAO->AddBuffer(*m_PlaneVBO, other);
m_PlaneVAO->Unbind();
m_Shader = std::make_unique<Shader>("res/shaders/Advanced.shader");
m_DiffShader = std::make_unique<Shader>("res/shaders/Diff.shader");
m_BasicShader = std::make_unique<Shader>("res/shaders/Geometry.shader", 1);
m_SkyboxShader = std::make_unique<Shader>("res/shaders/Skybox.shader");
m_QuadShader = std::make_unique<Shader>("res/shaders/Quad.shader");
m_NormalShader = std::make_unique<Shader>("res/shaders/Normal.shader", 1);
m_LightShader = std::make_unique<Shader>("res/shaders/LightShader.shader");
m_PointLightShader = std::make_unique<Shader>("res/shaders/PointLight.shader", 1);
m_SkyboxTexture = std::make_unique<CubeMap>("res/textures/skybox");
m_MetalTexture = std::make_unique<Texture>("res/obj/teapot/diffuse.jpg");
m_Textures.emplace("Marble", new Texture("res/textures/marble.jpg"));
m_Textures.emplace("Wood", new Texture("res/textures/wood.png"));
glTextureParameteri(m_Textures["Wood"]->GetId(), GL_TEXTURE_WRAP_S, GL_REPEAT);
glTextureParameteri(m_Textures["Wood"]->GetId(), GL_TEXTURE_WRAP_T, GL_REPEAT);
//loadModel = new obj::Model("res/obj/backpack/backpack.obj");
m_FrameBuffer = std::make_unique<FrameBuffer>(1280, 768);
glGenFramebuffers(1, &depthMapFBO);
GLCall(glGenTextures(1, &shadowTex));
GLCall(glBindTexture(GL_TEXTURE_2D, shadowTex));
GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, m_ShadowWidth, m_ShadowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER));
float borderColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor);
GLCall(glBindFramebuffer(GL_FRAMEBUFFER, depthMapFBO));
GLCall(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadowTex, 0));
GLCall(glDrawBuffer(GL_NONE));
GLCall(glReadBuffer(GL_NONE));
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
std::cout << "Frame Buffer Succed" << std::endl;
GLCall(glBindFramebuffer(GL_FRAMEBUFFER, 0));
m_PointLightTexture = std::make_unique<CubeMap>(m_ShadowWidth, m_ShadowHeight);
GLCall(glGenFramebuffers(1, &pointDepthMapFBO));
GLCall(glBindFramebuffer(GL_FRAMEBUFFER, pointDepthMapFBO));
GLCall(glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, m_PointLightTexture->GetID(), 0));
GLCall(glReadBuffer(GL_NONE));
GLCall(glDrawBuffer(GL_NONE));
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE)
std::cout << "CubeMap Frame Buffer Succed" << std::endl;
GLCall(glBindFramebuffer(GL_FRAMEBUFFER, 0));
}
TestAdvanced::~TestAdvanced()
{
}
void TestAdvanced::OnRender()
{
camera.OnRender();
std::vector<glm::mat4> m_ShadowTransform;
m_ShadowTransform.push_back(m_ShadowProjection *
glm::lookAt(m_LightPosition, m_LightPosition + glm::vec3(1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0)));
m_ShadowTransform.push_back(m_ShadowProjection *
glm::lookAt(m_LightPosition, m_LightPosition + glm::vec3(-1.0, 0.0, 0.0), glm::vec3(0.0, -1.0, 0.0)));
m_ShadowTransform.push_back(m_ShadowProjection *
glm::lookAt(m_LightPosition, m_LightPosition + glm::vec3(0.0, 1.0, 0.0), glm::vec3(0.0, 0.0, 1.0)));
m_ShadowTransform.push_back(m_ShadowProjection *
glm::lookAt(m_LightPosition, m_LightPosition + glm::vec3(0.0, -1.0, 0.0), glm::vec3(0.0, 0.0, -1.0)));
m_ShadowTransform.push_back(m_ShadowProjection *
glm::lookAt(m_LightPosition, m_LightPosition + glm::vec3(0.0, 0.0, 1.0), glm::vec3(0.0, -1.0, 0.0)));
m_ShadowTransform.push_back(m_ShadowProjection *
glm::lookAt(m_LightPosition, m_LightPosition + glm::vec3(0.0, 0.0, -1.0), glm::vec3(0.0, -1.0, 0.0)));
//glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
{
glDisable(GL_DEPTH_TEST);
m_SkyboxShader->Bind();
m_SkyboxVAO->Bind();
glm::mat4 mvp = m_Proj * glm::mat4(glm::mat3(m_View));
m_SkyboxShader->SetUniformMat4f("u_MVP", mvp);
m_SkyboxTexture->Bind(0);
glDrawArrays(GL_TRIANGLES, 0, 36);
glEnable(GL_DEPTH_TEST);
m_SkyboxShader->Unbind();
}
{
glViewport(0, 0, m_ShadowWidth, m_ShadowHeight);
glBindFramebuffer(GL_FRAMEBUFFER, pointDepthMapFBO);
glClear(GL_DEPTH_BUFFER_BIT);
m_PointLightShader->Bind();
m_CubeVAO->Bind();
for (size_t i = 0; i < 6; i++)
{
m_PointLightShader->SetUniformMat4f("u_ShadowMat[" + std::to_string(i) + "]", m_ShadowTransform[i]);
}
m_PointLightShader->SetUniform1f("u_FarPlane", 25.0f);
m_PointLightShader->SetUniformVec3f("u_LightPos", m_LightPosition);
m_Model = glm::translate(glm::mat4(1.0f), CubeTranslationA);
m_PointLightShader->SetUniformMat4f("u_Model", m_Model);
glDrawArrays(GL_TRIANGLES, 0, 36);
m_Model = glm::translate(glm::mat4(1.0f), CubeTranslationB);
m_PointLightShader->SetUniformMat4f("u_Model", m_Model);
glDrawArrays(GL_TRIANGLES, 0, 36);
m_Model = glm::translate(glm::mat4(1.0f), CubeTranslationC);
m_PointLightShader->SetUniformMat4f("u_Model", m_Model);
glDrawArrays(GL_TRIANGLES, 0, 36);
m_CubeVAO->Unbind();
m_PlaneVAO->Bind();
m_Model = glm::translate(glm::mat4(1.0f), PlaneTranslationA);
glDrawArrays(GL_TRIANGLES, 0, 6);
m_PointLightShader->SetUniformMat4f("u_Model", m_Model);
m_PlaneVAO->Unbind();
m_PointLightShader->Unbind();
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
{
glViewport(0, 0, 1280, 768);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
m_CubeVAO->Bind();
m_QuadShader->Bind();
m_Textures["Wood"]->Bind(1);
m_PointLightTexture->Bind(2);
m_QuadShader->SetUniform1f("u_FarPlane", 25.0f);
m_Model = glm::translate(glm::mat4(1.0f), CubeTranslationA);
m_QuadShader->SetUniformMat4f("u_Proj", m_Proj);
m_QuadShader->SetUniformMat4f("u_View", m_View);
m_QuadShader->SetUniformMat4f("u_Model", m_Model);
m_QuadShader->SetUniformVec3f("u_LightPos", m_LightPosition);
m_QuadShader->SetUniformVec3f("u_CamPos", camera.GetCameraPosition());
m_QuadShader->SetUniform1i("diffuseTexture", 1);
m_QuadShader->SetUniform1i("cubeDepthTexture", 2);
glDrawArrays(GL_TRIANGLES, 0, 36);
m_Model = glm::translate(glm::mat4(1.0f), CubeTranslationB);
m_QuadShader->SetUniformMat4f("u_Model", m_Model);
glDrawArrays(GL_TRIANGLES, 0, 36);
m_Model = glm::translate(glm::mat4(1.0f), CubeTranslationC);
m_QuadShader->SetUniformMat4f("u_Model", m_Model);
glDrawArrays(GL_TRIANGLES, 0, 36);
m_CubeVAO->Unbind();
m_PlaneVAO->Bind();
m_Model = glm::translate(glm::mat4(1.0f), PlaneTranslationA);
m_QuadShader->SetUniformMat4f("u_Model", m_Model);
glDrawArrays(GL_TRIANGLES, 0, 6);
m_PlaneVAO->Unbind();
m_QuadShader->Unbind();
}
}
void TestAdvanced::OnUpdate(float deltaTime)
{
camera.OnUpdate();
}
void TestAdvanced::OnImGuiRender()
{
ImGui::Begin("Translate");
ImGui::SliderFloat3("Cube A", &CubeTranslationA.x, -50.0f, 50.0f);
ImGui::SliderFloat3("Cube B", &CubeTranslationB.x, -50.0f, 50.0f);
ImGui::SliderFloat3("Cube C", &CubeTranslationC.x, -50.0f, 50.0f);
ImGui::SliderFloat3("Plane A", &PlaneTranslationA.x, -50.0f, 50.0f);
ImGui::SliderFloat3("LightPosition", &m_LightPosition.x, -50.0f, 50.0f);
if (ImGui::Button("Reset"))
{
CubeTranslationA = glm::vec3(4.0f, -3.5f, -27.0);
CubeTranslationB = glm::vec3(2.0f, 3.0f, -24.0);
CubeTranslationC = glm::vec3(7.0f, -1.0f, -22.0);
PlaneTranslationA = glm::vec3(-1.0f, -4.0f, -27.0f);
m_LightPosition = glm::vec3(-12.0f, -1.0f, -40.0f);
}
ImGui::End();
camera.OnImGuiRender();
}
}
| 44.261456 | 140 | 0.552281 | ilkeraktug |
20b83187f4fb38bb0026e9567dc41efb574b4cd5 | 17,034 | cpp | C++ | game/shared/EntityClasses.cpp | xalalau/HLEnhanced | f108222ab7d303c9ed5a8e81269f9e949508e78e | [
"Unlicense"
] | 83 | 2016-06-10T20:49:23.000Z | 2022-02-13T18:05:11.000Z | game/shared/EntityClasses.cpp | xalalau/HLEnhanced | f108222ab7d303c9ed5a8e81269f9e949508e78e | [
"Unlicense"
] | 26 | 2016-06-16T22:27:24.000Z | 2019-04-30T19:25:51.000Z | game/shared/EntityClasses.cpp | xalalau/HLEnhanced | f108222ab7d303c9ed5a8e81269f9e949508e78e | [
"Unlicense"
] | 58 | 2016-06-10T23:52:33.000Z | 2021-12-30T02:30:50.000Z | #include <algorithm>
#include <cstdio>
#include "extdll.h"
#include "util.h"
#include "DefaultClassifications.h"
#include "EntityClasses.h"
//TODO: move to utility header - Solokiller
//Taken from cppreference.com documentation for std::lower_bound - Solokiller
template<class ForwardIt, class T, class Compare = std::less<>>
ForwardIt binary_find( ForwardIt first, ForwardIt last, const T& value, Compare comp = {} )
{
// Note: BOTH type T and the type after ForwardIt is dereferenced
// must be implicitly convertible to BOTH Type1 and Type2, used in Compare.
// This is stricter than lower_bound requirement (see above)
first = std::lower_bound( first, last, value, comp );
return first != last && !comp( value, *first ) ? first : last;
}
namespace
{
static CEntityClassificationsManager g_EntityClassifications;
}
CEntityClassificationsManager& EntityClassifications()
{
return g_EntityClassifications;
}
#ifdef SERVER_DLL
static void EntityClassifications_WriteToFile_ServerCommand()
{
if( CMD_ARGC() != 2 )
{
Alert( at_console, "Usage: entityclassifications_writetofile <filename including extension>\n" );
return;
}
char szGameDir[ MAX_PATH ];
if( !UTIL_GetGameDir( szGameDir, ARRAYSIZE( szGameDir ) ) )
{
Alert( at_console, "Couldn't get game directory\n" );
return;
}
char szPath[ MAX_PATH ];
if( !PrintfSuccess( snprintf( szPath, ARRAYSIZE( szPath ), "%s/%s", szGameDir, CMD_ARGV( 1 ) ), ARRAYSIZE( szPath ) ) )
{
Alert( at_console, "Couldn't format file path\n" );
return;
}
EntityClassifications().WriteToFile( szPath );
}
#endif
bool CEntityClassificationData::HasRelationshipToClassification( EntityClassification_t targetClassId ) const
{
return binary_find( m_Relationships.begin(), m_Relationships.end(), targetClassId ) != m_Relationships.end();
}
bool CEntityClassificationData::GetRelationshipToClassification( EntityClassification_t targetClassId, Relationship& outRelationship )
{
auto it = binary_find( m_Relationships.begin(), m_Relationships.end(), targetClassId );
if( it == m_Relationships.end() )
{
outRelationship = R_NO;
return false;
}
outRelationship = it->m_Relationship;
return true;
}
void CEntityClassificationData::AddRelationship( EntityClassification_t targetClassId, Relationship relationship )
{
auto it = binary_find( m_Relationships.begin(), m_Relationships.end(), targetClassId );
if( it == m_Relationships.end() )
{
it = std::upper_bound(
m_Relationships.begin(),
m_Relationships.end(),
targetClassId );
m_Relationships.insert(
it,
CClassificationRelationship( targetClassId, relationship ) );
}
else
{
//Already existed; update.
Alert( at_aiconsole, "CEntityClassificationData::AddRelationship: Updating relationship between \"%s\" and \"%u\" from \"%u\" to \"%u\"\n",
m_szName.c_str(), targetClassId, it->m_Relationship, relationship );
it->m_Relationship = relationship;
}
}
void CEntityClassificationData::RemoveRelationship( EntityClassification_t targetClassId )
{
auto it = binary_find( m_Relationships.begin(), m_Relationships.end(), targetClassId );
if( it != m_Relationships.end() )
{
m_Relationships.erase( it );
}
}
const std::string CEntityClassificationsManager::EMPTY_STRING;
void CEntityClassificationsManager::Initialize()
{
#ifdef SERVER_DLL
g_engfuncs.pfnAddServerCommand( "entityclassifications_writetofile", &EntityClassifications_WriteToFile_ServerCommand );
#endif
}
void CEntityClassificationsManager::Reset()
{
m_ClassMap.clear();
m_ClassList.clear();
m_NoneId = AddClassification( classify::NONE );
}
bool CEntityClassificationsManager::IsClassIdValid( EntityClassification_t classId ) const
{
return classId != INVALID_ENTITY_CLASSIFICATION && classId <= m_ClassList.size() && m_ClassList[ IdToIndex( classId ) ];
}
EntityClassification_t CEntityClassificationsManager::AddClassification( std::string&& szName, Relationship defaultSourceRelationship )
{
return AddClassification( std::move( szName ), defaultSourceRelationship, R_NO, false );
}
EntityClassification_t CEntityClassificationsManager::AddClassification( std::string&& szName, Relationship defaultSourceRelationship, Relationship defaultTargetRelationship )
{
return AddClassification( std::move( szName ), defaultSourceRelationship, defaultTargetRelationship, true );
}
EntityClassification_t CEntityClassificationsManager::AddClassification( std::string&& szName,
Relationship defaultSourceRelationship, Relationship defaultTargetRelationship,
bool bHasDefaultTargetRelationship )
{
ASSERT( !szName.empty() );
if( szName.empty() )
{
Alert( at_console, "CEntityClassificationsManager::AddClassification: Cannot add classification with empty name\n" );
return INVALID_ENTITY_CLASSIFICATION;
}
{
auto it = m_ClassMap.find( szName );
if( it != m_ClassMap.end() )
{
auto& classification = m_ClassList[ it->second.first ];
if( !it->second.second )
{
Alert( at_aiconsole, "CEntityClassificationsManager::AddClassification: Updating classification \"%s\"\n", szName.c_str() );
classification->m_DefaultSourceRelationship = defaultSourceRelationship;
classification->m_DefaultTargetRelationship = defaultTargetRelationship;
classification->m_bHasDefaultTargetRelationship = bHasDefaultTargetRelationship;
}
else
{
Alert( at_console, "CEntityClassificationsManager::AddClassification: Cannot add classification \"%s\"; an alias with that name already exists\n", szName.c_str() );
}
return classification->m_ClassId;
}
}
if( m_ClassList.size() >= MAX_ENTITY_CLASSIFICATIONS )
{
Alert( at_console, "CEntityClassificationsManager::AddClassification: Couldn't add \"%s\", maximum classifications %u reached\n", szName.c_str(), MAX_ENTITY_CLASSIFICATIONS );
return GetNoneId();
}
const auto classId = m_ClassList.size() + FIRST_ID_OFFSET;
m_ClassList.emplace_back( std::make_unique<CEntityClassificationData>( classId, std::move( szName ), defaultSourceRelationship, defaultTargetRelationship, bHasDefaultTargetRelationship ) );
auto& data = m_ClassList.back();
m_ClassMap.emplace( data->m_szName, std::make_pair( m_ClassList.size() - 1, false ) );
return classId;
}
bool CEntityClassificationsManager::RemoveClassification( EntityClassification_t classId )
{
if( !IsClassIdValid( classId ) )
{
Alert( at_error, "CEntityClassificationsManager::RemoveClassification: Class Id (\"%u\") is invalid\n", classId );
return false;
}
const auto index = IdToIndex( classId );
//Erase all entries, both classifications and aliases.
for( auto it = m_ClassMap.begin(); it != m_ClassMap.end(); )
{
if( it->second.first == index )
{
it = m_ClassMap.erase( it );
}
else
++it;
}
m_ClassList[ index ].reset();
//Remove it from all classifications as well.
for( auto& classification : m_ClassList )
{
if( classification )
classification->RemoveRelationship( classId );
}
//TODO: reclaim freed Ids? - Solokiller
return true;
}
bool CEntityClassificationsManager::RemoveClassification( const std::string& szName, bool bRemoveAliases )
{
auto it = m_ClassMap.find( szName );
if( it == m_ClassMap.end() )
return false;
if( it->second.second && !bRemoveAliases )
return false;
return RemoveClassification( IndexToId( it->second.first ) );
}
EntityClassification_t CEntityClassificationsManager::GetClassificationId( const std::string& szName ) const
{
//The empty string is equivalent to the invalid classification.
if( szName == EMPTY_STRING )
return INVALID_ENTITY_CLASSIFICATION;
auto it = m_ClassMap.find( szName );
if( it == m_ClassMap.end() )
return GetNoneId();
return m_ClassList[ it->second.first ]->m_ClassId;
}
EntityClassification_t CEntityClassificationsManager::AddAlias( std::string&& szName, std::string&& szTarget )
{
EntityClassification_t targetId = INVALID_ENTITY_CLASSIFICATION;
//First get the Id for the target, inserting the classification if it doesn't exist yet.
{
auto it = m_ClassMap.find( szTarget );
if( it != m_ClassMap.end() )
{
targetId = IndexToId( it->second.first );
}
else
{
targetId = AddClassification( std::move( szTarget ) );
}
}
if( targetId == INVALID_ENTITY_CLASSIFICATION )
{
//The name is only moved from if it was inserted, so this can't be an empty string.
Alert( at_error, "CEntityClassificationsManager::AddAlias: Couldn't add or find classification \"%s\"\n",
szTarget.c_str() );
return targetId;
}
//Now check if the alias exists or not. If not, add it, otherwise, change target.
auto it = m_ClassMap.find( szName );
bool bInsert = false;
if( it == m_ClassMap.end() )
{
bInsert = true;
}
else
{
if( it->second.second )
{
it->second.first = IdToIndex( targetId );
}
else
{
//A classification with that name exists; remove classification and add as alias.
RemoveClassification( szName, false );
bInsert = true;
}
}
if( bInsert )
{
m_ClassMap.emplace( std::move( szName ), std::make_pair( IdToIndex( targetId ), true ) );
}
return targetId;
}
bool CEntityClassificationsManager::RemoveAlias( const std::string& szName )
{
auto it = m_ClassMap.find( szName );
if( it == m_ClassMap.end() )
return false;
//Only remove aliases.
if( !it->second.second )
{
return false;
}
m_ClassMap.erase( it );
return true;
}
void CEntityClassificationsManager::AddRelationship( EntityClassification_t sourceClassId, EntityClassification_t targetClassId, Relationship relationship, bool bBidirectional )
{
if( !IsClassIdValid( sourceClassId ) || !IsClassIdValid( targetClassId ) )
{
Alert( at_error, "CEntityClassificationsManager::AddRelationship: One or both class Ids (\"%u\" and \"%u\") are invalid\n", sourceClassId, targetClassId );
return;
}
auto& from = m_ClassList[ IdToIndex( sourceClassId ) ];
from->AddRelationship( targetClassId, relationship );
if( bBidirectional )
{
auto& to = m_ClassList[ IdToIndex( targetClassId ) ];
to->AddRelationship( sourceClassId, relationship );
}
}
void CEntityClassificationsManager::AddRelationship( const std::string& sourceClassName, const std::string& targetClassName, Relationship relationship, bool bBidirectional )
{
auto sourceId = GetClassificationId( sourceClassName );
auto targetId = GetClassificationId( targetClassName );
if( !IsClassIdValid( sourceId ) || !IsClassIdValid( targetId ) )
{
Alert( at_error, "CEntityClassificationsManager::AddRelationship: One or both classifications (\"%s\" and \"%s\") are nonexistent\n", sourceClassName.c_str(), targetClassName.c_str() );
return;
}
AddRelationship( sourceId, targetId, relationship, bBidirectional );
}
void CEntityClassificationsManager::RemoveRelationship( EntityClassification_t sourceClassId, EntityClassification_t targetClassId, bool bBidirectional )
{
if( !IsClassIdValid( sourceClassId ) || !IsClassIdValid( targetClassId ) )
{
Alert( at_error, "CEntityClassificationsManager::RemoveRelationship: One or both class Ids (\"%u\" and \"%u\") are invalid\n", sourceClassId, targetClassId );
return;
}
auto& from = m_ClassList[ IdToIndex( sourceClassId ) ];
from->RemoveRelationship( targetClassId );
if( bBidirectional )
{
auto& to = m_ClassList[ IdToIndex( targetClassId ) ];
to->RemoveRelationship( sourceClassId );
}
}
void CEntityClassificationsManager::RemoveRelationship( const std::string& sourceClassName, const std::string& targetClassName, bool bBidirectional )
{
auto sourceId = GetClassificationId( sourceClassName );
auto targetId = GetClassificationId( targetClassName );
if( !IsClassIdValid( sourceId ) || !IsClassIdValid( targetId ) )
{
Alert( at_error, "CEntityClassificationsManager::RemoveRelationship: One or both classifications (\"%s\" and \"%s\") are nonexistent\n", sourceClassName.c_str(), targetClassName.c_str() );
return;
}
RemoveRelationship( sourceId, targetId, bBidirectional );
}
Relationship CEntityClassificationsManager::GetRelationshipBetween( EntityClassification_t sourceClassId, EntityClassification_t targetClassId, bool bBidirectional ) const
{
if( !IsClassIdValid( sourceClassId ) || !IsClassIdValid( targetClassId ) )
{
Alert( at_error, "CEntityClassificationsManager::GetRelationshipBetween: One or both class Ids (\"%u\" and \"%u\") are invalid\n", sourceClassId, targetClassId );
return R_NO;
}
Relationship result = R_NO;
auto& from = m_ClassList[ IdToIndex( sourceClassId ) ];
auto& to = m_ClassList[ IdToIndex( targetClassId ) ];
//If there exists a relationship from source to target, return relationship.
if( from->GetRelationshipToClassification( targetClassId, result ) )
{
return result;
}
//No relationship from source to target, should we check for target to source?
if( bBidirectional )
{
//There is a relationship, return value.
if( to->GetRelationshipToClassification( sourceClassId, result ) )
{
return result;
}
}
if( to->m_bHasDefaultTargetRelationship )
{
return to->m_DefaultTargetRelationship;
}
//No explicit relationship, return default.
return from->m_DefaultSourceRelationship;
}
Relationship CEntityClassificationsManager::GetRelationshipBetween( const std::string& sourceClassName, const std::string& targetClassName, bool bBidirectional ) const
{
auto sourceId = GetClassificationId( sourceClassName );
auto targetId = GetClassificationId( targetClassName );
if( !IsClassIdValid( sourceId ) || !IsClassIdValid( targetId ) )
{
Alert( at_error, "CEntityClassificationsManager::GetRelationshipBetween: One or both classifications (\"%s\" and \"%s\") are nonexistent\n",
sourceClassName.c_str(), targetClassName.c_str() );
return R_NO;
}
return GetRelationshipBetween( sourceId, targetId, bBidirectional );
}
const std::string& CEntityClassificationsManager::GetClassificationName( EntityClassification_t classification ) const
{
if( !IsClassIdValid( classification ) )
return EMPTY_STRING;
return m_ClassList[ IdToIndex( classification ) ]->m_szName;
}
void CEntityClassificationsManager::WriteToFile( const char* pszFilename ) const
{
ASSERT( pszFilename );
FILE* pFile = fopen( pszFilename, "w" );
if( !pFile )
{
Alert( at_error, "CEntityClassificationsManager::WriteToFile: Couldn't open file \"%s\" for writing!\n", pszFilename );
return;
}
size_t uiClassCount = 0;
//Calculate the longest classification name so we can align everything.
size_t uiLongest = 0;
for( const auto& classification : m_ClassList )
{
if( !classification )
continue;
++uiClassCount;
const auto uiLength = classification->m_szName.length();
if( uiLength > uiLongest )
uiLongest = uiLength;
}
if( LONGEST_RELATIONSHIP_PRETTY_STRING > uiLongest )
uiLongest = LONGEST_RELATIONSHIP_PRETTY_STRING;
fprintf( pFile, "%u classifications\n", static_cast<unsigned int>( uiClassCount ) );
//Offset to match the first value in the matrix.
fprintf( pFile, "%-*s ", static_cast<int>( uiLongest ), "" );
//Write the headers.
for( const auto& classification : m_ClassList )
{
if( !classification )
continue;
//Align the headers so the pretty strings fit inside them.
fprintf( pFile, "%-*s ", static_cast<int>( max( classification->m_szName.length(), LONGEST_RELATIONSHIP_PRETTY_STRING ) ), classification->m_szName.c_str() );
}
fprintf( pFile, "\n" );
//Write the matrix of classification relationships.
for( const auto& classification : m_ClassList )
{
if( !classification )
continue;
fprintf( pFile, "%-*s ", static_cast<int>( uiLongest ), classification->m_szName.c_str() );
for( const auto& class2 : m_ClassList )
{
if( !class2 )
continue;
Relationship relationship;
if( !classification->GetRelationshipToClassification( class2->m_ClassId, relationship ) )
{
if( class2->m_bHasDefaultTargetRelationship )
{
relationship = classification->m_DefaultTargetRelationship;
}
else
{
relationship = classification->m_DefaultSourceRelationship;
}
}
//Align with header.
fprintf( pFile, "%-*s ", static_cast<int>( max( class2->m_szName.length(), LONGEST_RELATIONSHIP_PRETTY_STRING ) ), RelationshipToPrettyString( relationship ) );
}
fprintf( pFile, "\n" );
}
size_t uiNumAliases = 0;
for( const auto& classification : m_ClassMap )
{
if( classification.second.second )
++uiNumAliases;
}
fprintf( pFile, "\n%u aliases\n", static_cast<unsigned int>( uiNumAliases ) );
for( const auto& classification : m_ClassMap )
{
if( classification.second.second )
{
fprintf( pFile, "%s->%s\n", classification.first.c_str(), m_ClassList[ classification.second.first ]->m_szName.c_str() );
}
}
fclose( pFile );
Alert( at_console, "Written entity classifications to file \"%s\"\n", pszFilename );
}
size_t CEntityClassificationsManager::IdToIndex( EntityClassification_t classId )
{
return classId - FIRST_ID_OFFSET;
}
EntityClassification_t CEntityClassificationsManager::IndexToId( size_t index )
{
return index + FIRST_ID_OFFSET;
}
| 29.470588 | 190 | 0.739345 | xalalau |
20b9019037c3d7b60afffdd8961acefd1eb81251 | 206 | cpp | C++ | atcoder/abc156/b.cpp | yuik46/competition_programming_code | 0c47db99ce7fb9bcf6e3b0dbfb8c84d9cfa165fd | [
"MIT"
] | null | null | null | atcoder/abc156/b.cpp | yuik46/competition_programming_code | 0c47db99ce7fb9bcf6e3b0dbfb8c84d9cfa165fd | [
"MIT"
] | null | null | null | atcoder/abc156/b.cpp | yuik46/competition_programming_code | 0c47db99ce7fb9bcf6e3b0dbfb8c84d9cfa165fd | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int n;
int k;
cin >> n >> k;
int result = 0;
while(n > 0){
n = n / k;
result++;
}
cout << result << endl;
} | 13.733333 | 27 | 0.446602 | yuik46 |
20b9cb73861ce4198c51dbd83f0cb790d92203d4 | 32,229 | hpp | C++ | redemption/src/mod/rdp/channels/rail_session_manager.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/mod/rdp/channels/rail_session_manager.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | redemption/src/mod/rdp/channels/rail_session_manager.hpp | DianaAssistant/DIANA | 6a4c51c1861f6a936941b21c2c905fc291c229d7 | [
"MIT"
] | null | null | null | /*
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
675 Mass Ave, Cambridge, MA 02139, USA.
Product name: redemption, a FLOSS RDP proxy
Copyright (C) Wallix 2015
Author(s): Christophe Grosjean, Raphael Zhou
*/
#pragma once
#include "core/RDP/slowpath.hpp"
#include "core/RDP/remote_programs.hpp"
#include "core/RDP/orders/RDPOrdersPrimaryOpaqueRect.hpp"
#include "core/channel_list.hpp"
#include "core/channel_names.hpp"
#include "core/front_api.hpp"
#include "gdi/clip_from_cmd.hpp"
#include "gdi/graphic_api.hpp"
#include "gdi/text_metrics.hpp"
#include "gdi/protected_graphics.hpp"
#include "RAIL/client_execute.hpp"
#include "mod/internal/widget/button.hpp"
#include "mod/mod_api.hpp"
#include "mod/rdp/channels/rail_window_id_manager.hpp"
#include "mod/rdp/rdp_verbose.hpp"
#include "mod/rdp/windowing_api.hpp"
#include "mod/rdp/channels/rail_window_id_manager.hpp"
#include "utils/rect.hpp"
#include "utils/theme.hpp"
#include "utils/timebase.hpp"
#include "utils/translation.hpp"
#include "utils/sugar/not_null_ptr.hpp"
#include "core/events.hpp"
#include <string>
class RemoteProgramsSessionManager final
: public gdi::GraphicApi
, public RemoteProgramsWindowIdManager
, public windowing_api
{
gdi::GraphicApi & front;
mod_api & mod;
Language lang;
Font const & font;
Theme theme;
const RDPVerbose verbose;
uint32_t blocked_server_window_id = RemoteProgramsWindowIdManager::INVALID_WINDOW_ID;
bool graphics_update_disabled = false;
Rect protected_rect;
uint32_t dialog_box_window_id = RemoteProgramsWindowIdManager::INVALID_WINDOW_ID;
gdi::GraphicApi * drawable = nullptr;
enum class DialogBoxType {
SPLASH_SCREEN,
WAITING_SCREEN,
NONE
} dialog_box_type = DialogBoxType::NONE;
Rect disconnect_now_button_rect;
bool disconnect_now_button_clicked = false;
bool has_previous_window = false;
std::string session_probe_window_title;
uint32_t auxiliary_window_id = RemoteProgramsWindowIdManager::INVALID_WINDOW_ID;
const not_null_ptr<ClientExecute> rail_client_execute;
bool currently_without_window = false;
bool has_actively_monitored_desktop = true;
std::chrono::milliseconds rail_disconnect_message_delay {};
EventsGuard events_guard;
public:
void draw(RDP::FrameMarker const & cmd) override { this->draw_impl( cmd); }
void draw(RDPDstBlt const & cmd, Rect clip) override { this->draw_impl(cmd, clip); }
void draw(RDPMultiDstBlt const & cmd, Rect clip) override { this->draw_impl(cmd, clip); }
void draw(RDPPatBlt const & cmd, Rect clip, gdi::ColorCtx color_ctx) override { this->draw_impl(cmd, clip, color_ctx); }
void draw(RDP::RDPMultiPatBlt const & cmd, Rect clip, gdi::ColorCtx color_ctx) override { this->draw_impl(cmd, clip, color_ctx); }
void draw(RDPOpaqueRect const & cmd, Rect clip, gdi::ColorCtx color_ctx) override { this->draw_impl(cmd, clip, color_ctx); }
void draw(RDPMultiOpaqueRect const & cmd, Rect clip, gdi::ColorCtx color_ctx) override { this->draw_impl(cmd, clip, color_ctx); }
void draw(RDPScrBlt const & cmd, Rect clip) override { this->draw_impl(cmd, clip); }
void draw(RDP::RDPMultiScrBlt const & cmd, Rect clip) override { this->draw_impl(cmd, clip); }
void draw(RDPLineTo const & cmd, Rect clip, gdi::ColorCtx color_ctx) override { this->draw_impl(cmd, clip, color_ctx); }
void draw(RDPPolygonSC const & cmd, Rect clip, gdi::ColorCtx color_ctx) override { this->draw_impl(cmd, clip, color_ctx); }
void draw(RDPPolygonCB const & cmd, Rect clip, gdi::ColorCtx color_ctx) override { this->draw_impl(cmd, clip, color_ctx); }
void draw(RDPPolyline const & cmd, Rect clip, gdi::ColorCtx color_ctx) override { this->draw_impl(cmd, clip, color_ctx); }
void draw(RDPEllipseSC const & cmd, Rect clip, gdi::ColorCtx color_ctx) override { this->draw_impl(cmd, clip, color_ctx); }
void draw(RDPEllipseCB const & cmd, Rect clip, gdi::ColorCtx color_ctx) override { this->draw_impl(cmd, clip, color_ctx); }
void draw(RDPBitmapData const & cmd, Bitmap const & bmp) override { this->draw_impl(cmd, bmp); }
void draw(RDPMemBlt const & cmd, Rect clip, Bitmap const & bmp) override { this->draw_impl(cmd, clip, bmp);}
void draw(RDPMem3Blt const & cmd, Rect clip, gdi::ColorCtx color_ctx, Bitmap const & bmp) override { this->draw_impl(cmd, clip, color_ctx, bmp); }
void draw(RDPGlyphIndex const & cmd, Rect clip, gdi::ColorCtx color_ctx, GlyphCache const & gly_cache) override { this->draw_impl(cmd, clip, color_ctx, gly_cache); }
void draw(RDPSetSurfaceCommand const & /*cmd*/) override {}
void draw(RDPSetSurfaceCommand const & /*cmd*/, RDPSurfaceContent const &/*content*/) override {}
void draw(RDPColCache const & cmd) override { this->draw_impl(cmd); }
void draw(RDPBrushCache const & cmd) override { this->draw_impl(cmd); }
void new_pointer(gdi::CachePointerIndex cache_idx, const RdpPointerView & cursor) override
{
if (this->drawable) {
this->drawable->new_pointer(cache_idx, cursor);
}
}
void cached_pointer(gdi::CachePointerIndex cache_idx) override
{
if (this->drawable) {
this->drawable->cached_pointer(cache_idx);
}
}
explicit RemoteProgramsSessionManager(
EventContainer & events,
gdi::GraphicApi& front, mod_api& mod, Language lang,
Font const & font, Theme const & theme,
char const * session_probe_window_title,
not_null_ptr<ClientExecute> rail_client_execute,
std::chrono::milliseconds rail_disconnect_message_delay,
RDPVerbose verbose)
: front(front)
, mod(mod)
, lang(lang)
, font(font)
, theme(theme)
, verbose(verbose)
, session_probe_window_title(session_probe_window_title)
, rail_client_execute(rail_client_execute)
, rail_disconnect_message_delay(rail_disconnect_message_delay)
, events_guard(events)
{}
~RemoteProgramsSessionManager() = default;
void begin_update() override
{
if (this->drawable) {
this->drawable->begin_update();
}
}
void end_update() override
{
if (this->drawable) {
this->drawable->end_update();
}
}
void disable_graphics_update(bool disable)
{
this->graphics_update_disabled = disable;
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO,
"RemoteProgramsSessionManager::disable_graphics_update: "
"graphics_update_disabled=%s",
(this->graphics_update_disabled ? "yes" : "no"));
if (!disable) {
if (RemoteProgramsWindowIdManager::INVALID_WINDOW_ID != this->dialog_box_window_id) {
this->dialog_box_destroy();
}
if (RemoteProgramsWindowIdManager::INVALID_WINDOW_ID != this->auxiliary_window_id) {
this->destroy_auxiliary_window();
}
}
}
public:
bool is_server_only_window(uint32_t window_id) const {
return (this->blocked_server_window_id == window_id);
}
void set_drawable(gdi::GraphicApi * drawable) {
this->drawable = drawable;
}
void input_mouse(int device_flags, int x, int y) {
if (DialogBoxType::WAITING_SCREEN != this->dialog_box_type) {
return;
}
if (device_flags & SlowPath::PTRFLAGS_BUTTON1) {
this->disconnect_now_button_clicked = false;
if (device_flags & SlowPath::PTRFLAGS_DOWN) {
if (this->disconnect_now_button_rect.contains_pt(x, y)) {
this->disconnect_now_button_clicked = true;
}
}
this->waiting_screen_draw(this->disconnect_now_button_clicked
? WidgetButton::State::Pressed
: WidgetButton::State::Normal);
if (!(device_flags & SlowPath::PTRFLAGS_DOWN)
&& this->disconnect_now_button_rect.contains_pt(x, y)
) {
LOG(LOG_INFO, "RemoteApp session initiated disconnect by user");
throw Error(ERR_DISCONNECT_BY_USER);
}
}
}
void input_scancode(kbdtypes::KbdFlags flags, kbdtypes::Scancode scancode) {
if (DialogBoxType::WAITING_SCREEN != this->dialog_box_type) {
return;
}
if (kbdtypes::pressed_scancode(flags, scancode) == kbdtypes::Scancode::Enter) {
LOG(LOG_INFO, "RemoteApp session initiated disconnect by user");
throw Error(ERR_DISCONNECT_BY_USER);
}
}
private:
template<class Cmd, class... Args>
void draw_impl(Cmd const & cmd, Args const &... args) {
if (this->drawable) {
gdi::ProtectedGraphics(*this->drawable, this->mod, this->protected_rect)
.draw(cmd, args...);
}
}
public:
void draw(RDP::RAIL::WindowIcon const & order) override {
if (this->drawable) {
if (order.header.WindowId() != this->blocked_server_window_id) {
order.map_window_id(*this);
this->drawable->draw(order);
}
else {
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw_impl(WindowIcon): Order bloacked.");
}
}
}
void draw(RDP::RAIL::CachedIcon const & order) override {
if (this->drawable) {
if (order.header.WindowId() != this->blocked_server_window_id) {
order.map_window_id(*this);
this->drawable->draw(order);
}
else {
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw_impl(CachedIcon): Order bloacked.");
}
}
}
void draw(RDP::RAIL::DeletedWindow const & order) override {
// LOG(LOG_INFO, "RemoteProgramsSessionManager::draw(DeletedWindow)");
const uint32_t window_id = order.header.WindowId();
const bool window_is_blocked = (window_id == this->blocked_server_window_id);
if (this->drawable) {
if (!window_is_blocked) {
order.map_window_id(*this);
this->drawable->draw(order);
}
else {
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw_impl(DeletedWindow): Order bloacked.");
}
}
if (window_is_blocked) {
this->unregister_server_window(window_id);
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw_impl(DeletedWindow): Remove window 0x%X from blocked windows list.", window_id);
this->blocked_server_window_id = RemoteProgramsWindowIdManager::INVALID_WINDOW_ID;
}
}
void draw(RDP::RAIL::NewOrExistingWindow const & order) override {
// LOG(LOG_INFO, "RemoteProgramsSessionManager::draw(NewOrExistingWindow)");
const std::string& title_info = order.TitleInfo();
const uint32_t window_id = order.header.WindowId();
bool window_is_blocked = (window_id == this->blocked_server_window_id);
const bool window_is_new = (RDP::RAIL::WINDOW_ORDER_STATE_NEW & order.header.FieldsPresentFlags());
if (window_is_new) {
if (DialogBoxType::WAITING_SCREEN == this->dialog_box_type) {
this->dialog_box_destroy();
}
this->currently_without_window = false;
}
//if (bool(this->verbose & RDPVerbose::rail)) {
// LOG(LOG_INFO,
// "RemoteProgramsSessionManager::draw(NewOrExistingWindow): "
// "TitleInfo=\"%s\" WindowIsNew=%s GraphicsUpdateDisabled=%s",
// title_info, (window_is_new ? "yes" : "no"),
// (this->graphics_update_disabled ? "yes" : "no"));
//}
if ((RemoteProgramsWindowIdManager::INVALID_WINDOW_ID == this->blocked_server_window_id) &&
this->graphics_update_disabled) {
assert(!window_is_blocked);
if (utils::ends_with(title_info, this->session_probe_window_title)) {
if (window_is_new) {
{
RAILPDUHeader rpduh;
ClientSystemCommandPDU cscpdu;
cscpdu.WindowId(this->get_client_window_id_ex(window_id));
cscpdu.Command(SC_MINIMIZE);
StaticOutStream<1024> out_s;
rpduh.emit_begin(out_s, TS_RAIL_ORDER_SYSCOMMAND);
cscpdu.emit(out_s);
rpduh.emit_end();
InStream in_s(out_s.get_produced_bytes());
this->mod.send_to_mod_channel(channel_names::rail,
in_s,
out_s.get_offset(),
CHANNELS::CHANNEL_FLAG_FIRST
| CHANNELS::CHANNEL_FLAG_LAST
| CHANNELS::CHANNEL_FLAG_SHOW_PROTOCOL);
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw(NewOrExistingWindow): Window 0x%X is minimized.", window_id);
}
}
else {
{
RDP::RAIL::DeletedWindow order;
order.header.FieldsPresentFlags(
uint32_t(RDP::RAIL::WINDOW_ORDER_STATE_DELETED)
| uint32_t(RDP::RAIL::WINDOW_ORDER_TYPE_WINDOW));
order.header.WindowId(window_id);
if (bool(this->verbose & RDPVerbose::rail)) {
StaticOutStream<1024> out_s;
order.emit(out_s);
order.log(LOG_INFO);
}
this->front.draw(order);
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw(NewOrExistingWindow): Window 0x%X is deletec.", window_id);
}
}
this->blocked_server_window_id = window_id;
window_is_blocked = true;
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw(NewOrExistingWindow): Window 0x%X is blocked.", window_id);
this->dialog_box_create(DialogBoxType::SPLASH_SCREEN);
this->splash_screen_draw();
}
}
if (this->drawable) {
if (!window_is_blocked) {
order.map_window_id(*this);
this->drawable->draw(order);
}
else {
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw_impl(NewOrExistingWindow): Order bloacked.");
}
}
}
void draw(RDP::RAIL::NewOrExistingNotificationIcons const & order) override {
if (this->drawable) {
if (order.header.WindowId() != this->blocked_server_window_id) {
order.map_window_id(*this);
this->drawable->draw(order);
}
else {
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw_impl(NewOrExistingNotificationIcons): Order bloacked.");
}
}
}
void draw(RDP::RAIL::DeletedNotificationIcons const & order) override {
if (this->drawable) {
if (order.header.WindowId() != this->blocked_server_window_id) {
order.map_window_id(*this);
this->drawable->draw(order);
}
else {
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw_impl(DeletedNotificationIcons): Order bloacked.");
}
}
}
void draw(RDP::RAIL::ActivelyMonitoredDesktop const & order) override {
this->has_actively_monitored_desktop = true;
bool has_not_window =
((RDP::RAIL::WINDOW_ORDER_FIELD_DESKTOP_ZORDER & order.header.FieldsPresentFlags()) &&
!order.NumWindowIds());
bool has_window = false;
if (this->drawable) {
if (order.ActiveWindowId() != this->blocked_server_window_id) {
order.map_window_id(*this);
this->drawable->draw(order);
has_window =
((RDP::RAIL::WINDOW_ORDER_FIELD_DESKTOP_ZORDER & order.header.FieldsPresentFlags()) &&
order.NumWindowIds());
}
else {
LOG_IF(bool(this->verbose & RDPVerbose::rail), LOG_INFO, "RemoteProgramsSessionManager::draw(ActivelyMonitoredDesktop): Order bloacked.");
}
}
if (has_not_window && (DialogBoxType::NONE == this->dialog_box_type)
&& this->has_previous_window)
{
this->currently_without_window = true;
this->events_guard.create_event_timeout(
"Rail Waiting Screen Event",
this->rail_disconnect_message_delay,
[this](Event&event)
{
if (this->currently_without_window
&& (DialogBoxType::NONE == this->dialog_box_type)
&& this->has_previous_window
&& this->has_actively_monitored_desktop
) {
LOG(LOG_INFO, "RemoteProgramsSessionManager::draw(ActivelyMonitoredDesktop): Create waiting screen.");
this->dialog_box_create(DialogBoxType::WAITING_SCREEN);
this->waiting_screen_draw(WidgetButton::State::Normal);
}
event.garbage = true;
});
}
if (has_window) {
this->has_previous_window = true;
}
}
void draw(const RDP::RAIL::NonMonitoredDesktop & order) override {
this->has_actively_monitored_desktop = false;
if (this->drawable) {
this->drawable->draw(order);
}
}
private:
void dialog_box_create(DialogBoxType type) {
if (RemoteProgramsWindowIdManager::INVALID_WINDOW_ID != this->dialog_box_window_id) {
return;
}
this->dialog_box_window_id = this->register_client_window();
Rect mod_window_rect = this->rail_client_execute->get_window_rect();
Rect dialog_box_rect(
mod_window_rect.x + (mod_window_rect.cx - 640) / 2,
mod_window_rect.y + (mod_window_rect.cy - 480) / 2,
640,
480
);
this->protected_rect = dialog_box_rect;
const Rect adjusted_protected_rect = this->protected_rect.offset(
this->rail_client_execute->get_window_offset());
{
RDP::RAIL::NewOrExistingWindow order;
order.header.FieldsPresentFlags(
RDP::RAIL::WINDOW_ORDER_STATE_NEW
| RDP::RAIL::WINDOW_ORDER_TYPE_WINDOW
| RDP::RAIL::WINDOW_ORDER_FIELD_CLIENTDELTA
| RDP::RAIL::WINDOW_ORDER_FIELD_CLIENTAREAOFFSET
| RDP::RAIL::WINDOW_ORDER_FIELD_VISOFFSET
| RDP::RAIL::WINDOW_ORDER_FIELD_WNDOFFSET
| RDP::RAIL::WINDOW_ORDER_FIELD_WNDSIZE
| RDP::RAIL::WINDOW_ORDER_FIELD_VISIBILITY
| RDP::RAIL::WINDOW_ORDER_FIELD_SHOW
| RDP::RAIL::WINDOW_ORDER_FIELD_STYLE
| RDP::RAIL::WINDOW_ORDER_FIELD_TITLE
| RDP::RAIL::WINDOW_ORDER_FIELD_OWNER
);
order.header.WindowId(this->dialog_box_window_id);
order.OwnerWindowId(0x0);
order.Style(0x14EE0000);
order.ExtendedStyle(0x40310 | 0x8);
order.ShowState(5);
order.TitleInfo("Dialog box");
order.ClientOffsetX(adjusted_protected_rect.x + 6);
order.ClientOffsetY(adjusted_protected_rect.y + 25);
order.WindowOffsetX(adjusted_protected_rect.x);
order.WindowOffsetY(adjusted_protected_rect.y);
order.WindowClientDeltaX(6);
order.WindowClientDeltaY(25);
order.WindowWidth(adjusted_protected_rect.cx);
order.WindowHeight(adjusted_protected_rect.cy);
order.VisibleOffsetX(adjusted_protected_rect.x);
order.VisibleOffsetY(adjusted_protected_rect.y);
order.NumVisibilityRects(1);
order.VisibilityRects(0, RDP::RAIL::Rectangle(0, 0, adjusted_protected_rect.cx, adjusted_protected_rect.cy));
if (bool(this->verbose & RDPVerbose::rail)) {
StaticOutStream<1024> out_s;
order.emit(out_s);
order.log(LOG_INFO);
LOG(LOG_INFO, "RemoteProgramsSessionManager::dialog_box_create: Send NewOrExistingWindow to client: size=%zu", out_s.get_offset() - 1);
}
this->drawable->draw(order);
}
if (DialogBoxType::WAITING_SCREEN == type) {
RDP::RAIL::ActivelyMonitoredDesktop order;
order.header.FieldsPresentFlags(
RDP::RAIL::WINDOW_ORDER_TYPE_DESKTOP |
RDP::RAIL::WINDOW_ORDER_FIELD_DESKTOP_ZORDER
);
order.NumWindowIds(1);
order.window_ids(0, this->dialog_box_window_id);
if (bool(this->verbose & RDPVerbose::rail)) {
StaticOutStream<256> out_s;
order.emit(out_s);
order.log(LOG_INFO);
LOG(LOG_INFO, "RemoteProgramsSessionManager::dialog_box_create: Send ActivelyMonitoredDesktop to client: size=%zu", out_s.get_offset() - 1);
}
this->drawable->draw(order);
}
this->dialog_box_type = type;
this->disconnect_now_button_rect = Rect();
}
void dialog_box_destroy() {
assert(this->dialog_box_window_id);
{
RDP::RAIL::DeletedWindow order;
order.header.FieldsPresentFlags(
uint32_t(RDP::RAIL::WINDOW_ORDER_STATE_DELETED)
| uint32_t(RDP::RAIL::WINDOW_ORDER_TYPE_WINDOW));
order.header.WindowId(this->dialog_box_window_id);
if (bool(this->verbose & RDPVerbose::rail)) {
StaticOutStream<1024> out_s;
order.emit(out_s);
order.log(LOG_INFO);
LOG(LOG_INFO, "RemoteProgramsSessionManager::dialog_box_destroy: Send DeletedWindow to client: size=%zu", out_s.get_offset() - 1);
}
this->front.draw(order);
}
this->mod.rdp_input_invalidate(this->protected_rect);
this->protected_rect = Rect();
this->dialog_box_window_id = RemoteProgramsWindowIdManager::INVALID_WINDOW_ID;
this->dialog_box_type = DialogBoxType::NONE;
this->disconnect_now_button_rect = Rect();
this->disconnect_now_button_clicked = false;
}
void splash_screen_draw() {
if (!this->drawable) return;
this->drawable->begin_update();
{
RDPOpaqueRect order(this->protected_rect, encode_color24()(BLACK));
this->drawable->draw(order, this->protected_rect, gdi::ColorCtx::depth24());
}
{
Rect rect = this->protected_rect.shrink(1);
RDPOpaqueRect order(rect, encode_color24()(this->theme.global.bgcolor));
if (bool(this->verbose & RDPVerbose::rail)) {
order.log(LOG_INFO, rect);
}
this->drawable->draw(order, rect, gdi::ColorCtx::depth24());
}
gdi::TextMetrics tm(this->font, TR(trkeys::starting_remoteapp, this->lang));
gdi::server_draw_text(*this->drawable,
this->font,
this->protected_rect.x + (this->protected_rect.cx - tm.width) / 2,
this->protected_rect.y + (this->protected_rect.cy - tm.height) / 2,
TR(trkeys::starting_remoteapp, this->lang),
encode_color24()(this->theme.global.fgcolor),
encode_color24()(this->theme.global.bgcolor),
gdi::ColorCtx::depth24(),
this->protected_rect
);
this->drawable->end_update();
}
void waiting_screen_draw(WidgetButton::State state) {
if (!this->drawable) return;
this->drawable->begin_update();
{
RDPOpaqueRect order(this->protected_rect, encode_color24()(BLACK));
this->drawable->draw(order, this->protected_rect, gdi::ColorCtx::depth24());
}
{
Rect rect = this->protected_rect.shrink(1);
RDPOpaqueRect order(rect, encode_color24()(this->theme.global.bgcolor));
if (bool(this->verbose & RDPVerbose::rail)) {
order.log(LOG_INFO, rect);
}
this->drawable->draw(order, rect, gdi::ColorCtx::depth24());
}
const gdi::TextMetrics tm_msg(this->font, TR(trkeys::closing_remoteapp, this->lang));
const int xtext = 6;
const int ytext = 2;
const Dimension dim_button = WidgetButton::get_optimal_dim(2, this->font, TR(trkeys::disconnect_now, this->lang), xtext, ytext);
const uint32_t interspace = 60;
const uint32_t height = tm_msg.height + interspace + dim_button.h;
int ypos = this->protected_rect.y + (this->protected_rect.cy - height) / 2;
gdi::server_draw_text(*this->drawable,
this->font,
this->protected_rect.x + (this->protected_rect.cx - tm_msg.width) / 2,
ypos,
TR(trkeys::closing_remoteapp, this->lang),
encode_color24()(this->theme.global.fgcolor),
encode_color24()(this->theme.global.bgcolor),
gdi::ColorCtx::depth24(),
this->protected_rect
);
ypos += (tm_msg.height + interspace);
this->disconnect_now_button_rect.x = this->protected_rect.x + (this->protected_rect.cx - dim_button.w) / 2;
this->disconnect_now_button_rect.y = ypos;
this->disconnect_now_button_rect.cx = dim_button.w;
this->disconnect_now_button_rect.cy = dim_button.h;
WidgetButton::draw(this->protected_rect,
this->disconnect_now_button_rect,
*this->drawable,
false, // logo
true, // has_focus
TR(trkeys::disconnect_now, this->lang),
this->theme.global.fgcolor,
this->theme.global.bgcolor,
this->theme.global.focus_color,
gdi::ColorCtx::depth24(),
Rect(),
state,
2,
this->font,
xtext,
ytext
);
this->drawable->end_update();
}
///////////////////
// windowing_api
//
public:
void create_auxiliary_window(Rect const window_rect) override {
if (RemoteProgramsWindowIdManager::INVALID_WINDOW_ID != this->auxiliary_window_id) return;
this->auxiliary_window_id = this->register_client_window();
{
const Rect adjusted_window_rect = window_rect.offset(
this->rail_client_execute->get_window_offset());
RDP::RAIL::NewOrExistingWindow order;
order.header.FieldsPresentFlags(
RDP::RAIL::WINDOW_ORDER_STATE_NEW
| RDP::RAIL::WINDOW_ORDER_TYPE_WINDOW
| RDP::RAIL::WINDOW_ORDER_FIELD_CLIENTDELTA
| RDP::RAIL::WINDOW_ORDER_FIELD_CLIENTAREAOFFSET
| RDP::RAIL::WINDOW_ORDER_FIELD_VISOFFSET
| RDP::RAIL::WINDOW_ORDER_FIELD_WNDOFFSET
| RDP::RAIL::WINDOW_ORDER_FIELD_WNDSIZE
| RDP::RAIL::WINDOW_ORDER_FIELD_VISIBILITY
| RDP::RAIL::WINDOW_ORDER_FIELD_SHOW
| RDP::RAIL::WINDOW_ORDER_FIELD_STYLE
| RDP::RAIL::WINDOW_ORDER_FIELD_TITLE
| RDP::RAIL::WINDOW_ORDER_FIELD_OWNER
);
order.header.WindowId(this->auxiliary_window_id);
order.OwnerWindowId(0x0);
order.Style(0x14EE0000);
order.ExtendedStyle(0x40310 | 0x8);
order.ShowState(5);
order.TitleInfo("Dialog box");
order.ClientOffsetX(adjusted_window_rect.x + 6);
order.ClientOffsetY(adjusted_window_rect.y + 25);
order.WindowOffsetX(adjusted_window_rect.x);
order.WindowOffsetY(adjusted_window_rect.y);
order.WindowClientDeltaX(6);
order.WindowClientDeltaY(25);
order.WindowWidth(adjusted_window_rect.cx);
order.WindowHeight(adjusted_window_rect.cy);
order.VisibleOffsetX(adjusted_window_rect.x);
order.VisibleOffsetY(adjusted_window_rect.y);
order.NumVisibilityRects(1);
order.VisibilityRects(0, RDP::RAIL::Rectangle(0, 0, adjusted_window_rect.cx, adjusted_window_rect.cy));
if (bool(this->verbose & RDPVerbose::rail)) {
StaticOutStream<1024> out_s;
order.emit(out_s);
order.log(LOG_INFO);
LOG(LOG_INFO, "RemoteProgramsSessionManager::dialog_box_create: Send NewOrExistingWindow to client: size=%zu", out_s.get_offset() - 1);
}
this->drawable->draw(order);
}
}
void destroy_auxiliary_window() override {
if (RemoteProgramsWindowIdManager::INVALID_WINDOW_ID == this->auxiliary_window_id) return;
{
RDP::RAIL::DeletedWindow order;
order.header.FieldsPresentFlags(
uint32_t(RDP::RAIL::WINDOW_ORDER_STATE_DELETED)
| uint32_t(RDP::RAIL::WINDOW_ORDER_TYPE_WINDOW));
order.header.WindowId(this->auxiliary_window_id);
if (bool(this->verbose & RDPVerbose::rail)) {
StaticOutStream<1024> out_s;
order.emit(out_s);
order.log(LOG_INFO);
LOG(LOG_INFO, "RemoteProgramsSessionManager::destroy_auxiliary_window: Send DeletedWindow to client: size=%zu", out_s.get_offset() - 1);
}
this->front.draw(order);
}
this->auxiliary_window_id = RemoteProgramsWindowIdManager::INVALID_WINDOW_ID;
}
}; // class RemoteProgramsSessionManager
| 39.986352 | 185 | 0.58919 | DianaAssistant |
20ba2f04decb2e79b9054982b3c3ac7cad79d59e | 1,631 | hh | C++ | include/io/rest.hh | king1600/Valk | b376a0dcce522ae03ced7d882835e4dea98df86e | [
"MIT"
] | null | null | null | include/io/rest.hh | king1600/Valk | b376a0dcce522ae03ced7d882835e4dea98df86e | [
"MIT"
] | null | null | null | include/io/rest.hh | king1600/Valk | b376a0dcce522ae03ced7d882835e4dea98df86e | [
"MIT"
] | null | null | null | #pragma once
#include "http.hh"
namespace io {
using RestCallback = std::function<void(const json&)>;
static const json JSON_EMPTY = json::parse("{}");
static const RestCallback CB_NONE = [](const json& j){};
class RestRequest {
public:
json data;
std::string method;
std::string endpoint;
RestCallback callback;
};
class RestRoute {
private:
bool limited;
std::deque<RestRequest> queued;
public:
RestRoute();
void setLimited(bool state);
const bool isLimited() const;
const bool hasPending() const;
void getPending(RestRequest &req);
const std::size_t hasLeft() const;
void addPending(const RestRequest &req);
};
class RestClient {
private:
Service& service;
std::string token;
HttpParser parser;
RestRoute globalRoute;
std::deque<std::string> writes;
std::vector<std::string> cookies;
std::shared_ptr<SSLClient> client;
std::map<std::string, RestRoute> routes;
void _connect();
void pushRequest(const std::string &data);
public:
RestClient(Service &loop);
void SetToken(const std::string &token);
void Request(const std::string& method, const std::string &endpoint,
const json &data = JSON_EMPTY, const RestCallback &cb = CB_NONE);
void get(const std::string& endpoint,
const json &data=JSON_EMPTY, const RestCallback &cb = CB_NONE);
void post(const std::string& endpoint,
const json &data=JSON_EMPTY, const RestCallback &cb = CB_NONE);
void del(const std::string& endpoint,
const json &data=JSON_EMPTY, const RestCallback &cb = CB_NONE);
};
} | 25.092308 | 72 | 0.669528 | king1600 |
20ba5330cab4477274432ce6129c724719399f12 | 922 | hpp | C++ | plugins/help_mongo/include/help_mongo/help_mongo.hpp | myappbase/myappbase | 5a405ca0c1411da48ee755874b11dfb4ee625155 | [
"MIT"
] | null | null | null | plugins/help_mongo/include/help_mongo/help_mongo.hpp | myappbase/myappbase | 5a405ca0c1411da48ee755874b11dfb4ee625155 | [
"MIT"
] | null | null | null | plugins/help_mongo/include/help_mongo/help_mongo.hpp | myappbase/myappbase | 5a405ca0c1411da48ee755874b11dfb4ee625155 | [
"MIT"
] | null | null | null | /**
* @file
* @copyright defined in myappbase/LICENSE
*/
#pragma once
#include <string>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/exception/exception.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/pool.hpp>
#include <mongocxx/exception/operation_exception.hpp>
#include <mongocxx/exception/logic_error.hpp>
#include <help_mongo/bson.hpp>
namespace my {
namespace help_mongo {
bsoncxx::oid make_custom_oid();
uint32_t get_last_block(mongocxx::collection &);
std::vector<bsoncxx::document::view> get_objects(
mongocxx::collection &col,
const uint32_t);
void handle_mongo_exception(const std::string &desc, int line_num);
} // namespace help_mongo
} // namespace my
| 27.117647 | 75 | 0.712581 | myappbase |
20baf3805dca450bd4450c313df25c6688db4669 | 1,324 | hh | C++ | XRADGUI/Sources/RasterImageFile/RasterImageFile.hh | n-kulberg/xrad | 3d089cc24d942db4649f1a50defbd69f01739ae2 | [
"BSD-3-Clause"
] | 1 | 2021-04-02T16:47:00.000Z | 2021-04-02T16:47:00.000Z | XRADGUI/Sources/RasterImageFile/RasterImageFile.hh | n-kulberg/xrad | 3d089cc24d942db4649f1a50defbd69f01739ae2 | [
"BSD-3-Clause"
] | null | null | null | XRADGUI/Sources/RasterImageFile/RasterImageFile.hh | n-kulberg/xrad | 3d089cc24d942db4649f1a50defbd69f01739ae2 | [
"BSD-3-Clause"
] | 3 | 2021-08-30T11:26:23.000Z | 2021-09-23T09:39:56.000Z |
#ifndef __RasterImageFile_hh
//#error This file must be included from "RasterImageFile.h" only
#endif
XRAD_BEGIN
template<class RGB_IMAGE_T>
RGB_IMAGE_T RasterImageFile::rgb()
{
using value_type = typename RGB_IMAGE_T::value_type;
ColorImageF64 buffer = rgb_internal();
double scalefactor = scalefactor_calculator<value_type>::get(m_bits_per_channel);
RGB_IMAGE_T result;
MakeCopy(result, buffer, [scalefactor](value_type &y, const auto &x){return y = x*scalefactor;});
return result;
}
template <typename IMAGE_T> IMAGE_T RasterImageFile::channel(color_channel in_channel)
{
using value_type = typename IMAGE_T::value_type;
RealFunction2D_F64 buffer = channel_internal(in_channel);
double scalefactor, offset;
if(in_channel == color_channel::hue)
{
XRAD_ASSERT_THROW_M(numeric_limits<value_type>::max() > 360, invalid_argument, ssprintf("datatype is to small for hue"));
scalefactor = 180.;
offset = -1.;
}
else
{
scalefactor = value_scalefactor_calculator<value_type>::get(m_bits_per_channel);
offset = 0.;
}
IMAGE_T result;
result.MakeCopy(buffer, [scalefactor, offset](value_type &y, const auto &x){return y = (x-offset)*scalefactor;});
return result;
}
template <typename IMAGE_T>
IMAGE_T RasterImageFile::lightness()
{
return channel(color_channel::lightness);
}
XRAD_END
| 24.072727 | 123 | 0.762085 | n-kulberg |
20bb811d1aae729460f3e6f60b4cf4d83f0c03e6 | 742 | cpp | C++ | docs/mfc/codesnippet/CPP/mfc-activex-controls-creating-an-automation-server_2.cpp | jmittert/cpp-docs | cea5a8ee2b4764b2bac4afe5d386362ffd64e55a | [
"CC-BY-4.0",
"MIT"
] | 14 | 2018-01-28T18:10:55.000Z | 2021-11-16T13:21:18.000Z | docs/mfc/codesnippet/CPP/mfc-activex-controls-creating-an-automation-server_2.cpp | jmittert/cpp-docs | cea5a8ee2b4764b2bac4afe5d386362ffd64e55a | [
"CC-BY-4.0",
"MIT"
] | 1 | 2021-04-01T04:17:07.000Z | 2021-04-01T04:17:07.000Z | docs/mfc/codesnippet/CPP/mfc-activex-controls-creating-an-automation-server_2.cpp | jmittert/cpp-docs | cea5a8ee2b4764b2bac4afe5d386362ffd64e55a | [
"CC-BY-4.0",
"MIT"
] | 2 | 2018-11-01T12:33:08.000Z | 2021-11-16T13:21:19.000Z | void CCircDlg::OnOK()
{
UpdateData(); // Get the current data from the dialog box.
CCirc2 circ; // Create a wrapper class for the ActiveX object.
COleException e; // In case of errors
// Create the ActiveX object.
// The name is the control's progid; look it up using OleView
if (circ.CreateDispatch(_T("CIRC.CircCtrl.1"), &e))
{
// get the Caption property of your ActiveX object
// get the result into m_strCaption
m_strCaption = circ.GetCaption();
UpdateData(FALSE); // Display the string in the dialog box.
}
else { // An error
TCHAR buf[255];
e.GetErrorMessage(buf, sizeof(buf) / sizeof(TCHAR));
AfxMessageBox(buf); // Display the error message.
}
} | 35.333333 | 68 | 0.642857 | jmittert |
20c051b1a532c68c0f76f2ca0f302595f86136cf | 1,425 | cpp | C++ | tests/external/libcxx/array/compare.pass.cpp | GlitterIsMe/libpmemobj-cpp | 71c614ca4c8bb769cf8bb01550acc1ca1c76d6bc | [
"BSD-3-Clause"
] | 1 | 2018-11-06T13:09:12.000Z | 2018-11-06T13:09:12.000Z | tests/external/libcxx/array/compare.pass.cpp | GlitterIsMe/libpmemobj-cpp | 71c614ca4c8bb769cf8bb01550acc1ca1c76d6bc | [
"BSD-3-Clause"
] | null | null | null | tests/external/libcxx/array/compare.pass.cpp | GlitterIsMe/libpmemobj-cpp | 71c614ca4c8bb769cf8bb01550acc1ca1c76d6bc | [
"BSD-3-Clause"
] | null | null | null | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Copyright 2018, Intel Corporation
//
// Modified to test pmem::obj containers
//
#include "unittest.hpp"
#include <libpmemobj++/experimental/array.hpp>
#include <vector>
namespace pmem_exp = pmem::obj::experimental;
template <class Array>
void
test_compare(const Array &LHS, const Array &RHS)
{
typedef std::vector<typename Array::value_type> Vector;
const Vector LHSV(LHS.begin(), LHS.end());
const Vector RHSV(RHS.begin(), RHS.end());
UT_ASSERT((LHS == RHS) == (LHSV == RHSV));
UT_ASSERT((LHS != RHS) == (LHSV != RHSV));
UT_ASSERT((LHS < RHS) == (LHSV < RHSV));
UT_ASSERT((LHS <= RHS) == (LHSV <= RHSV));
UT_ASSERT((LHS > RHS) == (LHSV > RHSV));
UT_ASSERT((LHS >= RHS) == (LHSV >= RHSV));
}
int
main()
{
START();
{
typedef int T;
typedef pmem_exp::array<T, 3> C;
C c1 = {1, 2, 3};
C c2 = {1, 2, 3};
C c3 = {3, 2, 1};
C c4 = {1, 2, 1};
test_compare(c1, c2);
test_compare(c1, c3);
test_compare(c1, c4);
}
{
typedef int T;
typedef pmem_exp::array<T, 0> C;
C c1 = {};
C c2 = {};
test_compare(c1, c2);
}
return 0;
}
| 22.619048 | 80 | 0.54386 | GlitterIsMe |
20c3629dd29990b7bdb2273bbc8cef74b2040ff3 | 289,875 | cpp | C++ | Development/SDKs/1.7.1/SDK/AIModule_functions.cpp | ResaloliPT/HydroneerReleases | 3a3501f04608cea77ccbf7229f94089295128ea7 | [
"Unlicense"
] | null | null | null | Development/SDKs/1.7.1/SDK/AIModule_functions.cpp | ResaloliPT/HydroneerReleases | 3a3501f04608cea77ccbf7229f94089295128ea7 | [
"Unlicense"
] | null | null | null | Development/SDKs/1.7.1/SDK/AIModule_functions.cpp | ResaloliPT/HydroneerReleases | 3a3501f04608cea77ccbf7229f94089295128ea7 | [
"Unlicense"
] | null | null | null | // Name: Hydroneer, Version: 1.7.1
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
void FAIRequestID::AfterRead()
{
}
void FAIRequestID::BeforeDelete()
{
}
void FAIStimulus::AfterRead()
{
}
void FAIStimulus::BeforeDelete()
{
}
void FActorPerceptionBlueprintInfo::AfterRead()
{
READ_PTR_FULL(Target, AActor);
}
void FActorPerceptionBlueprintInfo::BeforeDelete()
{
DELE_PTR_FULL(Target);
}
void FAIDamageEvent::AfterRead()
{
READ_PTR_FULL(DamagedActor, AActor);
READ_PTR_FULL(Instigator, AActor);
}
void FAIDamageEvent::BeforeDelete()
{
DELE_PTR_FULL(DamagedActor);
DELE_PTR_FULL(Instigator);
}
void FEnvOverlapData::AfterRead()
{
}
void FEnvOverlapData::BeforeDelete()
{
}
void FPawnActionStack::AfterRead()
{
READ_PTR_FULL(TopAction, UPawnAction);
}
void FPawnActionStack::BeforeDelete()
{
DELE_PTR_FULL(TopAction);
}
void FPawnActionEvent::AfterRead()
{
READ_PTR_FULL(Action, UPawnAction);
}
void FPawnActionEvent::BeforeDelete()
{
DELE_PTR_FULL(Action);
}
void FAIDataProviderValue::AfterRead()
{
READ_PTR_FULL(CachedProperty, UProperty);
READ_PTR_FULL(DataBinding, UAIDataProvider);
}
void FAIDataProviderValue::BeforeDelete()
{
DELE_PTR_FULL(CachedProperty);
DELE_PTR_FULL(DataBinding);
}
void FAIDataProviderStructValue::AfterRead()
{
FAIDataProviderValue::AfterRead();
}
void FAIDataProviderStructValue::BeforeDelete()
{
FAIDataProviderValue::BeforeDelete();
}
void FAISightEvent::AfterRead()
{
READ_PTR_FULL(SeenActor, AActor);
READ_PTR_FULL(Observer, AActor);
}
void FAISightEvent::BeforeDelete()
{
DELE_PTR_FULL(SeenActor);
DELE_PTR_FULL(Observer);
}
void FEnvQueryRequest::AfterRead()
{
READ_PTR_FULL(QueryTemplate, UEnvQuery);
READ_PTR_FULL(Owner, UObject);
READ_PTR_FULL(World, UWorld);
}
void FEnvQueryRequest::BeforeDelete()
{
DELE_PTR_FULL(QueryTemplate);
DELE_PTR_FULL(Owner);
DELE_PTR_FULL(World);
}
void FEnvQueryResult::AfterRead()
{
READ_PTR_FULL(itemType, UClass);
}
void FEnvQueryResult::BeforeDelete()
{
DELE_PTR_FULL(itemType);
}
void FGenericTeamId::AfterRead()
{
}
void FGenericTeamId::BeforeDelete()
{
}
void FAINoiseEvent::AfterRead()
{
READ_PTR_FULL(Instigator, AActor);
}
void FAINoiseEvent::BeforeDelete()
{
DELE_PTR_FULL(Instigator);
}
void FAIPredictionEvent::AfterRead()
{
READ_PTR_FULL(Requestor, AActor);
READ_PTR_FULL(PredictedActor, AActor);
}
void FAIPredictionEvent::BeforeDelete()
{
DELE_PTR_FULL(Requestor);
DELE_PTR_FULL(PredictedActor);
}
void FAITeamStimulusEvent::AfterRead()
{
READ_PTR_FULL(Broadcaster, AActor);
READ_PTR_FULL(Enemy, AActor);
}
void FAITeamStimulusEvent::BeforeDelete()
{
DELE_PTR_FULL(Broadcaster);
DELE_PTR_FULL(Enemy);
}
void FAITouchEvent::AfterRead()
{
READ_PTR_FULL(TouchReceiver, AActor);
READ_PTR_FULL(OtherActor, AActor);
}
void FAITouchEvent::BeforeDelete()
{
DELE_PTR_FULL(TouchReceiver);
DELE_PTR_FULL(OtherActor);
}
void FAISenseAffiliationFilter::AfterRead()
{
}
void FAISenseAffiliationFilter::BeforeDelete()
{
}
void FAIMoveRequest::AfterRead()
{
READ_PTR_FULL(GoalActor, AActor);
}
void FAIMoveRequest::BeforeDelete()
{
DELE_PTR_FULL(GoalActor);
}
void FBTDecoratorLogic::AfterRead()
{
}
void FBTDecoratorLogic::BeforeDelete()
{
}
void FBehaviorTreeTemplateInfo::AfterRead()
{
READ_PTR_FULL(Asset, UBehaviorTree);
READ_PTR_FULL(Template, UBTCompositeNode);
}
void FBehaviorTreeTemplateInfo::BeforeDelete()
{
DELE_PTR_FULL(Asset);
DELE_PTR_FULL(Template);
}
void FBlackboardEntry::AfterRead()
{
READ_PTR_FULL(KeyType, UBlackboardKeyType);
}
void FBlackboardEntry::BeforeDelete()
{
DELE_PTR_FULL(KeyType);
}
void FBTCompositeChild::AfterRead()
{
READ_PTR_FULL(ChildComposite, UBTCompositeNode);
READ_PTR_FULL(ChildTask, UBTTaskNode);
}
void FBTCompositeChild::BeforeDelete()
{
DELE_PTR_FULL(ChildComposite);
DELE_PTR_FULL(ChildTask);
}
void FBlackboardKeySelector::AfterRead()
{
READ_PTR_FULL(SelectedKeyType, UClass);
}
void FBlackboardKeySelector::BeforeDelete()
{
DELE_PTR_FULL(SelectedKeyType);
}
void FAIDataProviderTypedValue::AfterRead()
{
FAIDataProviderValue::AfterRead();
READ_PTR_FULL(PropertyType, UClass);
}
void FAIDataProviderTypedValue::BeforeDelete()
{
FAIDataProviderValue::BeforeDelete();
DELE_PTR_FULL(PropertyType);
}
void FAIDataProviderFloatValue::AfterRead()
{
FAIDataProviderTypedValue::AfterRead();
}
void FAIDataProviderFloatValue::BeforeDelete()
{
FAIDataProviderTypedValue::BeforeDelete();
}
void FAIDynamicParam::AfterRead()
{
}
void FAIDynamicParam::BeforeDelete()
{
}
void FEQSParametrizedQueryExecutionRequest::AfterRead()
{
READ_PTR_FULL(QueryTemplate, UEnvQuery);
}
void FEQSParametrizedQueryExecutionRequest::BeforeDelete()
{
DELE_PTR_FULL(QueryTemplate);
}
void FEnvNamedValue::AfterRead()
{
}
void FEnvNamedValue::BeforeDelete()
{
}
void FCrowdAvoidanceConfig::AfterRead()
{
}
void FCrowdAvoidanceConfig::BeforeDelete()
{
}
void FCrowdAvoidanceSamplingPattern::AfterRead()
{
}
void FCrowdAvoidanceSamplingPattern::BeforeDelete()
{
}
void FAIDataProviderBoolValue::AfterRead()
{
FAIDataProviderTypedValue::AfterRead();
}
void FAIDataProviderBoolValue::BeforeDelete()
{
FAIDataProviderTypedValue::BeforeDelete();
}
void FEnvTraceData::AfterRead()
{
READ_PTR_FULL(NavigationFilter, UClass);
}
void FEnvTraceData::BeforeDelete()
{
DELE_PTR_FULL(NavigationFilter);
}
void FAIDataProviderIntValue::AfterRead()
{
FAIDataProviderTypedValue::AfterRead();
}
void FAIDataProviderIntValue::BeforeDelete()
{
FAIDataProviderTypedValue::BeforeDelete();
}
void FEnvDirection::AfterRead()
{
READ_PTR_FULL(LineFrom, UClass);
READ_PTR_FULL(LineTo, UClass);
READ_PTR_FULL(Rotation, UClass);
}
void FEnvDirection::BeforeDelete()
{
DELE_PTR_FULL(LineFrom);
DELE_PTR_FULL(LineTo);
DELE_PTR_FULL(Rotation);
}
void FEnvQueryInstanceCache::AfterRead()
{
READ_PTR_FULL(Template, UEnvQuery);
}
void FEnvQueryInstanceCache::BeforeDelete()
{
DELE_PTR_FULL(Template);
}
// Function:
// Offset -> 0x01F644B0
// Name -> Function AIModule.AIAsyncTaskBlueprintProxy.OnMoveCompleted
// Flags -> (Final, Native, Public)
// Parameters:
// struct FAIRequestID RequestID (Parm, NoDestructor, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EPathFollowingResult> MovementResult (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIAsyncTaskBlueprintProxy::OnMoveCompleted(const struct FAIRequestID& RequestID, TEnumAsByte<AIModule_EPathFollowingResult> MovementResult)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIAsyncTaskBlueprintProxy.OnMoveCompleted");
UAIAsyncTaskBlueprintProxy_OnMoveCompleted_Params params {};
params.RequestID = RequestID;
params.MovementResult = MovementResult;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UAIAsyncTaskBlueprintProxy::AfterRead()
{
UObject::AfterRead();
}
void UAIAsyncTaskBlueprintProxy::BeforeDelete()
{
UObject::BeforeDelete();
}
// Function:
// Offset -> 0x01F65140
// Name -> Function AIModule.AIBlueprintHelperLibrary.UnlockAIResourcesWithAnimation
// Flags -> (Final, BlueprintAuthorityOnly, Native, Static, Public, BlueprintCallable)
// Parameters:
// class UAnimInstance* AnimInstance (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bUnlockMovement (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool UnlockAILogic (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIBlueprintHelperLibrary::STATIC_UnlockAIResourcesWithAnimation(class UAnimInstance* AnimInstance, bool bUnlockMovement, bool UnlockAILogic)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.UnlockAIResourcesWithAnimation");
UAIBlueprintHelperLibrary_UnlockAIResourcesWithAnimation_Params params {};
params.AnimInstance = AnimInstance;
params.bUnlockMovement = bUnlockMovement;
params.UnlockAILogic = UnlockAILogic;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F64EF0
// Name -> Function AIModule.AIBlueprintHelperLibrary.SpawnAIFromClass
// Flags -> (Final, Native, Static, Public, HasDefaults, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UClass* PawnClass (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UBehaviorTree* BehaviorTree (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector Location (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FRotator Rotation (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
// bool bNoCollisionFail (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class APawn* UAIBlueprintHelperLibrary::STATIC_SpawnAIFromClass(class UObject* WorldContextObject, class UClass* PawnClass, class UBehaviorTree* BehaviorTree, const struct FVector& Location, const struct FRotator& Rotation, bool bNoCollisionFail)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.SpawnAIFromClass");
UAIBlueprintHelperLibrary_SpawnAIFromClass_Params params {};
params.WorldContextObject = WorldContextObject;
params.PawnClass = PawnClass;
params.BehaviorTree = BehaviorTree;
params.Location = Location;
params.Rotation = Rotation;
params.bNoCollisionFail = bNoCollisionFail;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F64E30
// Name -> Function AIModule.AIBlueprintHelperLibrary.SimpleMoveToLocation
// Flags -> (Final, Native, Static, Public, HasOutParms, HasDefaults, BlueprintCallable)
// Parameters:
// class AController* Controller (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector Goal (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIBlueprintHelperLibrary::STATIC_SimpleMoveToLocation(class AController* Controller, const struct FVector& Goal)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.SimpleMoveToLocation");
UAIBlueprintHelperLibrary_SimpleMoveToLocation_Params params {};
params.Controller = Controller;
params.Goal = Goal;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F64D80
// Name -> Function AIModule.AIBlueprintHelperLibrary.SimpleMoveToActor
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class AController* Controller (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* Goal (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIBlueprintHelperLibrary::STATIC_SimpleMoveToActor(class AController* Controller, class AActor* Goal)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.SimpleMoveToActor");
UAIBlueprintHelperLibrary_SimpleMoveToActor_Params params {};
params.Controller = Controller;
params.Goal = Goal;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F64A70
// Name -> Function AIModule.AIBlueprintHelperLibrary.SendAIMessage
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class APawn* Target (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FName Message (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UObject* MessageSource (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bSuccess (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIBlueprintHelperLibrary::STATIC_SendAIMessage(class APawn* Target, const struct FName& Message, class UObject* MessageSource, bool bSuccess)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.SendAIMessage");
UAIBlueprintHelperLibrary_SendAIMessage_Params params {};
params.Target = Target;
params.Message = Message;
params.MessageSource = MessageSource;
params.bSuccess = bSuccess;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F63E40
// Name -> Function AIModule.AIBlueprintHelperLibrary.LockAIResourcesWithAnimation
// Flags -> (Final, BlueprintAuthorityOnly, Native, Static, Public, BlueprintCallable)
// Parameters:
// class UAnimInstance* AnimInstance (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bLockMovement (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool LockAILogic (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIBlueprintHelperLibrary::STATIC_LockAIResourcesWithAnimation(class UAnimInstance* AnimInstance, bool bLockMovement, bool LockAILogic)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.LockAIResourcesWithAnimation");
UAIBlueprintHelperLibrary_LockAIResourcesWithAnimation_Params params {};
params.AnimInstance = AnimInstance;
params.bLockMovement = bLockMovement;
params.LockAILogic = LockAILogic;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F63C80
// Name -> Function AIModule.AIBlueprintHelperLibrary.IsValidAIRotation
// Flags -> (Final, Native, Static, Public, HasDefaults, BlueprintCallable, BlueprintPure)
// Parameters:
// struct FRotator Rotation (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UAIBlueprintHelperLibrary::STATIC_IsValidAIRotation(const struct FRotator& Rotation)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.IsValidAIRotation");
UAIBlueprintHelperLibrary_IsValidAIRotation_Params params {};
params.Rotation = Rotation;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F63BF0
// Name -> Function AIModule.AIBlueprintHelperLibrary.IsValidAILocation
// Flags -> (Final, Native, Static, Public, HasDefaults, BlueprintCallable, BlueprintPure)
// Parameters:
// struct FVector Location (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UAIBlueprintHelperLibrary::STATIC_IsValidAILocation(const struct FVector& Location)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.IsValidAILocation");
UAIBlueprintHelperLibrary_IsValidAILocation_Params params {};
params.Location = Location;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F63B60
// Name -> Function AIModule.AIBlueprintHelperLibrary.IsValidAIDirection
// Flags -> (Final, Native, Static, Public, HasDefaults, BlueprintCallable, BlueprintPure)
// Parameters:
// struct FVector DirectionVector (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UAIBlueprintHelperLibrary::STATIC_IsValidAIDirection(const struct FVector& DirectionVector)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.IsValidAIDirection");
UAIBlueprintHelperLibrary_IsValidAIDirection_Params params {};
params.DirectionVector = DirectionVector;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F63450
// Name -> Function AIModule.AIBlueprintHelperLibrary.GetCurrentPath
// Flags -> (Final, Native, Static, Public, BlueprintCallable, BlueprintPure)
// Parameters:
// class AController* Controller (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UNavigationPath* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UNavigationPath* UAIBlueprintHelperLibrary::STATIC_GetCurrentPath(class AController* Controller)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.GetCurrentPath");
UAIBlueprintHelperLibrary_GetCurrentPath_Params params {};
params.Controller = Controller;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F633D0
// Name -> Function AIModule.AIBlueprintHelperLibrary.GetBlackboard
// Flags -> (Final, Native, Static, Public, BlueprintCallable, BlueprintPure)
// Parameters:
// class AActor* Target (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UBlackboardComponent* ReturnValue (ExportObject, Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UBlackboardComponent* UAIBlueprintHelperLibrary::STATIC_GetBlackboard(class AActor* Target)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.GetBlackboard");
UAIBlueprintHelperLibrary_GetBlackboard_Params params {};
params.Target = Target;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F63230
// Name -> Function AIModule.AIBlueprintHelperLibrary.GetAIController
// Flags -> (Final, Native, Static, Public, BlueprintCallable, BlueprintPure)
// Parameters:
// class AActor* ControlledActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AAIController* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class AAIController* UAIBlueprintHelperLibrary::STATIC_GetAIController(class AActor* ControlledActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.GetAIController");
UAIBlueprintHelperLibrary_GetAIController_Params params {};
params.ControlledActor = ControlledActor;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F63070
// Name -> Function AIModule.AIBlueprintHelperLibrary.CreateMoveToProxyObject
// Flags -> (Final, Native, Static, Public, HasDefaults, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* Pawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector Destination (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* TargetActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float AcceptanceRadius (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bStopOnOverlap (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UAIAsyncTaskBlueprintProxy* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UAIAsyncTaskBlueprintProxy* UAIBlueprintHelperLibrary::STATIC_CreateMoveToProxyObject(class UObject* WorldContextObject, class APawn* Pawn, const struct FVector& Destination, class AActor* TargetActor, float AcceptanceRadius, bool bStopOnOverlap)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIBlueprintHelperLibrary.CreateMoveToProxyObject");
UAIBlueprintHelperLibrary_CreateMoveToProxyObject_Params params {};
params.WorldContextObject = WorldContextObject;
params.Pawn = Pawn;
params.Destination = Destination;
params.TargetActor = TargetActor;
params.AcceptanceRadius = AcceptanceRadius;
params.bStopOnOverlap = bStopOnOverlap;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UAIBlueprintHelperLibrary::AfterRead()
{
UBlueprintFunctionLibrary::AfterRead();
}
void UAIBlueprintHelperLibrary::BeforeDelete()
{
UBlueprintFunctionLibrary::BeforeDelete();
}
// Function:
// Offset -> 0x01F652F0
// Name -> Function AIModule.AIController.UseBlackboard
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBlackboardData* BlackboardAsset (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UBlackboardComponent* BlackboardComponent (Parm, OutParm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool AAIController::UseBlackboard(class UBlackboardData* BlackboardAsset, class UBlackboardComponent** BlackboardComponent)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.UseBlackboard");
AAIController_UseBlackboard_Params params {};
params.BlackboardAsset = BlackboardAsset;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (BlackboardComponent != nullptr)
*BlackboardComponent = params.BlackboardComponent;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F650C0
// Name -> Function AIModule.AIController.UnclaimTaskResource
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class UClass* ResourceClass (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void AAIController::UnclaimTaskResource(class UClass* ResourceClass)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.UnclaimTaskResource");
AAIController_UnclaimTaskResource_Params params {};
params.ResourceClass = ResourceClass;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F64C30
// Name -> Function AIModule.AIController.SetPathFollowingComponent
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class UPathFollowingComponent* NewPFComponent (Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void AAIController::SetPathFollowingComponent(class UPathFollowingComponent* NewPFComponent)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.SetPathFollowingComponent");
AAIController_SetPathFollowingComponent_Params params {};
params.NewPFComponent = NewPFComponent;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F64BA0
// Name -> Function AIModule.AIController.SetMoveBlockDetection
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// bool bEnable (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void AAIController::SetMoveBlockDetection(bool bEnable)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.SetMoveBlockDetection");
AAIController_SetMoveBlockDetection_Params params {};
params.bEnable = bEnable;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F649D0
// Name -> Function AIModule.AIController.RunBehaviorTree
// Flags -> (Native, Public, BlueprintCallable)
// Parameters:
// class UBehaviorTree* BTAsset (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool AAIController::RunBehaviorTree(class UBehaviorTree* BTAsset)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.RunBehaviorTree");
AAIController_RunBehaviorTree_Params params {};
params.BTAsset = BTAsset;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.AIController.OnUsingBlackBoard
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class UBlackboardComponent* BlackboardComp (Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UBlackboardData* BlackboardAsset (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void AAIController::OnUsingBlackBoard(class UBlackboardComponent* BlackboardComp, class UBlackboardData* BlackboardAsset)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.OnUsingBlackBoard");
AAIController_OnUsingBlackBoard_Params params {};
params.BlackboardComp = BlackboardComp;
params.BlackboardAsset = BlackboardAsset;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F643E0
// Name -> Function AIModule.AIController.OnGameplayTaskResourcesClaimed
// Flags -> (Native, Public)
// Parameters:
// struct FGameplayResourceSet NewlyClaimed (Parm, NoDestructor, NativeAccessSpecifierPublic)
// struct FGameplayResourceSet FreshlyReleased (Parm, NoDestructor, NativeAccessSpecifierPublic)
void AAIController::OnGameplayTaskResourcesClaimed(const struct FGameplayResourceSet& NewlyClaimed, const struct FGameplayResourceSet& FreshlyReleased)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.OnGameplayTaskResourcesClaimed");
AAIController_OnGameplayTaskResourcesClaimed_Params params {};
params.NewlyClaimed = NewlyClaimed;
params.FreshlyReleased = FreshlyReleased;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F64170
// Name -> Function AIModule.AIController.MoveToLocation
// Flags -> (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable)
// Parameters:
// struct FVector Dest (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float AcceptanceRadius (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bStopOnOverlap (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bUsePathfinding (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bProjectDestinationToNavigation (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bCanStrafe (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UClass* FilterClass (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bAllowPartialPath (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EPathFollowingRequestResult> ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<AIModule_EPathFollowingRequestResult> AAIController::MoveToLocation(const struct FVector& Dest, float AcceptanceRadius, bool bStopOnOverlap, bool bUsePathfinding, bool bProjectDestinationToNavigation, bool bCanStrafe, class UClass* FilterClass, bool bAllowPartialPath)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.MoveToLocation");
AAIController_MoveToLocation_Params params {};
params.Dest = Dest;
params.AcceptanceRadius = AcceptanceRadius;
params.bStopOnOverlap = bStopOnOverlap;
params.bUsePathfinding = bUsePathfinding;
params.bProjectDestinationToNavigation = bProjectDestinationToNavigation;
params.bCanStrafe = bCanStrafe;
params.FilterClass = FilterClass;
params.bAllowPartialPath = bAllowPartialPath;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F63F50
// Name -> Function AIModule.AIController.MoveToActor
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class AActor* Goal (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float AcceptanceRadius (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bStopOnOverlap (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bUsePathfinding (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bCanStrafe (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UClass* FilterClass (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bAllowPartialPath (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EPathFollowingRequestResult> ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<AIModule_EPathFollowingRequestResult> AAIController::MoveToActor(class AActor* Goal, float AcceptanceRadius, bool bStopOnOverlap, bool bUsePathfinding, bool bCanStrafe, class UClass* FilterClass, bool bAllowPartialPath)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.MoveToActor");
AAIController_MoveToActor_Params params {};
params.Goal = Goal;
params.AcceptanceRadius = AcceptanceRadius;
params.bStopOnOverlap = bStopOnOverlap;
params.bUsePathfinding = bUsePathfinding;
params.bCanStrafe = bCanStrafe;
params.FilterClass = FilterClass;
params.bAllowPartialPath = bAllowPartialPath;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F63DC0
// Name -> Function AIModule.AIController.K2_SetFocus
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class AActor* NewFocus (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void AAIController::K2_SetFocus(class AActor* NewFocus)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.K2_SetFocus");
AAIController_K2_SetFocus_Params params {};
params.NewFocus = NewFocus;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F63D30
// Name -> Function AIModule.AIController.K2_SetFocalPoint
// Flags -> (Final, Native, Public, HasDefaults, BlueprintCallable)
// Parameters:
// struct FVector FP (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void AAIController::K2_SetFocalPoint(const struct FVector& FP)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.K2_SetFocalPoint");
AAIController_K2_SetFocalPoint_Params params {};
params.FP = FP;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F63D10
// Name -> Function AIModule.AIController.K2_ClearFocus
// Flags -> (Final, Native, Public, BlueprintCallable)
void AAIController::K2_ClearFocus()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.K2_ClearFocus");
AAIController_K2_ClearFocus_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F63B30
// Name -> Function AIModule.AIController.HasPartialPath
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool AAIController::HasPartialPath()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.HasPartialPath");
AAIController_HasPartialPath_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F63840
// Name -> Function AIModule.AIController.GetPathFollowingComponent
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// class UPathFollowingComponent* ReturnValue (ExportObject, Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UPathFollowingComponent* AAIController::GetPathFollowingComponent()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.GetPathFollowingComponent");
AAIController_GetPathFollowingComponent_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F63810
// Name -> Function AIModule.AIController.GetMoveStatus
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// TEnumAsByte<AIModule_EPathFollowingStatus> ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<AIModule_EPathFollowingStatus> AAIController::GetMoveStatus()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.GetMoveStatus");
AAIController_GetMoveStatus_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F636E0
// Name -> Function AIModule.AIController.GetImmediateMoveDestination
// Flags -> (Final, Native, Public, HasDefaults, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FVector ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FVector AAIController::GetImmediateMoveDestination()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.GetImmediateMoveDestination");
AAIController_GetImmediateMoveDestination_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F636B0
// Name -> Function AIModule.AIController.GetFocusActor
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// class AActor* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class AActor* AAIController::GetFocusActor()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.GetFocusActor");
AAIController_GetFocusActor_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F63600
// Name -> Function AIModule.AIController.GetFocalPointOnActor
// Flags -> (Native, Public, HasDefaults, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// class AActor* Actor (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FVector AAIController::GetFocalPointOnActor(class AActor* Actor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.GetFocalPointOnActor");
AAIController_GetFocalPointOnActor_Params params {};
params.Actor = Actor;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F635C0
// Name -> Function AIModule.AIController.GetFocalPoint
// Flags -> (Final, Native, Public, HasDefaults, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FVector ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FVector AAIController::GetFocalPoint()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.GetFocalPoint");
AAIController_GetFocalPoint_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F632B0
// Name -> Function AIModule.AIController.GetAIPerceptionComponent
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure)
// Parameters:
// class UAIPerceptionComponent* ReturnValue (ExportObject, Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UAIPerceptionComponent* AAIController::GetAIPerceptionComponent()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.GetAIPerceptionComponent");
AAIController_GetAIPerceptionComponent_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F62FF0
// Name -> Function AIModule.AIController.ClaimTaskResource
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class UClass* ResourceClass (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void AAIController::ClaimTaskResource(class UClass* ResourceClass)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIController.ClaimTaskResource");
AAIController_ClaimTaskResource_Params params {};
params.ResourceClass = ResourceClass;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void AAIController::AfterRead()
{
AController::AfterRead();
READ_PTR_FULL(PathFollowingComponent, UPathFollowingComponent);
READ_PTR_FULL(BrainComponent, UBrainComponent);
READ_PTR_FULL(PerceptionComponent, UAIPerceptionComponent);
READ_PTR_FULL(ActionsComp, UPawnActionsComponent);
READ_PTR_FULL(Blackboard, UBlackboardComponent);
READ_PTR_FULL(CachedGameplayTasksComponent, UGameplayTasksComponent);
READ_PTR_FULL(DefaultNavigationFilterClass, UClass);
}
void AAIController::BeforeDelete()
{
AController::BeforeDelete();
DELE_PTR_FULL(PathFollowingComponent);
DELE_PTR_FULL(BrainComponent);
DELE_PTR_FULL(PerceptionComponent);
DELE_PTR_FULL(ActionsComp);
DELE_PTR_FULL(Blackboard);
DELE_PTR_FULL(CachedGameplayTasksComponent);
DELE_PTR_FULL(DefaultNavigationFilterClass);
}
void UAIDataProvider::AfterRead()
{
UObject::AfterRead();
}
void UAIDataProvider::BeforeDelete()
{
UObject::BeforeDelete();
}
void UAIDataProvider_QueryParams::AfterRead()
{
UAIDataProvider::AfterRead();
}
void UAIDataProvider_QueryParams::BeforeDelete()
{
UAIDataProvider::BeforeDelete();
}
void UAIDataProvider_Random::AfterRead()
{
UAIDataProvider_QueryParams::AfterRead();
}
void UAIDataProvider_Random::BeforeDelete()
{
UAIDataProvider_QueryParams::BeforeDelete();
}
void UAIHotSpotManager::AfterRead()
{
UObject::AfterRead();
}
void UAIHotSpotManager::BeforeDelete()
{
UObject::BeforeDelete();
}
// Function:
// Offset -> 0x01F64CB0
// Name -> Function AIModule.AIPerceptionComponent.SetSenseEnabled
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class UClass* SenseClass (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bEnable (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIPerceptionComponent::SetSenseEnabled(class UClass* SenseClass, bool bEnable)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionComponent.SetSenseEnabled");
UAIPerceptionComponent_SetSenseEnabled_Params params {};
params.SenseClass = SenseClass;
params.bEnable = bEnable;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F649B0
// Name -> Function AIModule.AIPerceptionComponent.RequestStimuliListenerUpdate
// Flags -> (Final, Native, Public, BlueprintCallable)
void UAIPerceptionComponent::RequestStimuliListenerUpdate()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionComponent.RequestStimuliListenerUpdate");
UAIPerceptionComponent_RequestStimuliListenerUpdate_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F64570
// Name -> Function AIModule.AIPerceptionComponent.OnOwnerEndPlay
// Flags -> (Final, Native, Public)
// Parameters:
// class AActor* Actor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<Engine_EEndPlayReason> EndPlayReason (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIPerceptionComponent::OnOwnerEndPlay(class AActor* Actor, TEnumAsByte<Engine_EEndPlayReason> EndPlayReason)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionComponent.OnOwnerEndPlay");
UAIPerceptionComponent_OnOwnerEndPlay_Params params {};
params.Actor = Actor;
params.EndPlayReason = EndPlayReason;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F63950
// Name -> Function AIModule.AIPerceptionComponent.GetPerceivedHostileActors
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// TArray<class AActor*> OutActors (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic)
void UAIPerceptionComponent::GetPerceivedHostileActors(TArray<class AActor*>* OutActors)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionComponent.GetPerceivedHostileActors");
UAIPerceptionComponent_GetPerceivedHostileActors_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (OutActors != nullptr)
*OutActors = params.OutActors;
}
// Function:
// Offset -> 0x01F63860
// Name -> Function AIModule.AIPerceptionComponent.GetPerceivedActors
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// class UClass* SenseToUse (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TArray<class AActor*> OutActors (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic)
void UAIPerceptionComponent::GetPerceivedActors(class UClass* SenseToUse, TArray<class AActor*>* OutActors)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionComponent.GetPerceivedActors");
UAIPerceptionComponent_GetPerceivedActors_Params params {};
params.SenseToUse = SenseToUse;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (OutActors != nullptr)
*OutActors = params.OutActors;
}
// Function:
// Offset -> 0x01F63720
// Name -> Function AIModule.AIPerceptionComponent.GetKnownPerceivedActors
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// class UClass* SenseToUse (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TArray<class AActor*> OutActors (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic)
void UAIPerceptionComponent::GetKnownPerceivedActors(class UClass* SenseToUse, TArray<class AActor*>* OutActors)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionComponent.GetKnownPerceivedActors");
UAIPerceptionComponent_GetKnownPerceivedActors_Params params {};
params.SenseToUse = SenseToUse;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (OutActors != nullptr)
*OutActors = params.OutActors;
}
// Function:
// Offset -> 0x01F634D0
// Name -> Function AIModule.AIPerceptionComponent.GetCurrentlyPerceivedActors
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// class UClass* SenseToUse (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TArray<class AActor*> OutActors (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic)
void UAIPerceptionComponent::GetCurrentlyPerceivedActors(class UClass* SenseToUse, TArray<class AActor*>* OutActors)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionComponent.GetCurrentlyPerceivedActors");
UAIPerceptionComponent_GetCurrentlyPerceivedActors_Params params {};
params.SenseToUse = SenseToUse;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (OutActors != nullptr)
*OutActors = params.OutActors;
}
// Function:
// Offset -> 0x01F632D0
// Name -> Function AIModule.AIPerceptionComponent.GetActorsPerception
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class AActor* Actor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FActorPerceptionBlueprintInfo Info (Parm, OutParm, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UAIPerceptionComponent::GetActorsPerception(class AActor* Actor, struct FActorPerceptionBlueprintInfo* Info)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionComponent.GetActorsPerception");
UAIPerceptionComponent_GetActorsPerception_Params params {};
params.Actor = Actor;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Info != nullptr)
*Info = params.Info;
return params.ReturnValue;
}
void UAIPerceptionComponent::AfterRead()
{
UActorComponent::AfterRead();
READ_PTR_FULL(DominantSense, UClass);
READ_PTR_FULL(AIOwner, AAIController);
}
void UAIPerceptionComponent::BeforeDelete()
{
UActorComponent::BeforeDelete();
DELE_PTR_FULL(DominantSense);
DELE_PTR_FULL(AIOwner);
}
void UAIPerceptionListenerInterface::AfterRead()
{
UInterface::AfterRead();
}
void UAIPerceptionListenerInterface::BeforeDelete()
{
UInterface::BeforeDelete();
}
// Function:
// Offset -> 0x01F65270
// Name -> Function AIModule.AIPerceptionStimuliSourceComponent.UnregisterFromSense
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class UClass* SenseClass (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIPerceptionStimuliSourceComponent::UnregisterFromSense(class UClass* SenseClass)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionStimuliSourceComponent.UnregisterFromSense");
UAIPerceptionStimuliSourceComponent_UnregisterFromSense_Params params {};
params.SenseClass = SenseClass;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F65250
// Name -> Function AIModule.AIPerceptionStimuliSourceComponent.UnregisterFromPerceptionSystem
// Flags -> (Final, Native, Public, BlueprintCallable)
void UAIPerceptionStimuliSourceComponent::UnregisterFromPerceptionSystem()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionStimuliSourceComponent.UnregisterFromPerceptionSystem");
UAIPerceptionStimuliSourceComponent_UnregisterFromPerceptionSystem_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F64860
// Name -> Function AIModule.AIPerceptionStimuliSourceComponent.RegisterWithPerceptionSystem
// Flags -> (Final, Native, Public, BlueprintCallable)
void UAIPerceptionStimuliSourceComponent::RegisterWithPerceptionSystem()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionStimuliSourceComponent.RegisterWithPerceptionSystem");
UAIPerceptionStimuliSourceComponent_RegisterWithPerceptionSystem_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F646F0
// Name -> Function AIModule.AIPerceptionStimuliSourceComponent.RegisterForSense
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class UClass* SenseClass (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIPerceptionStimuliSourceComponent::RegisterForSense(class UClass* SenseClass)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionStimuliSourceComponent.RegisterForSense");
UAIPerceptionStimuliSourceComponent_RegisterForSense_Params params {};
params.SenseClass = SenseClass;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UAIPerceptionStimuliSourceComponent::AfterRead()
{
UActorComponent::AfterRead();
}
void UAIPerceptionStimuliSourceComponent::BeforeDelete()
{
UActorComponent::BeforeDelete();
}
void UAISubsystem::AfterRead()
{
UObject::AfterRead();
READ_PTR_FULL(AISystem, UAISystem);
}
void UAISubsystem::BeforeDelete()
{
UObject::BeforeDelete();
DELE_PTR_FULL(AISystem);
}
// Function:
// Offset -> 0x01F64900
// Name -> Function AIModule.AIPerceptionSystem.ReportPerceptionEvent
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UAISenseEvent* PerceptionEvent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIPerceptionSystem::STATIC_ReportPerceptionEvent(class UObject* WorldContextObject, class UAISenseEvent* PerceptionEvent)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionSystem.ReportPerceptionEvent");
UAIPerceptionSystem_ReportPerceptionEvent_Params params {};
params.WorldContextObject = WorldContextObject;
params.PerceptionEvent = PerceptionEvent;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F64880
// Name -> Function AIModule.AIPerceptionSystem.ReportEvent
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class UAISenseEvent* PerceptionEvent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIPerceptionSystem::ReportEvent(class UAISenseEvent* PerceptionEvent)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionSystem.ReportEvent");
UAIPerceptionSystem_ReportEvent_Params params {};
params.PerceptionEvent = PerceptionEvent;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F64770
// Name -> Function AIModule.AIPerceptionSystem.RegisterPerceptionStimuliSource
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UClass* Sense (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* Target (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UAIPerceptionSystem::STATIC_RegisterPerceptionStimuliSource(class UObject* WorldContextObject, class UClass* Sense, class AActor* Target)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionSystem.RegisterPerceptionStimuliSource");
UAIPerceptionSystem_RegisterPerceptionStimuliSource_Params params {};
params.WorldContextObject = WorldContextObject;
params.Sense = Sense;
params.Target = Target;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F64630
// Name -> Function AIModule.AIPerceptionSystem.OnPerceptionStimuliSourceEndPlay
// Flags -> (Final, Native, Protected)
// Parameters:
// class AActor* Actor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<Engine_EEndPlayReason> EndPlayReason (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAIPerceptionSystem::OnPerceptionStimuliSourceEndPlay(class AActor* Actor, TEnumAsByte<Engine_EEndPlayReason> EndPlayReason)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionSystem.OnPerceptionStimuliSourceEndPlay");
UAIPerceptionSystem_OnPerceptionStimuliSourceEndPlay_Params params {};
params.Actor = Actor;
params.EndPlayReason = EndPlayReason;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F63A00
// Name -> Function AIModule.AIPerceptionSystem.GetSenseClassForStimulus
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FAIStimulus Stimulus (ConstParm, Parm, OutParm, ReferenceParm, NoDestructor, NativeAccessSpecifierPublic)
// class UClass* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UClass* UAIPerceptionSystem::STATIC_GetSenseClassForStimulus(class UObject* WorldContextObject, const struct FAIStimulus& Stimulus)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AIPerceptionSystem.GetSenseClassForStimulus");
UAIPerceptionSystem_GetSenseClassForStimulus_Params params {};
params.WorldContextObject = WorldContextObject;
params.Stimulus = Stimulus;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UAIPerceptionSystem::AfterRead()
{
UAISubsystem::AfterRead();
}
void UAIPerceptionSystem::BeforeDelete()
{
UAISubsystem::BeforeDelete();
}
void UAIResourceInterface::AfterRead()
{
UInterface::AfterRead();
}
void UAIResourceInterface::BeforeDelete()
{
UInterface::BeforeDelete();
}
void UAIResource_Movement::AfterRead()
{
UGameplayTaskResource::AfterRead();
}
void UAIResource_Movement::BeforeDelete()
{
UGameplayTaskResource::BeforeDelete();
}
void UAIResource_Logic::AfterRead()
{
UGameplayTaskResource::AfterRead();
}
void UAIResource_Logic::BeforeDelete()
{
UGameplayTaskResource::BeforeDelete();
}
void UAISense::AfterRead()
{
UObject::AfterRead();
READ_PTR_FULL(PerceptionSystemInstance, UAIPerceptionSystem);
}
void UAISense::BeforeDelete()
{
UObject::BeforeDelete();
DELE_PTR_FULL(PerceptionSystemInstance);
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.AISense_Blueprint.OnUpdate
// Flags -> (Event, Public, HasOutParms, BlueprintEvent)
// Parameters:
// TArray<class UAISenseEvent*> EventsToProcess (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, NativeAccessSpecifierPublic)
// float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float UAISense_Blueprint::OnUpdate(TArray<class UAISenseEvent*> EventsToProcess)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Blueprint.OnUpdate");
UAISense_Blueprint_OnUpdate_Params params {};
params.EventsToProcess = EventsToProcess;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.AISense_Blueprint.OnListenerUpdated
// Flags -> (Event, Public, BlueprintEvent)
// Parameters:
// class AActor* ActorListener (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UAIPerceptionComponent* PerceptionComponent (Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAISense_Blueprint::OnListenerUpdated(class AActor* ActorListener, class UAIPerceptionComponent* PerceptionComponent)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Blueprint.OnListenerUpdated");
UAISense_Blueprint_OnListenerUpdated_Params params {};
params.ActorListener = ActorListener;
params.PerceptionComponent = PerceptionComponent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.AISense_Blueprint.OnListenerUnregistered
// Flags -> (Event, Public, BlueprintEvent)
// Parameters:
// class AActor* ActorListener (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UAIPerceptionComponent* PerceptionComponent (Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAISense_Blueprint::OnListenerUnregistered(class AActor* ActorListener, class UAIPerceptionComponent* PerceptionComponent)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Blueprint.OnListenerUnregistered");
UAISense_Blueprint_OnListenerUnregistered_Params params {};
params.ActorListener = ActorListener;
params.PerceptionComponent = PerceptionComponent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.AISense_Blueprint.OnListenerRegistered
// Flags -> (Event, Public, BlueprintEvent)
// Parameters:
// class AActor* ActorListener (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UAIPerceptionComponent* PerceptionComponent (Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAISense_Blueprint::OnListenerRegistered(class AActor* ActorListener, class UAIPerceptionComponent* PerceptionComponent)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Blueprint.OnListenerRegistered");
UAISense_Blueprint_OnListenerRegistered_Params params {};
params.ActorListener = ActorListener;
params.PerceptionComponent = PerceptionComponent;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.AISense_Blueprint.K2_OnNewPawn
// Flags -> (Event, Public, BlueprintEvent)
// Parameters:
// class APawn* NewPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAISense_Blueprint::K2_OnNewPawn(class APawn* NewPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Blueprint.K2_OnNewPawn");
UAISense_Blueprint_K2_OnNewPawn_Params params {};
params.NewPawn = NewPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F69340
// Name -> Function AIModule.AISense_Blueprint.GetAllListenerComponents
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// TArray<class UAIPerceptionComponent*> ListenerComponents (Parm, OutParm, ZeroConstructor, ContainsInstancedReference, NativeAccessSpecifierPublic)
void UAISense_Blueprint::GetAllListenerComponents(TArray<class UAIPerceptionComponent*>* ListenerComponents)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Blueprint.GetAllListenerComponents");
UAISense_Blueprint_GetAllListenerComponents_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (ListenerComponents != nullptr)
*ListenerComponents = params.ListenerComponents;
}
// Function:
// Offset -> 0x01F69290
// Name -> Function AIModule.AISense_Blueprint.GetAllListenerActors
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// TArray<class AActor*> ListenerActors (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic)
void UAISense_Blueprint::GetAllListenerActors(TArray<class AActor*>* ListenerActors)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Blueprint.GetAllListenerActors");
UAISense_Blueprint_GetAllListenerActors_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (ListenerActors != nullptr)
*ListenerActors = params.ListenerActors;
}
void UAISense_Blueprint::AfterRead()
{
UAISense::AfterRead();
READ_PTR_FULL(ListenerDataType, UClass);
}
void UAISense_Blueprint::BeforeDelete()
{
UAISense::BeforeDelete();
DELE_PTR_FULL(ListenerDataType);
}
// Function:
// Offset -> 0x01F69490
// Name -> Function AIModule.AISense_Damage.ReportDamageEvent
// Flags -> (Final, Native, Static, Public, HasDefaults, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* DamagedActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* Instigator (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float DamageAmount (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector EventLocation (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector HitLocation (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAISense_Damage::STATIC_ReportDamageEvent(class UObject* WorldContextObject, class AActor* DamagedActor, class AActor* Instigator, float DamageAmount, const struct FVector& EventLocation, const struct FVector& HitLocation)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Damage.ReportDamageEvent");
UAISense_Damage_ReportDamageEvent_Params params {};
params.WorldContextObject = WorldContextObject;
params.DamagedActor = DamagedActor;
params.Instigator = Instigator;
params.DamageAmount = DamageAmount;
params.EventLocation = EventLocation;
params.HitLocation = HitLocation;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UAISense_Damage::AfterRead()
{
UAISense::AfterRead();
}
void UAISense_Damage::BeforeDelete()
{
UAISense::BeforeDelete();
}
void UEnvQueryNode::AfterRead()
{
UObject::AfterRead();
}
void UEnvQueryNode::BeforeDelete()
{
UObject::BeforeDelete();
}
void UEnvQueryTest::AfterRead()
{
UEnvQueryNode::AfterRead();
}
void UEnvQueryTest::BeforeDelete()
{
UEnvQueryNode::BeforeDelete();
}
void UEnvQueryTest_GameplayTags::AfterRead()
{
UEnvQueryTest::AfterRead();
}
void UEnvQueryTest_GameplayTags::BeforeDelete()
{
UEnvQueryTest::BeforeDelete();
}
void UEnvQueryTest_Overlap::AfterRead()
{
UEnvQueryTest::AfterRead();
}
void UEnvQueryTest_Overlap::BeforeDelete()
{
UEnvQueryTest::BeforeDelete();
}
void UEnvQueryTest_Pathfinding::AfterRead()
{
UEnvQueryTest::AfterRead();
READ_PTR_FULL(Context, UClass);
READ_PTR_FULL(FilterClass, UClass);
}
void UEnvQueryTest_Pathfinding::BeforeDelete()
{
UEnvQueryTest::BeforeDelete();
DELE_PTR_FULL(Context);
DELE_PTR_FULL(FilterClass);
}
void UEnvQueryTest_PathfindingBatch::AfterRead()
{
UEnvQueryTest_Pathfinding::AfterRead();
}
void UEnvQueryTest_PathfindingBatch::BeforeDelete()
{
UEnvQueryTest_Pathfinding::BeforeDelete();
}
void UEnvQueryTest_Project::AfterRead()
{
UEnvQueryTest::AfterRead();
}
void UEnvQueryTest_Project::BeforeDelete()
{
UEnvQueryTest::BeforeDelete();
}
void UEnvQueryTest_Random::AfterRead()
{
UEnvQueryTest::AfterRead();
}
void UEnvQueryTest_Random::BeforeDelete()
{
UEnvQueryTest::BeforeDelete();
}
void UEnvQueryTest_Trace::AfterRead()
{
UEnvQueryTest::AfterRead();
READ_PTR_FULL(Context, UClass);
}
void UEnvQueryTest_Trace::BeforeDelete()
{
UEnvQueryTest::BeforeDelete();
DELE_PTR_FULL(Context);
}
void UEnvQueryTypes::AfterRead()
{
UObject::AfterRead();
}
void UEnvQueryTypes::BeforeDelete()
{
UObject::BeforeDelete();
}
void UEQSQueryResultSourceInterface::AfterRead()
{
UInterface::AfterRead();
}
void UEQSQueryResultSourceInterface::BeforeDelete()
{
UInterface::BeforeDelete();
}
void UEQSRenderingComponent::AfterRead()
{
UPrimitiveComponent::AfterRead();
}
void UEQSRenderingComponent::BeforeDelete()
{
UPrimitiveComponent::BeforeDelete();
}
void AEQSTestingPawn::AfterRead()
{
ACharacter::AfterRead();
READ_PTR_FULL(QueryTemplate, UEnvQuery);
}
void AEQSTestingPawn::BeforeDelete()
{
ACharacter::BeforeDelete();
DELE_PTR_FULL(QueryTemplate);
}
void UGenericTeamAgentInterface::AfterRead()
{
UInterface::AfterRead();
}
void UGenericTeamAgentInterface::BeforeDelete()
{
UInterface::BeforeDelete();
}
void AGridPathAIController::AfterRead()
{
AAIController::AfterRead();
}
void AGridPathAIController::BeforeDelete()
{
AAIController::BeforeDelete();
}
// Function:
// Offset -> 0x01F7C0D0
// Name -> Function AIModule.PathFollowingComponent.OnNavDataRegistered
// Flags -> (Final, Native, Protected)
// Parameters:
// class ANavigationData* NavData (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPathFollowingComponent::OnNavDataRegistered(class ANavigationData* NavData)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PathFollowingComponent.OnNavDataRegistered");
UPathFollowingComponent_OnNavDataRegistered_Params params {};
params.NavData = NavData;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F7BF30
// Name -> Function AIModule.PathFollowingComponent.OnActorBump
// Flags -> (Native, Public, HasOutParms, HasDefaults)
// Parameters:
// class AActor* SelfActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* OtherActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector NormalImpulse (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FHitResult Hit (ConstParm, Parm, OutParm, ReferenceParm, IsPlainOldData, NoDestructor, ContainsInstancedReference, NativeAccessSpecifierPublic)
void UPathFollowingComponent::OnActorBump(class AActor* SelfActor, class AActor* OtherActor, const struct FVector& NormalImpulse, const struct FHitResult& Hit)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PathFollowingComponent.OnActorBump");
UPathFollowingComponent_OnActorBump_Params params {};
params.SelfActor = SelfActor;
params.OtherActor = OtherActor;
params.NormalImpulse = NormalImpulse;
params.Hit = Hit;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F7BBA0
// Name -> Function AIModule.PathFollowingComponent.GetPathDestination
// Flags -> (Final, Native, Public, HasDefaults, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FVector ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FVector UPathFollowingComponent::GetPathDestination()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PathFollowingComponent.GetPathDestination");
UPathFollowingComponent_GetPathDestination_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F7BB70
// Name -> Function AIModule.PathFollowingComponent.GetPathActionType
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// TEnumAsByte<AIModule_EPathFollowingAction> ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<AIModule_EPathFollowingAction> UPathFollowingComponent::GetPathActionType()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PathFollowingComponent.GetPathActionType");
UPathFollowingComponent_GetPathActionType_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UPathFollowingComponent::AfterRead()
{
UActorComponent::AfterRead();
READ_PTR_FULL(MovementComp, UNavMovementComponent);
READ_PTR_FULL(MyNavData, ANavigationData);
}
void UPathFollowingComponent::BeforeDelete()
{
UActorComponent::BeforeDelete();
DELE_PTR_FULL(MovementComp);
DELE_PTR_FULL(MyNavData);
}
void UGridPathFollowingComponent::AfterRead()
{
UPathFollowingComponent::AfterRead();
READ_PTR_FULL(GridManager, UNavLocalGridManager);
}
void UGridPathFollowingComponent::BeforeDelete()
{
UPathFollowingComponent::BeforeDelete();
DELE_PTR_FULL(GridManager);
}
void UNavFilter_AIControllerDefault::AfterRead()
{
UNavigationQueryFilter::AfterRead();
}
void UNavFilter_AIControllerDefault::BeforeDelete()
{
UNavigationQueryFilter::BeforeDelete();
}
// Function:
// Offset -> 0x01F7A300
// Name -> Function AIModule.NavLinkProxy.SetSmartLinkEnabled
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// bool bEnabled (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void ANavLinkProxy::SetSmartLinkEnabled(bool bEnabled)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLinkProxy.SetSmartLinkEnabled");
ANavLinkProxy_SetSmartLinkEnabled_Params params {};
params.bEnabled = bEnabled;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F7A030
// Name -> Function AIModule.NavLinkProxy.ResumePathFollowing
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class AActor* Agent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void ANavLinkProxy::ResumePathFollowing(class AActor* Agent)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLinkProxy.ResumePathFollowing");
ANavLinkProxy_ResumePathFollowing_Params params {};
params.Agent = Agent;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.NavLinkProxy.ReceiveSmartLinkReached
// Flags -> (Event, Public, HasOutParms, HasDefaults, BlueprintEvent)
// Parameters:
// class AActor* Agent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector Destination (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void ANavLinkProxy::ReceiveSmartLinkReached(class AActor* Agent, const struct FVector& Destination)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLinkProxy.ReceiveSmartLinkReached");
ANavLinkProxy_ReceiveSmartLinkReached_Params params {};
params.Agent = Agent;
params.Destination = Destination;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F79F10
// Name -> Function AIModule.NavLinkProxy.IsSmartLinkEnabled
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool ANavLinkProxy::IsSmartLinkEnabled()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLinkProxy.IsSmartLinkEnabled");
ANavLinkProxy_IsSmartLinkEnabled_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F79EE0
// Name -> Function AIModule.NavLinkProxy.HasMovingAgents
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool ANavLinkProxy::HasMovingAgents()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLinkProxy.HasMovingAgents");
ANavLinkProxy_HasMovingAgents_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void ANavLinkProxy::AfterRead()
{
AActor::AfterRead();
READ_PTR_FULL(SmartLinkComp, UNavLinkCustomComponent);
}
void ANavLinkProxy::BeforeDelete()
{
AActor::BeforeDelete();
DELE_PTR_FULL(SmartLinkComp);
}
// Function:
// Offset -> 0x01F7A230
// Name -> Function AIModule.NavLocalGridManager.SetLocalNavigationGridDensity
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float CellSize (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UNavLocalGridManager::STATIC_SetLocalNavigationGridDensity(class UObject* WorldContextObject, float CellSize)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLocalGridManager.SetLocalNavigationGridDensity");
UNavLocalGridManager_SetLocalNavigationGridDensity_Params params {};
params.WorldContextObject = WorldContextObject;
params.CellSize = CellSize;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F79F40
// Name -> Function AIModule.NavLocalGridManager.RemoveLocalNavigationGrid
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// int GridId (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bRebuildGrids (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UNavLocalGridManager::STATIC_RemoveLocalNavigationGrid(class UObject* WorldContextObject, int GridId, bool bRebuildGrids)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLocalGridManager.RemoveLocalNavigationGrid");
UNavLocalGridManager_RemoveLocalNavigationGrid_Params params {};
params.WorldContextObject = WorldContextObject;
params.GridId = GridId;
params.bRebuildGrids = bRebuildGrids;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F79D50
// Name -> Function AIModule.NavLocalGridManager.FindLocalNavigationGridPath
// Flags -> (Final, Native, Static, Public, HasOutParms, HasDefaults, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector Start (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector End (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TArray<struct FVector> PathPoints (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UNavLocalGridManager::STATIC_FindLocalNavigationGridPath(class UObject* WorldContextObject, const struct FVector& Start, const struct FVector& End, TArray<struct FVector>* PathPoints)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLocalGridManager.FindLocalNavigationGridPath");
UNavLocalGridManager_FindLocalNavigationGridPath_Params params {};
params.WorldContextObject = WorldContextObject;
params.Start = Start;
params.End = End;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (PathPoints != nullptr)
*PathPoints = params.PathPoints;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F79B90
// Name -> Function AIModule.NavLocalGridManager.AddLocalNavigationGridForPoints
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TArray<struct FVector> Locations (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, NativeAccessSpecifierPublic)
// int Radius2D (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float Height (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bRebuildGrids (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int UNavLocalGridManager::STATIC_AddLocalNavigationGridForPoints(class UObject* WorldContextObject, TArray<struct FVector> Locations, int Radius2D, float Height, bool bRebuildGrids)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLocalGridManager.AddLocalNavigationGridForPoints");
UNavLocalGridManager_AddLocalNavigationGridForPoints_Params params {};
params.WorldContextObject = WorldContextObject;
params.Locations = Locations;
params.Radius2D = Radius2D;
params.Height = Height;
params.bRebuildGrids = bRebuildGrids;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F799E0
// Name -> Function AIModule.NavLocalGridManager.AddLocalNavigationGridForPoint
// Flags -> (Final, Native, Static, Public, HasOutParms, HasDefaults, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector Location (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// int Radius2D (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float Height (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bRebuildGrids (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int UNavLocalGridManager::STATIC_AddLocalNavigationGridForPoint(class UObject* WorldContextObject, const struct FVector& Location, int Radius2D, float Height, bool bRebuildGrids)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLocalGridManager.AddLocalNavigationGridForPoint");
UNavLocalGridManager_AddLocalNavigationGridForPoint_Params params {};
params.WorldContextObject = WorldContextObject;
params.Location = Location;
params.Radius2D = Radius2D;
params.Height = Height;
params.bRebuildGrids = bRebuildGrids;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F797E0
// Name -> Function AIModule.NavLocalGridManager.AddLocalNavigationGridForCapsule
// Flags -> (Final, Native, Static, Public, HasOutParms, HasDefaults, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector Location (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float CapsuleRadius (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float CapsuleHalfHeight (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// int Radius2D (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float Height (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bRebuildGrids (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int UNavLocalGridManager::STATIC_AddLocalNavigationGridForCapsule(class UObject* WorldContextObject, const struct FVector& Location, float CapsuleRadius, float CapsuleHalfHeight, int Radius2D, float Height, bool bRebuildGrids)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLocalGridManager.AddLocalNavigationGridForCapsule");
UNavLocalGridManager_AddLocalNavigationGridForCapsule_Params params {};
params.WorldContextObject = WorldContextObject;
params.Location = Location;
params.CapsuleRadius = CapsuleRadius;
params.CapsuleHalfHeight = CapsuleHalfHeight;
params.Radius2D = Radius2D;
params.Height = Height;
params.bRebuildGrids = bRebuildGrids;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F795C0
// Name -> Function AIModule.NavLocalGridManager.AddLocalNavigationGridForBox
// Flags -> (Final, Native, Static, Public, HasOutParms, HasDefaults, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector Location (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector Extent (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FRotator Rotation (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
// int Radius2D (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float Height (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bRebuildGrids (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int UNavLocalGridManager::STATIC_AddLocalNavigationGridForBox(class UObject* WorldContextObject, const struct FVector& Location, const struct FVector& Extent, const struct FRotator& Rotation, int Radius2D, float Height, bool bRebuildGrids)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.NavLocalGridManager.AddLocalNavigationGridForBox");
UNavLocalGridManager_AddLocalNavigationGridForBox_Params params {};
params.WorldContextObject = WorldContextObject;
params.Location = Location;
params.Extent = Extent;
params.Rotation = Rotation;
params.Radius2D = Radius2D;
params.Height = Height;
params.bRebuildGrids = bRebuildGrids;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UNavLocalGridManager::AfterRead()
{
UObject::AfterRead();
}
void UNavLocalGridManager::BeforeDelete()
{
UObject::BeforeDelete();
}
void UPathFollowingManager::AfterRead()
{
UObject::AfterRead();
}
void UPathFollowingManager::BeforeDelete()
{
UObject::BeforeDelete();
}
// Function:
// Offset -> 0x01F7BB50
// Name -> Function AIModule.PawnAction.GetActionPriority
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure)
// Parameters:
// TEnumAsByte<AIModule_EAIRequestPriority> ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<AIModule_EAIRequestPriority> UPawnAction::GetActionPriority()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnAction.GetActionPriority");
UPawnAction_GetActionPriority_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x0156E990
// Name -> Function AIModule.PawnAction.Finish
// Flags -> (Native, Protected, BlueprintCallable)
// Parameters:
// TEnumAsByte<AIModule_EPawnActionResult> WithResult (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnAction::Finish(TEnumAsByte<AIModule_EPawnActionResult> WithResult)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnAction.Finish");
UPawnAction_Finish_Params params {};
params.WithResult = WithResult;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F7BA90
// Name -> Function AIModule.PawnAction.CreateActionInstance
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UClass* ActionClass (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UPawnAction* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UPawnAction* UPawnAction::STATIC_CreateActionInstance(class UObject* WorldContextObject, class UClass* ActionClass)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnAction.CreateActionInstance");
UPawnAction_CreateActionInstance_Params params {};
params.WorldContextObject = WorldContextObject;
params.ActionClass = ActionClass;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UPawnAction::AfterRead()
{
UObject::AfterRead();
READ_PTR_FULL(ChildAction, UPawnAction);
READ_PTR_FULL(ParentAction, UPawnAction);
READ_PTR_FULL(OwnerComponent, UPawnActionsComponent);
READ_PTR_FULL(Instigator, UObject);
READ_PTR_FULL(BrainComp, UBrainComponent);
}
void UPawnAction::BeforeDelete()
{
UObject::BeforeDelete();
DELE_PTR_FULL(ChildAction);
DELE_PTR_FULL(ParentAction);
DELE_PTR_FULL(OwnerComponent);
DELE_PTR_FULL(Instigator);
DELE_PTR_FULL(BrainComp);
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.PawnAction_BlueprintBase.ActionTick
// Flags -> (Event, Public, BlueprintEvent)
// Parameters:
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnAction_BlueprintBase::ActionTick(class APawn* ControlledPawn, float DeltaSeconds)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnAction_BlueprintBase.ActionTick");
UPawnAction_BlueprintBase_ActionTick_Params params {};
params.ControlledPawn = ControlledPawn;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.PawnAction_BlueprintBase.ActionStart
// Flags -> (Event, Public, BlueprintEvent)
// Parameters:
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnAction_BlueprintBase::ActionStart(class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnAction_BlueprintBase.ActionStart");
UPawnAction_BlueprintBase_ActionStart_Params params {};
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.PawnAction_BlueprintBase.ActionResume
// Flags -> (Event, Public, BlueprintEvent)
// Parameters:
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnAction_BlueprintBase::ActionResume(class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnAction_BlueprintBase.ActionResume");
UPawnAction_BlueprintBase_ActionResume_Params params {};
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.PawnAction_BlueprintBase.ActionPause
// Flags -> (Event, Public, BlueprintEvent)
// Parameters:
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnAction_BlueprintBase::ActionPause(class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnAction_BlueprintBase.ActionPause");
UPawnAction_BlueprintBase_ActionPause_Params params {};
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.PawnAction_BlueprintBase.ActionFinished
// Flags -> (Event, Public, BlueprintEvent)
// Parameters:
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EPawnActionResult> WithResult (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnAction_BlueprintBase::ActionFinished(class APawn* ControlledPawn, TEnumAsByte<AIModule_EPawnActionResult> WithResult)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnAction_BlueprintBase.ActionFinished");
UPawnAction_BlueprintBase_ActionFinished_Params params {};
params.ControlledPawn = ControlledPawn;
params.WithResult = WithResult;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UPawnAction_BlueprintBase::AfterRead()
{
UPawnAction::AfterRead();
}
void UPawnAction_BlueprintBase::BeforeDelete()
{
UPawnAction::BeforeDelete();
}
void UPawnAction_Move::AfterRead()
{
UPawnAction::AfterRead();
READ_PTR_FULL(GoalActor, AActor);
READ_PTR_FULL(FilterClass, UClass);
}
void UPawnAction_Move::BeforeDelete()
{
UPawnAction::BeforeDelete();
DELE_PTR_FULL(GoalActor);
DELE_PTR_FULL(FilterClass);
}
void UPawnAction_Repeat::AfterRead()
{
UPawnAction::AfterRead();
READ_PTR_FULL(ActionToRepeat, UPawnAction);
READ_PTR_FULL(RecentActionCopy, UPawnAction);
}
void UPawnAction_Repeat::BeforeDelete()
{
UPawnAction::BeforeDelete();
DELE_PTR_FULL(ActionToRepeat);
DELE_PTR_FULL(RecentActionCopy);
}
void UPawnAction_Sequence::AfterRead()
{
UPawnAction::AfterRead();
READ_PTR_FULL(RecentActionCopy, UPawnAction);
}
void UPawnAction_Sequence::BeforeDelete()
{
UPawnAction::BeforeDelete();
DELE_PTR_FULL(RecentActionCopy);
}
void UPawnAction_Wait::AfterRead()
{
UPawnAction::AfterRead();
}
void UPawnAction_Wait::BeforeDelete()
{
UPawnAction::BeforeDelete();
}
// Function:
// Offset -> 0x01F7BE30
// Name -> Function AIModule.PawnActionsComponent.K2_PushAction
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class UPawnAction* NewAction (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EAIRequestPriority> Priority (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UObject* Instigator (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UPawnActionsComponent::K2_PushAction(class UPawnAction* NewAction, TEnumAsByte<AIModule_EAIRequestPriority> Priority, class UObject* Instigator)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnActionsComponent.K2_PushAction");
UPawnActionsComponent_K2_PushAction_Params params {};
params.NewAction = NewAction;
params.Priority = Priority;
params.Instigator = Instigator;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F7BD40
// Name -> Function AIModule.PawnActionsComponent.K2_PerformAction
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class APawn* Pawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UPawnAction* Action (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EAIRequestPriority> Priority (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UPawnActionsComponent::STATIC_K2_PerformAction(class APawn* Pawn, class UPawnAction* Action, TEnumAsByte<AIModule_EAIRequestPriority> Priority)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnActionsComponent.K2_PerformAction");
UPawnActionsComponent_K2_PerformAction_Params params {};
params.Pawn = Pawn;
params.Action = Action;
params.Priority = Priority;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F7BCB0
// Name -> Function AIModule.PawnActionsComponent.K2_ForceAbortAction
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class UPawnAction* ActionToAbort (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EPawnActionAbortState> ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<AIModule_EPawnActionAbortState> UPawnActionsComponent::K2_ForceAbortAction(class UPawnAction* ActionToAbort)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnActionsComponent.K2_ForceAbortAction");
UPawnActionsComponent_K2_ForceAbortAction_Params params {};
params.ActionToAbort = ActionToAbort;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F7BC20
// Name -> Function AIModule.PawnActionsComponent.K2_AbortAction
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// class UPawnAction* ActionToAbort (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EPawnActionAbortState> ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<AIModule_EPawnActionAbortState> UPawnActionsComponent::K2_AbortAction(class UPawnAction* ActionToAbort)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnActionsComponent.K2_AbortAction");
UPawnActionsComponent_K2_AbortAction_Params params {};
params.ActionToAbort = ActionToAbort;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UPawnActionsComponent::AfterRead()
{
UActorComponent::AfterRead();
READ_PTR_FULL(ControlledPawn, APawn);
READ_PTR_FULL(CurrentAction, UPawnAction);
}
void UPawnActionsComponent::BeforeDelete()
{
UActorComponent::BeforeDelete();
DELE_PTR_FULL(ControlledPawn);
DELE_PTR_FULL(CurrentAction);
}
// Function:
// Offset -> 0x01F7C250
// Name -> Function AIModule.PawnSensingComponent.SetSensingUpdatesEnabled
// Flags -> (BlueprintAuthorityOnly, Native, Public, BlueprintCallable)
// Parameters:
// bool bEnabled (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnSensingComponent::SetSensingUpdatesEnabled(bool bEnabled)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnSensingComponent.SetSensingUpdatesEnabled");
UPawnSensingComponent_SetSensingUpdatesEnabled_Params params {};
params.bEnabled = bEnabled;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F7C1D0
// Name -> Function AIModule.PawnSensingComponent.SetSensingInterval
// Flags -> (BlueprintAuthorityOnly, Native, Public, BlueprintCallable)
// Parameters:
// float NewSensingInterval (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnSensingComponent::SetSensingInterval(float NewSensingInterval)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnSensingComponent.SetSensingInterval");
UPawnSensingComponent_SetSensingInterval_Params params {};
params.NewSensingInterval = NewSensingInterval;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F7C150
// Name -> Function AIModule.PawnSensingComponent.SetPeripheralVisionAngle
// Flags -> (BlueprintAuthorityOnly, Native, Public, BlueprintCallable)
// Parameters:
// float NewPeripheralVisionAngle (ConstParm, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnSensingComponent::SetPeripheralVisionAngle(float NewPeripheralVisionAngle)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnSensingComponent.SetPeripheralVisionAngle");
UPawnSensingComponent_SetPeripheralVisionAngle_Params params {};
params.NewPeripheralVisionAngle = NewPeripheralVisionAngle;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> DelegateFunction AIModule.PawnSensingComponent.SeePawnDelegate__DelegateSignature
// Flags -> (MulticastDelegate, Public, Delegate)
// Parameters:
// class APawn* Pawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnSensingComponent::SeePawnDelegate__DelegateSignature(class APawn* Pawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("DelegateFunction AIModule.PawnSensingComponent.SeePawnDelegate__DelegateSignature");
UPawnSensingComponent_SeePawnDelegate__DelegateSignature_Params params {};
params.Pawn = Pawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> DelegateFunction AIModule.PawnSensingComponent.HearNoiseDelegate__DelegateSignature
// Flags -> (MulticastDelegate, Public, Delegate, HasOutParms, HasDefaults)
// Parameters:
// class APawn* Instigator (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector Location (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float Volume (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UPawnSensingComponent::HearNoiseDelegate__DelegateSignature(class APawn* Instigator, const struct FVector& Location, float Volume)
{
static UFunction* fn = UObject::FindObject<UFunction>("DelegateFunction AIModule.PawnSensingComponent.HearNoiseDelegate__DelegateSignature");
UPawnSensingComponent_HearNoiseDelegate__DelegateSignature_Params params {};
params.Instigator = Instigator;
params.Location = Location;
params.Volume = Volume;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F7BC00
// Name -> Function AIModule.PawnSensingComponent.GetPeripheralVisionCosine
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float UPawnSensingComponent::GetPeripheralVisionCosine()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnSensingComponent.GetPeripheralVisionCosine");
UPawnSensingComponent_GetPeripheralVisionCosine_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F7BBE0
// Name -> Function AIModule.PawnSensingComponent.GetPeripheralVisionAngle
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float UPawnSensingComponent::GetPeripheralVisionAngle()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.PawnSensingComponent.GetPeripheralVisionAngle");
UPawnSensingComponent_GetPeripheralVisionAngle_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UPawnSensingComponent::AfterRead()
{
UActorComponent::AfterRead();
}
void UPawnSensingComponent::BeforeDelete()
{
UActorComponent::BeforeDelete();
}
void UVisualLoggerExtension::AfterRead()
{
UObject::AfterRead();
}
void UVisualLoggerExtension::BeforeDelete()
{
UObject::BeforeDelete();
}
// Function:
// Offset -> 0x01F69660
// Name -> Function AIModule.AISense_Hearing.ReportNoiseEvent
// Flags -> (Final, Native, Static, Public, HasDefaults, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector NoiseLocation (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float Loudness (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* Instigator (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float MaxRange (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FName Tag (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAISense_Hearing::STATIC_ReportNoiseEvent(class UObject* WorldContextObject, const struct FVector& NoiseLocation, float Loudness, class AActor* Instigator, float MaxRange, const struct FName& Tag)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Hearing.ReportNoiseEvent");
UAISense_Hearing_ReportNoiseEvent_Params params {};
params.WorldContextObject = WorldContextObject;
params.NoiseLocation = NoiseLocation;
params.Loudness = Loudness;
params.Instigator = Instigator;
params.MaxRange = MaxRange;
params.Tag = Tag;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UAISense_Hearing::AfterRead()
{
UAISense::AfterRead();
}
void UAISense_Hearing::BeforeDelete()
{
UAISense::BeforeDelete();
}
// Function:
// Offset -> 0x01F69920
// Name -> Function AIModule.AISense_Prediction.RequestPawnPredictionEvent
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class APawn* Requestor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* PredictedActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float PredictionTime (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAISense_Prediction::STATIC_RequestPawnPredictionEvent(class APawn* Requestor, class AActor* PredictedActor, float PredictionTime)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Prediction.RequestPawnPredictionEvent");
UAISense_Prediction_RequestPawnPredictionEvent_Params params {};
params.Requestor = Requestor;
params.PredictedActor = PredictedActor;
params.PredictionTime = PredictionTime;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F69820
// Name -> Function AIModule.AISense_Prediction.RequestControllerPredictionEvent
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class AAIController* Requestor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* PredictedActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float PredictionTime (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UAISense_Prediction::STATIC_RequestControllerPredictionEvent(class AAIController* Requestor, class AActor* PredictedActor, float PredictionTime)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISense_Prediction.RequestControllerPredictionEvent");
UAISense_Prediction_RequestControllerPredictionEvent_Params params {};
params.Requestor = Requestor;
params.PredictedActor = PredictedActor;
params.PredictionTime = PredictionTime;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UAISense_Prediction::AfterRead()
{
UAISense::AfterRead();
}
void UAISense_Prediction::BeforeDelete()
{
UAISense::BeforeDelete();
}
void UAISense_Sight::AfterRead()
{
UAISense::AfterRead();
}
void UAISense_Sight::BeforeDelete()
{
UAISense::BeforeDelete();
}
void UAISense_Team::AfterRead()
{
UAISense::AfterRead();
}
void UAISense_Team::BeforeDelete()
{
UAISense::BeforeDelete();
}
void UAISense_Touch::AfterRead()
{
UAISense::AfterRead();
}
void UAISense_Touch::BeforeDelete()
{
UAISense::BeforeDelete();
}
void UAISenseBlueprintListener::AfterRead()
{
UUserDefinedStruct::AfterRead();
}
void UAISenseBlueprintListener::BeforeDelete()
{
UUserDefinedStruct::BeforeDelete();
}
void UAISenseConfig::AfterRead()
{
UObject::AfterRead();
}
void UAISenseConfig::BeforeDelete()
{
UObject::BeforeDelete();
}
void UAISenseConfig_Blueprint::AfterRead()
{
UAISenseConfig::AfterRead();
READ_PTR_FULL(Implementation, UClass);
}
void UAISenseConfig_Blueprint::BeforeDelete()
{
UAISenseConfig::BeforeDelete();
DELE_PTR_FULL(Implementation);
}
void UAISenseConfig_Damage::AfterRead()
{
UAISenseConfig::AfterRead();
READ_PTR_FULL(Implementation, UClass);
}
void UAISenseConfig_Damage::BeforeDelete()
{
UAISenseConfig::BeforeDelete();
DELE_PTR_FULL(Implementation);
}
void UAISenseConfig_Hearing::AfterRead()
{
UAISenseConfig::AfterRead();
READ_PTR_FULL(Implementation, UClass);
}
void UAISenseConfig_Hearing::BeforeDelete()
{
UAISenseConfig::BeforeDelete();
DELE_PTR_FULL(Implementation);
}
void UAISenseConfig_Prediction::AfterRead()
{
UAISenseConfig::AfterRead();
}
void UAISenseConfig_Prediction::BeforeDelete()
{
UAISenseConfig::BeforeDelete();
}
void UAISenseConfig_Sight::AfterRead()
{
UAISenseConfig::AfterRead();
READ_PTR_FULL(Implementation, UClass);
}
void UAISenseConfig_Sight::BeforeDelete()
{
UAISenseConfig::BeforeDelete();
DELE_PTR_FULL(Implementation);
}
void UAISenseConfig_Team::AfterRead()
{
UAISenseConfig::AfterRead();
}
void UAISenseConfig_Team::BeforeDelete()
{
UAISenseConfig::BeforeDelete();
}
void UAISenseConfig_Touch::AfterRead()
{
UAISenseConfig::AfterRead();
}
void UAISenseConfig_Touch::BeforeDelete()
{
UAISenseConfig::BeforeDelete();
}
void UAISenseEvent::AfterRead()
{
UObject::AfterRead();
}
void UAISenseEvent::BeforeDelete()
{
UObject::BeforeDelete();
}
void UAISenseEvent_Damage::AfterRead()
{
UAISenseEvent::AfterRead();
}
void UAISenseEvent_Damage::BeforeDelete()
{
UAISenseEvent::BeforeDelete();
}
void UAISenseEvent_Hearing::AfterRead()
{
UAISenseEvent::AfterRead();
}
void UAISenseEvent_Hearing::BeforeDelete()
{
UAISenseEvent::BeforeDelete();
}
void UAISightTargetInterface::AfterRead()
{
UInterface::AfterRead();
}
void UAISightTargetInterface::BeforeDelete()
{
UInterface::BeforeDelete();
}
// Function:
// Offset -> 0x01647BA0
// Name -> Function AIModule.AISystem.AILoggingVerbose
// Flags -> (Exec, Native, Public)
void UAISystem::AILoggingVerbose()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISystem.AILoggingVerbose");
UAISystem_AILoggingVerbose_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01CE3BE0
// Name -> Function AIModule.AISystem.AIIgnorePlayers
// Flags -> (Exec, Native, Public)
void UAISystem::AIIgnorePlayers()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AISystem.AIIgnorePlayers");
UAISystem_AIIgnorePlayers_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UAISystem::AfterRead()
{
UAISystemBase::AfterRead();
READ_PTR_FULL(BehaviorTreeManager, UBehaviorTreeManager);
READ_PTR_FULL(EnvironmentQueryManager, UEnvQueryManager);
READ_PTR_FULL(PerceptionSystem, UAIPerceptionSystem);
READ_PTR_FULL(HotSpotManager, UAIHotSpotManager);
READ_PTR_FULL(NavLocalGrids, UNavLocalGridManager);
}
void UAISystem::BeforeDelete()
{
UAISystemBase::BeforeDelete();
DELE_PTR_FULL(BehaviorTreeManager);
DELE_PTR_FULL(EnvironmentQueryManager);
DELE_PTR_FULL(PerceptionSystem);
DELE_PTR_FULL(HotSpotManager);
DELE_PTR_FULL(NavLocalGrids);
}
void UAITask::AfterRead()
{
UGameplayTask::AfterRead();
READ_PTR_FULL(OwnerController, AAIController);
}
void UAITask::BeforeDelete()
{
UGameplayTask::BeforeDelete();
DELE_PTR_FULL(OwnerController);
}
void UAITask_LockLogic::AfterRead()
{
UAITask::AfterRead();
}
void UAITask_LockLogic::BeforeDelete()
{
UAITask::BeforeDelete();
}
// Function:
// Offset -> 0x01F68EF0
// Name -> Function AIModule.AITask_MoveTo.AIMoveTo
// Flags -> (Final, Native, Static, Public, HasDefaults, BlueprintCallable)
// Parameters:
// class AAIController* Controller (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector GoalLocation (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* GoalActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float AcceptanceRadius (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EAIOptionFlag> StopOnOverlap (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EAIOptionFlag> AcceptPartialPath (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bUsePathfinding (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bLockAILogic (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bUseContinuosGoalTracking (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UAITask_MoveTo* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UAITask_MoveTo* UAITask_MoveTo::STATIC_AIMoveTo(class AAIController* Controller, const struct FVector& GoalLocation, class AActor* GoalActor, float AcceptanceRadius, TEnumAsByte<AIModule_EAIOptionFlag> StopOnOverlap, TEnumAsByte<AIModule_EAIOptionFlag> AcceptPartialPath, bool bUsePathfinding, bool bLockAILogic, bool bUseContinuosGoalTracking)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AITask_MoveTo.AIMoveTo");
UAITask_MoveTo_AIMoveTo_Params params {};
params.Controller = Controller;
params.GoalLocation = GoalLocation;
params.GoalActor = GoalActor;
params.AcceptanceRadius = AcceptanceRadius;
params.StopOnOverlap = StopOnOverlap;
params.AcceptPartialPath = AcceptPartialPath;
params.bUsePathfinding = bUsePathfinding;
params.bLockAILogic = bLockAILogic;
params.bUseContinuosGoalTracking = bUseContinuosGoalTracking;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UAITask_MoveTo::AfterRead()
{
UAITask::AfterRead();
}
void UAITask_MoveTo::BeforeDelete()
{
UAITask::BeforeDelete();
}
// Function:
// Offset -> 0x01F69A20
// Name -> Function AIModule.AITask_RunEQS.RunEQS
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class AAIController* Controller (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UEnvQuery* QueryTemplate (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UAITask_RunEQS* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UAITask_RunEQS* UAITask_RunEQS::STATIC_RunEQS(class AAIController* Controller, class UEnvQuery* QueryTemplate)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.AITask_RunEQS.RunEQS");
UAITask_RunEQS_RunEQS_Params params {};
params.Controller = Controller;
params.QueryTemplate = QueryTemplate;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UAITask_RunEQS::AfterRead()
{
UAITask::AfterRead();
}
void UAITask_RunEQS::BeforeDelete()
{
UAITask::BeforeDelete();
}
void UBehaviorTree::AfterRead()
{
UObject::AfterRead();
READ_PTR_FULL(RootNode, UBTCompositeNode);
READ_PTR_FULL(BlackboardAsset, UBlackboardData);
}
void UBehaviorTree::BeforeDelete()
{
UObject::BeforeDelete();
DELE_PTR_FULL(RootNode);
DELE_PTR_FULL(BlackboardAsset);
}
// Function:
// Offset -> 0x01F6E030
// Name -> Function AIModule.BrainComponent.StopLogic
// Flags -> (Native, Public, BlueprintCallable)
// Parameters:
// struct FString Reason (Parm, ZeroConstructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBrainComponent::StopLogic(const struct FString& Reason)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BrainComponent.StopLogic");
UBrainComponent_StopLogic_Params params {};
params.Reason = Reason;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01DA6C60
// Name -> Function AIModule.BrainComponent.RestartLogic
// Flags -> (Native, Public, BlueprintCallable)
void UBrainComponent::RestartLogic()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BrainComponent.RestartLogic");
UBrainComponent_RestartLogic_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6D6A0
// Name -> Function AIModule.BrainComponent.IsRunning
// Flags -> (Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBrainComponent::IsRunning()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BrainComponent.IsRunning");
UBrainComponent_IsRunning_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D670
// Name -> Function AIModule.BrainComponent.IsPaused
// Flags -> (Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBrainComponent::IsPaused()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BrainComponent.IsPaused");
UBrainComponent_IsPaused_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UBrainComponent::AfterRead()
{
UActorComponent::AfterRead();
READ_PTR_FULL(BlackboardComp, UBlackboardComponent);
READ_PTR_FULL(AIOwner, AAIController);
}
void UBrainComponent::BeforeDelete()
{
UActorComponent::BeforeDelete();
DELE_PTR_FULL(BlackboardComp);
DELE_PTR_FULL(AIOwner);
}
// Function:
// Offset -> 0x01F69AE0
// Name -> Function AIModule.BehaviorTreeComponent.SetDynamicSubtree
// Flags -> (Native, Public, BlueprintCallable)
// Parameters:
// struct FGameplayTag InjectTag (Parm, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UBehaviorTree* BehaviorAsset (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBehaviorTreeComponent::SetDynamicSubtree(const struct FGameplayTag& InjectTag, class UBehaviorTree* BehaviorAsset)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BehaviorTreeComponent.SetDynamicSubtree");
UBehaviorTreeComponent_SetDynamicSubtree_Params params {};
params.InjectTag = InjectTag;
params.BehaviorAsset = BehaviorAsset;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F693F0
// Name -> Function AIModule.BehaviorTreeComponent.GetTagCooldownEndTime
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FGameplayTag CooldownTag (Parm, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float UBehaviorTreeComponent::GetTagCooldownEndTime(const struct FGameplayTag& CooldownTag)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BehaviorTreeComponent.GetTagCooldownEndTime");
UBehaviorTreeComponent_GetTagCooldownEndTime_Params params {};
params.CooldownTag = CooldownTag;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F69180
// Name -> Function AIModule.BehaviorTreeComponent.AddCooldownTagDuration
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// struct FGameplayTag CooldownTag (Parm, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float CooldownDuration (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool bAddToExistingDuration (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBehaviorTreeComponent::AddCooldownTagDuration(const struct FGameplayTag& CooldownTag, float CooldownDuration, bool bAddToExistingDuration)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BehaviorTreeComponent.AddCooldownTagDuration");
UBehaviorTreeComponent_AddCooldownTagDuration_Params params {};
params.CooldownTag = CooldownTag;
params.CooldownDuration = CooldownDuration;
params.bAddToExistingDuration = bAddToExistingDuration;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UBehaviorTreeComponent::AfterRead()
{
UBrainComponent::AfterRead();
}
void UBehaviorTreeComponent::BeforeDelete()
{
UBrainComponent::BeforeDelete();
}
void UBehaviorTreeManager::AfterRead()
{
UObject::AfterRead();
}
void UBehaviorTreeManager::BeforeDelete()
{
UObject::BeforeDelete();
}
void UBehaviorTreeTypes::AfterRead()
{
UObject::AfterRead();
}
void UBehaviorTreeTypes::BeforeDelete()
{
UObject::BeforeDelete();
}
// Function:
// Offset -> 0x01F6DF40
// Name -> Function AIModule.BlackboardComponent.SetValueAsVector
// Flags -> (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector VectorValue (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBlackboardComponent::SetValueAsVector(const struct FName& KeyName, const struct FVector& VectorValue)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.SetValueAsVector");
UBlackboardComponent_SetValueAsVector_Params params {};
params.KeyName = KeyName;
params.VectorValue = VectorValue;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6DE10
// Name -> Function AIModule.BlackboardComponent.SetValueAsString
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FString StringValue (Parm, ZeroConstructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBlackboardComponent::SetValueAsString(const struct FName& KeyName, const struct FString& StringValue)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.SetValueAsString");
UBlackboardComponent_SetValueAsString_Params params {};
params.KeyName = KeyName;
params.StringValue = StringValue;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6DD20
// Name -> Function AIModule.BlackboardComponent.SetValueAsRotator
// Flags -> (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FRotator VectorValue (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
void UBlackboardComponent::SetValueAsRotator(const struct FName& KeyName, const struct FRotator& VectorValue)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.SetValueAsRotator");
UBlackboardComponent_SetValueAsRotator_Params params {};
params.KeyName = KeyName;
params.VectorValue = VectorValue;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6DC50
// Name -> Function AIModule.BlackboardComponent.SetValueAsObject
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UObject* ObjectValue (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBlackboardComponent::SetValueAsObject(const struct FName& KeyName, class UObject* ObjectValue)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.SetValueAsObject");
UBlackboardComponent_SetValueAsObject_Params params {};
params.KeyName = KeyName;
params.ObjectValue = ObjectValue;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6DB80
// Name -> Function AIModule.BlackboardComponent.SetValueAsName
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FName NameValue (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBlackboardComponent::SetValueAsName(const struct FName& KeyName, const struct FName& NameValue)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.SetValueAsName");
UBlackboardComponent_SetValueAsName_Params params {};
params.KeyName = KeyName;
params.NameValue = NameValue;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6DAB0
// Name -> Function AIModule.BlackboardComponent.SetValueAsInt
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// int IntValue (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBlackboardComponent::SetValueAsInt(const struct FName& KeyName, int IntValue)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.SetValueAsInt");
UBlackboardComponent_SetValueAsInt_Params params {};
params.KeyName = KeyName;
params.IntValue = IntValue;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6D9E0
// Name -> Function AIModule.BlackboardComponent.SetValueAsFloat
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float FloatValue (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBlackboardComponent::SetValueAsFloat(const struct FName& KeyName, float FloatValue)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.SetValueAsFloat");
UBlackboardComponent_SetValueAsFloat_Params params {};
params.KeyName = KeyName;
params.FloatValue = FloatValue;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6D910
// Name -> Function AIModule.BlackboardComponent.SetValueAsEnum
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// unsigned char EnumValue (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBlackboardComponent::SetValueAsEnum(const struct FName& KeyName, unsigned char EnumValue)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.SetValueAsEnum");
UBlackboardComponent_SetValueAsEnum_Params params {};
params.KeyName = KeyName;
params.EnumValue = EnumValue;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6D840
// Name -> Function AIModule.BlackboardComponent.SetValueAsClass
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UClass* ClassValue (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBlackboardComponent::SetValueAsClass(const struct FName& KeyName, class UClass* ClassValue)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.SetValueAsClass");
UBlackboardComponent_SetValueAsClass_Params params {};
params.KeyName = KeyName;
params.ClassValue = ClassValue;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6D770
// Name -> Function AIModule.BlackboardComponent.SetValueAsBool
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool BoolValue (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBlackboardComponent::SetValueAsBool(const struct FName& KeyName, bool BoolValue)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.SetValueAsBool");
UBlackboardComponent_SetValueAsBool_Params params {};
params.KeyName = KeyName;
params.BoolValue = BoolValue;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F6D6D0
// Name -> Function AIModule.BlackboardComponent.IsVectorValueSet
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBlackboardComponent::IsVectorValueSet(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.IsVectorValueSet");
UBlackboardComponent_IsVectorValueSet_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D560
// Name -> Function AIModule.BlackboardComponent.GetValueAsVector
// Flags -> (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FVector UBlackboardComponent::GetValueAsVector(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetValueAsVector");
UBlackboardComponent_GetValueAsVector_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D480
// Name -> Function AIModule.BlackboardComponent.GetValueAsString
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FString ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FString UBlackboardComponent::GetValueAsString(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetValueAsString");
UBlackboardComponent_GetValueAsString_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D3D0
// Name -> Function AIModule.BlackboardComponent.GetValueAsRotator
// Flags -> (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FRotator ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
struct FRotator UBlackboardComponent::GetValueAsRotator(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetValueAsRotator");
UBlackboardComponent_GetValueAsRotator_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D330
// Name -> Function AIModule.BlackboardComponent.GetValueAsObject
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UObject* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UObject* UBlackboardComponent::GetValueAsObject(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetValueAsObject");
UBlackboardComponent_GetValueAsObject_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D290
// Name -> Function AIModule.BlackboardComponent.GetValueAsName
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FName ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FName UBlackboardComponent::GetValueAsName(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetValueAsName");
UBlackboardComponent_GetValueAsName_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D1F0
// Name -> Function AIModule.BlackboardComponent.GetValueAsInt
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int UBlackboardComponent::GetValueAsInt(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetValueAsInt");
UBlackboardComponent_GetValueAsInt_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D150
// Name -> Function AIModule.BlackboardComponent.GetValueAsFloat
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float UBlackboardComponent::GetValueAsFloat(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetValueAsFloat");
UBlackboardComponent_GetValueAsFloat_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D0B0
// Name -> Function AIModule.BlackboardComponent.GetValueAsEnum
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// unsigned char ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UBlackboardComponent::GetValueAsEnum(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetValueAsEnum");
UBlackboardComponent_GetValueAsEnum_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D010
// Name -> Function AIModule.BlackboardComponent.GetValueAsClass
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UClass* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UClass* UBlackboardComponent::GetValueAsClass(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetValueAsClass");
UBlackboardComponent_GetValueAsClass_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6CF70
// Name -> Function AIModule.BlackboardComponent.GetValueAsBool
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBlackboardComponent::GetValueAsBool(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetValueAsBool");
UBlackboardComponent_GetValueAsBool_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6CE80
// Name -> Function AIModule.BlackboardComponent.GetRotationFromEntry
// Flags -> (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FRotator ResultRotation (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBlackboardComponent::GetRotationFromEntry(const struct FName& KeyName, struct FRotator* ResultRotation)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetRotationFromEntry");
UBlackboardComponent_GetRotationFromEntry_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (ResultRotation != nullptr)
*ResultRotation = params.ResultRotation;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6CD90
// Name -> Function AIModule.BlackboardComponent.GetLocationFromEntry
// Flags -> (Final, Native, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector ResultLocation (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBlackboardComponent::GetLocationFromEntry(const struct FName& KeyName, struct FVector* ResultLocation)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.GetLocationFromEntry");
UBlackboardComponent_GetLocationFromEntry_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (ResultLocation != nullptr)
*ResultLocation = params.ResultLocation;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6CD00
// Name -> Function AIModule.BlackboardComponent.ClearValue
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable)
// Parameters:
// struct FName KeyName (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBlackboardComponent::ClearValue(const struct FName& KeyName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BlackboardComponent.ClearValue");
UBlackboardComponent_ClearValue_Params params {};
params.KeyName = KeyName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UBlackboardComponent::AfterRead()
{
UActorComponent::AfterRead();
READ_PTR_FULL(BrainComp, UBrainComponent);
READ_PTR_FULL(BlackboardAsset, UBlackboardData);
}
void UBlackboardComponent::BeforeDelete()
{
UActorComponent::BeforeDelete();
DELE_PTR_FULL(BrainComp);
DELE_PTR_FULL(BlackboardAsset);
}
void UBlackboardData::AfterRead()
{
UDataAsset::AfterRead();
READ_PTR_FULL(Parent, UBlackboardData);
}
void UBlackboardData::BeforeDelete()
{
UDataAsset::BeforeDelete();
DELE_PTR_FULL(Parent);
}
void UBlackboardKeyType::AfterRead()
{
UObject::AfterRead();
}
void UBlackboardKeyType::BeforeDelete()
{
UObject::BeforeDelete();
}
void UBlackboardKeyType_Bool::AfterRead()
{
UBlackboardKeyType::AfterRead();
}
void UBlackboardKeyType_Bool::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
}
void UBlackboardKeyType_Class::AfterRead()
{
UBlackboardKeyType::AfterRead();
READ_PTR_FULL(BaseClass, UClass);
}
void UBlackboardKeyType_Class::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
DELE_PTR_FULL(BaseClass);
}
void UBlackboardKeyType_Enum::AfterRead()
{
UBlackboardKeyType::AfterRead();
READ_PTR_FULL(EnumType, UEnum);
}
void UBlackboardKeyType_Enum::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
DELE_PTR_FULL(EnumType);
}
void UBlackboardKeyType_Float::AfterRead()
{
UBlackboardKeyType::AfterRead();
}
void UBlackboardKeyType_Float::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
}
void UBlackboardKeyType_Int::AfterRead()
{
UBlackboardKeyType::AfterRead();
}
void UBlackboardKeyType_Int::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
}
void UBlackboardKeyType_Name::AfterRead()
{
UBlackboardKeyType::AfterRead();
}
void UBlackboardKeyType_Name::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
}
void UBlackboardKeyType_NativeEnum::AfterRead()
{
UBlackboardKeyType::AfterRead();
READ_PTR_FULL(EnumType, UEnum);
}
void UBlackboardKeyType_NativeEnum::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
DELE_PTR_FULL(EnumType);
}
void UBlackboardKeyType_Object::AfterRead()
{
UBlackboardKeyType::AfterRead();
READ_PTR_FULL(BaseClass, UClass);
}
void UBlackboardKeyType_Object::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
DELE_PTR_FULL(BaseClass);
}
void UBlackboardKeyType_Rotator::AfterRead()
{
UBlackboardKeyType::AfterRead();
}
void UBlackboardKeyType_Rotator::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
}
void UBlackboardKeyType_String::AfterRead()
{
UBlackboardKeyType::AfterRead();
}
void UBlackboardKeyType_String::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
}
void UBlackboardKeyType_Vector::AfterRead()
{
UBlackboardKeyType::AfterRead();
}
void UBlackboardKeyType_Vector::BeforeDelete()
{
UBlackboardKeyType::BeforeDelete();
}
void UBTNode::AfterRead()
{
UObject::AfterRead();
READ_PTR_FULL(TreeAsset, UBehaviorTree);
READ_PTR_FULL(ParentNode, UBTCompositeNode);
}
void UBTNode::BeforeDelete()
{
UObject::BeforeDelete();
DELE_PTR_FULL(TreeAsset);
DELE_PTR_FULL(ParentNode);
}
void UBTAuxiliaryNode::AfterRead()
{
UBTNode::AfterRead();
}
void UBTAuxiliaryNode::BeforeDelete()
{
UBTNode::BeforeDelete();
}
void UBTCompositeNode::AfterRead()
{
UBTNode::AfterRead();
}
void UBTCompositeNode::BeforeDelete()
{
UBTNode::BeforeDelete();
}
void UBTComposite_Selector::AfterRead()
{
UBTCompositeNode::AfterRead();
}
void UBTComposite_Selector::BeforeDelete()
{
UBTCompositeNode::BeforeDelete();
}
void UBTComposite_Sequence::AfterRead()
{
UBTCompositeNode::AfterRead();
}
void UBTComposite_Sequence::BeforeDelete()
{
UBTCompositeNode::BeforeDelete();
}
void UBTComposite_SimpleParallel::AfterRead()
{
UBTCompositeNode::AfterRead();
}
void UBTComposite_SimpleParallel::BeforeDelete()
{
UBTCompositeNode::BeforeDelete();
}
void UBTDecorator::AfterRead()
{
UBTAuxiliaryNode::AfterRead();
}
void UBTDecorator::BeforeDelete()
{
UBTAuxiliaryNode::BeforeDelete();
}
void UBTDecorator_BlackboardBase::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_BlackboardBase::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_Blackboard::AfterRead()
{
UBTDecorator_BlackboardBase::AfterRead();
}
void UBTDecorator_Blackboard::BeforeDelete()
{
UBTDecorator_BlackboardBase::BeforeDelete();
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.ReceiveTickAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTDecorator_BlueprintBase::ReceiveTickAI(class AAIController* OwnerController, class APawn* ControlledPawn, float DeltaSeconds)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.ReceiveTickAI");
UBTDecorator_BlueprintBase_ReceiveTickAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.ReceiveTick
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTDecorator_BlueprintBase::ReceiveTick(class AActor* OwnerActor, float DeltaSeconds)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.ReceiveTick");
UBTDecorator_BlueprintBase_ReceiveTick_Params params {};
params.OwnerActor = OwnerActor;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.ReceiveObserverDeactivatedAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTDecorator_BlueprintBase::ReceiveObserverDeactivatedAI(class AAIController* OwnerController, class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.ReceiveObserverDeactivatedAI");
UBTDecorator_BlueprintBase_ReceiveObserverDeactivatedAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.ReceiveObserverDeactivated
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTDecorator_BlueprintBase::ReceiveObserverDeactivated(class AActor* OwnerActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.ReceiveObserverDeactivated");
UBTDecorator_BlueprintBase_ReceiveObserverDeactivated_Params params {};
params.OwnerActor = OwnerActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.ReceiveObserverActivatedAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTDecorator_BlueprintBase::ReceiveObserverActivatedAI(class AAIController* OwnerController, class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.ReceiveObserverActivatedAI");
UBTDecorator_BlueprintBase_ReceiveObserverActivatedAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.ReceiveObserverActivated
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTDecorator_BlueprintBase::ReceiveObserverActivated(class AActor* OwnerActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.ReceiveObserverActivated");
UBTDecorator_BlueprintBase_ReceiveObserverActivated_Params params {};
params.OwnerActor = OwnerActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.ReceiveExecutionStartAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTDecorator_BlueprintBase::ReceiveExecutionStartAI(class AAIController* OwnerController, class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.ReceiveExecutionStartAI");
UBTDecorator_BlueprintBase_ReceiveExecutionStartAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.ReceiveExecutionStart
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTDecorator_BlueprintBase::ReceiveExecutionStart(class AActor* OwnerActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.ReceiveExecutionStart");
UBTDecorator_BlueprintBase_ReceiveExecutionStart_Params params {};
params.OwnerActor = OwnerActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.ReceiveExecutionFinishAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EBTNodeResult> NodeResult (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTDecorator_BlueprintBase::ReceiveExecutionFinishAI(class AAIController* OwnerController, class APawn* ControlledPawn, TEnumAsByte<AIModule_EBTNodeResult> NodeResult)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.ReceiveExecutionFinishAI");
UBTDecorator_BlueprintBase_ReceiveExecutionFinishAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
params.NodeResult = NodeResult;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.ReceiveExecutionFinish
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EBTNodeResult> NodeResult (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTDecorator_BlueprintBase::ReceiveExecutionFinish(class AActor* OwnerActor, TEnumAsByte<AIModule_EBTNodeResult> NodeResult)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.ReceiveExecutionFinish");
UBTDecorator_BlueprintBase_ReceiveExecutionFinish_Params params {};
params.OwnerActor = OwnerActor;
params.NodeResult = NodeResult;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.PerformConditionCheckAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBTDecorator_BlueprintBase::PerformConditionCheckAI(class AAIController* OwnerController, class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.PerformConditionCheckAI");
UBTDecorator_BlueprintBase_PerformConditionCheckAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTDecorator_BlueprintBase.PerformConditionCheck
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBTDecorator_BlueprintBase::PerformConditionCheck(class AActor* OwnerActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.PerformConditionCheck");
UBTDecorator_BlueprintBase_PerformConditionCheck_Params params {};
params.OwnerActor = OwnerActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D640
// Name -> Function AIModule.BTDecorator_BlueprintBase.IsDecoratorObserverActive
// Flags -> (Final, Native, Protected, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBTDecorator_BlueprintBase::IsDecoratorObserverActive()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.IsDecoratorObserverActive");
UBTDecorator_BlueprintBase_IsDecoratorObserverActive_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F6D610
// Name -> Function AIModule.BTDecorator_BlueprintBase.IsDecoratorExecutionActive
// Flags -> (Final, Native, Protected, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBTDecorator_BlueprintBase::IsDecoratorExecutionActive()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTDecorator_BlueprintBase.IsDecoratorExecutionActive");
UBTDecorator_BlueprintBase_IsDecoratorExecutionActive_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UBTDecorator_BlueprintBase::AfterRead()
{
UBTDecorator::AfterRead();
READ_PTR_FULL(AIOwner, AAIController);
READ_PTR_FULL(ActorOwner, AActor);
}
void UBTDecorator_BlueprintBase::BeforeDelete()
{
UBTDecorator::BeforeDelete();
DELE_PTR_FULL(AIOwner);
DELE_PTR_FULL(ActorOwner);
}
void UBTDecorator_CheckGameplayTagsOnActor::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_CheckGameplayTagsOnActor::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_CompareBBEntries::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_CompareBBEntries::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_ConditionalLoop::AfterRead()
{
UBTDecorator_Blackboard::AfterRead();
}
void UBTDecorator_ConditionalLoop::BeforeDelete()
{
UBTDecorator_Blackboard::BeforeDelete();
}
void UBTDecorator_ConeCheck::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_ConeCheck::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_Cooldown::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_Cooldown::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_DoesPathExist::AfterRead()
{
UBTDecorator::AfterRead();
READ_PTR_FULL(FilterClass, UClass);
}
void UBTDecorator_DoesPathExist::BeforeDelete()
{
UBTDecorator::BeforeDelete();
DELE_PTR_FULL(FilterClass);
}
void UBTDecorator_ForceSuccess::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_ForceSuccess::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_IsAtLocation::AfterRead()
{
UBTDecorator_BlackboardBase::AfterRead();
}
void UBTDecorator_IsAtLocation::BeforeDelete()
{
UBTDecorator_BlackboardBase::BeforeDelete();
}
void UBTDecorator_IsBBEntryOfClass::AfterRead()
{
UBTDecorator_BlackboardBase::AfterRead();
READ_PTR_FULL(TestClass, UClass);
}
void UBTDecorator_IsBBEntryOfClass::BeforeDelete()
{
UBTDecorator_BlackboardBase::BeforeDelete();
DELE_PTR_FULL(TestClass);
}
void UBTDecorator_KeepInCone::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_KeepInCone::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_Loop::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_Loop::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_ReachedMoveGoal::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_ReachedMoveGoal::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_SetTagCooldown::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_SetTagCooldown::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_TagCooldown::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_TagCooldown::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
void UBTDecorator_TimeLimit::AfterRead()
{
UBTDecorator::AfterRead();
}
void UBTDecorator_TimeLimit::BeforeDelete()
{
UBTDecorator::BeforeDelete();
}
// Function:
// Offset -> 0x01D61D00
// Name -> Function AIModule.BTFunctionLibrary.StopUsingExternalEvent
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_StopUsingExternalEvent(class UBTNode* NodeOwner)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.StopUsingExternalEvent");
UBTFunctionLibrary_StopUsingExternalEvent_Params params {};
params.NodeOwner = NodeOwner;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01DF0FA0
// Name -> Function AIModule.BTFunctionLibrary.StartUsingExternalEvent
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* OwningActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_StartUsingExternalEvent(class UBTNode* NodeOwner, class AActor* OwningActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.StartUsingExternalEvent");
UBTFunctionLibrary_StartUsingExternalEvent_Params params {};
params.NodeOwner = NodeOwner;
params.OwningActor = OwningActor;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F72460
// Name -> Function AIModule.BTFunctionLibrary.SetBlackboardValueAsVector
// Flags -> (Final, Native, Static, Public, HasOutParms, HasDefaults, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// struct FVector Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_SetBlackboardValueAsVector(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key, const struct FVector& Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.SetBlackboardValueAsVector");
UBTFunctionLibrary_SetBlackboardValueAsVector_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F722E0
// Name -> Function AIModule.BTFunctionLibrary.SetBlackboardValueAsString
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// struct FString Value (Parm, ZeroConstructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_SetBlackboardValueAsString(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key, const struct FString& Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.SetBlackboardValueAsString");
UBTFunctionLibrary_SetBlackboardValueAsString_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F721A0
// Name -> Function AIModule.BTFunctionLibrary.SetBlackboardValueAsRotator
// Flags -> (Final, Native, Static, Public, HasOutParms, HasDefaults, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// struct FRotator Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_SetBlackboardValueAsRotator(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key, const struct FRotator& Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.SetBlackboardValueAsRotator");
UBTFunctionLibrary_SetBlackboardValueAsRotator_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F72060
// Name -> Function AIModule.BTFunctionLibrary.SetBlackboardValueAsObject
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// class UObject* Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_SetBlackboardValueAsObject(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key, class UObject* Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.SetBlackboardValueAsObject");
UBTFunctionLibrary_SetBlackboardValueAsObject_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F71F20
// Name -> Function AIModule.BTFunctionLibrary.SetBlackboardValueAsName
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// struct FName Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_SetBlackboardValueAsName(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key, const struct FName& Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.SetBlackboardValueAsName");
UBTFunctionLibrary_SetBlackboardValueAsName_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F71DE0
// Name -> Function AIModule.BTFunctionLibrary.SetBlackboardValueAsInt
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// int Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_SetBlackboardValueAsInt(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key, int Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.SetBlackboardValueAsInt");
UBTFunctionLibrary_SetBlackboardValueAsInt_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F71CA0
// Name -> Function AIModule.BTFunctionLibrary.SetBlackboardValueAsFloat
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// float Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_SetBlackboardValueAsFloat(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key, float Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.SetBlackboardValueAsFloat");
UBTFunctionLibrary_SetBlackboardValueAsFloat_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F71B60
// Name -> Function AIModule.BTFunctionLibrary.SetBlackboardValueAsEnum
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// unsigned char Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_SetBlackboardValueAsEnum(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key, unsigned char Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.SetBlackboardValueAsEnum");
UBTFunctionLibrary_SetBlackboardValueAsEnum_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F71A20
// Name -> Function AIModule.BTFunctionLibrary.SetBlackboardValueAsClass
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// class UClass* Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_SetBlackboardValueAsClass(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key, class UClass* Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.SetBlackboardValueAsClass");
UBTFunctionLibrary_SetBlackboardValueAsClass_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F718E0
// Name -> Function AIModule.BTFunctionLibrary.SetBlackboardValueAsBool
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// bool Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_SetBlackboardValueAsBool(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key, bool Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.SetBlackboardValueAsBool");
UBTFunctionLibrary_SetBlackboardValueAsBool_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F717D0
// Name -> Function AIModule.BTFunctionLibrary.GetOwnersBlackboard
// Flags -> (Final, Native, Static, Public, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UBlackboardComponent* ReturnValue (ExportObject, Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UBlackboardComponent* UBTFunctionLibrary::STATIC_GetOwnersBlackboard(class UBTNode* NodeOwner)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetOwnersBlackboard");
UBTFunctionLibrary_GetOwnersBlackboard_Params params {};
params.NodeOwner = NodeOwner;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F71750
// Name -> Function AIModule.BTFunctionLibrary.GetOwnerComponent
// Flags -> (Final, Native, Static, Public, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UBehaviorTreeComponent* ReturnValue (ExportObject, Parm, OutParm, ZeroConstructor, ReturnParm, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UBehaviorTreeComponent* UBTFunctionLibrary::STATIC_GetOwnerComponent(class UBTNode* NodeOwner)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetOwnerComponent");
UBTFunctionLibrary_GetOwnerComponent_Params params {};
params.NodeOwner = NodeOwner;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F71640
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsVector
// Flags -> (Final, Native, Static, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// struct FVector ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FVector UBTFunctionLibrary::STATIC_GetBlackboardValueAsVector(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsVector");
UBTFunctionLibrary_GetBlackboardValueAsVector_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F71500
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsString
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// struct FString ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FString UBTFunctionLibrary::STATIC_GetBlackboardValueAsString(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsString");
UBTFunctionLibrary_GetBlackboardValueAsString_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F713F0
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsRotator
// Flags -> (Final, Native, Static, Public, HasOutParms, HasDefaults, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// struct FRotator ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, NativeAccessSpecifierPublic)
struct FRotator UBTFunctionLibrary::STATIC_GetBlackboardValueAsRotator(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsRotator");
UBTFunctionLibrary_GetBlackboardValueAsRotator_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F712F0
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsObject
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// class UObject* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UObject* UBTFunctionLibrary::STATIC_GetBlackboardValueAsObject(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsObject");
UBTFunctionLibrary_GetBlackboardValueAsObject_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F711F0
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsName
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// struct FName ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
struct FName UBTFunctionLibrary::STATIC_GetBlackboardValueAsName(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsName");
UBTFunctionLibrary_GetBlackboardValueAsName_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F710F0
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsInt
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// int ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int UBTFunctionLibrary::STATIC_GetBlackboardValueAsInt(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsInt");
UBTFunctionLibrary_GetBlackboardValueAsInt_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F70FF0
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsFloat
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float UBTFunctionLibrary::STATIC_GetBlackboardValueAsFloat(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsFloat");
UBTFunctionLibrary_GetBlackboardValueAsFloat_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F70EF0
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsEnum
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// unsigned char ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UBTFunctionLibrary::STATIC_GetBlackboardValueAsEnum(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsEnum");
UBTFunctionLibrary_GetBlackboardValueAsEnum_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F70DF0
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsClass
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// class UClass* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UClass* UBTFunctionLibrary::STATIC_GetBlackboardValueAsClass(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsClass");
UBTFunctionLibrary_GetBlackboardValueAsClass_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F70CF0
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsBool
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBTFunctionLibrary::STATIC_GetBlackboardValueAsBool(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsBool");
UBTFunctionLibrary_GetBlackboardValueAsBool_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F70BF0
// Name -> Function AIModule.BTFunctionLibrary.GetBlackboardValueAsActor
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable, BlueprintPure)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
// class AActor* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class AActor* UBTFunctionLibrary::STATIC_GetBlackboardValueAsActor(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.GetBlackboardValueAsActor");
UBTFunctionLibrary_GetBlackboardValueAsActor_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F70A50
// Name -> Function AIModule.BTFunctionLibrary.ClearBlackboardValueAsVector
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_ClearBlackboardValueAsVector(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.ClearBlackboardValueAsVector");
UBTFunctionLibrary_ClearBlackboardValueAsVector_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F70A50
// Name -> Function AIModule.BTFunctionLibrary.ClearBlackboardValue
// Flags -> (Final, Native, Static, Public, HasOutParms, BlueprintCallable)
// Parameters:
// class UBTNode* NodeOwner (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FBlackboardKeySelector Key (ConstParm, Parm, OutParm, ReferenceParm, NativeAccessSpecifierPublic)
void UBTFunctionLibrary::STATIC_ClearBlackboardValue(class UBTNode* NodeOwner, const struct FBlackboardKeySelector& Key)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTFunctionLibrary.ClearBlackboardValue");
UBTFunctionLibrary_ClearBlackboardValue_Params params {};
params.NodeOwner = NodeOwner;
params.Key = Key;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UBTFunctionLibrary::AfterRead()
{
UBlueprintFunctionLibrary::AfterRead();
}
void UBTFunctionLibrary::BeforeDelete()
{
UBlueprintFunctionLibrary::BeforeDelete();
}
void UBTService::AfterRead()
{
UBTAuxiliaryNode::AfterRead();
}
void UBTService::BeforeDelete()
{
UBTAuxiliaryNode::BeforeDelete();
}
void UBTService_BlackboardBase::AfterRead()
{
UBTService::AfterRead();
}
void UBTService_BlackboardBase::BeforeDelete()
{
UBTService::BeforeDelete();
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTService_BlueprintBase.ReceiveTickAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTService_BlueprintBase::ReceiveTickAI(class AAIController* OwnerController, class APawn* ControlledPawn, float DeltaSeconds)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTService_BlueprintBase.ReceiveTickAI");
UBTService_BlueprintBase_ReceiveTickAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTService_BlueprintBase.ReceiveTick
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTService_BlueprintBase::ReceiveTick(class AActor* OwnerActor, float DeltaSeconds)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTService_BlueprintBase.ReceiveTick");
UBTService_BlueprintBase_ReceiveTick_Params params {};
params.OwnerActor = OwnerActor;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTService_BlueprintBase.ReceiveSearchStartAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTService_BlueprintBase::ReceiveSearchStartAI(class AAIController* OwnerController, class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTService_BlueprintBase.ReceiveSearchStartAI");
UBTService_BlueprintBase_ReceiveSearchStartAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTService_BlueprintBase.ReceiveSearchStart
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTService_BlueprintBase::ReceiveSearchStart(class AActor* OwnerActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTService_BlueprintBase.ReceiveSearchStart");
UBTService_BlueprintBase_ReceiveSearchStart_Params params {};
params.OwnerActor = OwnerActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTService_BlueprintBase.ReceiveDeactivationAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTService_BlueprintBase::ReceiveDeactivationAI(class AAIController* OwnerController, class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTService_BlueprintBase.ReceiveDeactivationAI");
UBTService_BlueprintBase_ReceiveDeactivationAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTService_BlueprintBase.ReceiveDeactivation
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTService_BlueprintBase::ReceiveDeactivation(class AActor* OwnerActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTService_BlueprintBase.ReceiveDeactivation");
UBTService_BlueprintBase_ReceiveDeactivation_Params params {};
params.OwnerActor = OwnerActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTService_BlueprintBase.ReceiveActivationAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTService_BlueprintBase::ReceiveActivationAI(class AAIController* OwnerController, class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTService_BlueprintBase.ReceiveActivationAI");
UBTService_BlueprintBase_ReceiveActivationAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTService_BlueprintBase.ReceiveActivation
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTService_BlueprintBase::ReceiveActivation(class AActor* OwnerActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTService_BlueprintBase.ReceiveActivation");
UBTService_BlueprintBase_ReceiveActivation_Params params {};
params.OwnerActor = OwnerActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F71850
// Name -> Function AIModule.BTService_BlueprintBase.IsServiceActive
// Flags -> (Final, Native, Protected, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBTService_BlueprintBase::IsServiceActive()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTService_BlueprintBase.IsServiceActive");
UBTService_BlueprintBase_IsServiceActive_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UBTService_BlueprintBase::AfterRead()
{
UBTService::AfterRead();
READ_PTR_FULL(AIOwner, AAIController);
READ_PTR_FULL(ActorOwner, AActor);
}
void UBTService_BlueprintBase::BeforeDelete()
{
UBTService::BeforeDelete();
DELE_PTR_FULL(AIOwner);
DELE_PTR_FULL(ActorOwner);
}
void UBTService_DefaultFocus::AfterRead()
{
UBTService_BlackboardBase::AfterRead();
}
void UBTService_DefaultFocus::BeforeDelete()
{
UBTService_BlackboardBase::BeforeDelete();
}
void UBTService_RunEQS::AfterRead()
{
UBTService_BlackboardBase::AfterRead();
}
void UBTService_RunEQS::BeforeDelete()
{
UBTService_BlackboardBase::BeforeDelete();
}
void UBTTaskNode::AfterRead()
{
UBTNode::AfterRead();
}
void UBTTaskNode::BeforeDelete()
{
UBTNode::BeforeDelete();
}
void UBTTask_BlackboardBase::AfterRead()
{
UBTTaskNode::AfterRead();
}
void UBTTask_BlackboardBase::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
}
// Function:
// Offset -> 0x01F72620
// Name -> Function AIModule.BTTask_BlueprintBase.SetFinishOnMessageWithId
// Flags -> (Final, Native, Protected, BlueprintCallable)
// Parameters:
// struct FName MessageName (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// int RequestID (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTTask_BlueprintBase::SetFinishOnMessageWithId(const struct FName& MessageName, int RequestID)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.SetFinishOnMessageWithId");
UBTTask_BlueprintBase_SetFinishOnMessageWithId_Params params {};
params.MessageName = MessageName;
params.RequestID = RequestID;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F725A0
// Name -> Function AIModule.BTTask_BlueprintBase.SetFinishOnMessage
// Flags -> (Final, Native, Protected, BlueprintCallable)
// Parameters:
// struct FName MessageName (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTTask_BlueprintBase::SetFinishOnMessage(const struct FName& MessageName)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.SetFinishOnMessage");
UBTTask_BlueprintBase_SetFinishOnMessage_Params params {};
params.MessageName = MessageName;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTTask_BlueprintBase.ReceiveTickAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTTask_BlueprintBase::ReceiveTickAI(class AAIController* OwnerController, class APawn* ControlledPawn, float DeltaSeconds)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.ReceiveTickAI");
UBTTask_BlueprintBase_ReceiveTickAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTTask_BlueprintBase.ReceiveTick
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float DeltaSeconds (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTTask_BlueprintBase::ReceiveTick(class AActor* OwnerActor, float DeltaSeconds)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.ReceiveTick");
UBTTask_BlueprintBase_ReceiveTick_Params params {};
params.OwnerActor = OwnerActor;
params.DeltaSeconds = DeltaSeconds;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTTask_BlueprintBase.ReceiveExecuteAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTTask_BlueprintBase::ReceiveExecuteAI(class AAIController* OwnerController, class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.ReceiveExecuteAI");
UBTTask_BlueprintBase_ReceiveExecuteAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTTask_BlueprintBase.ReceiveExecute
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTTask_BlueprintBase::ReceiveExecute(class AActor* OwnerActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.ReceiveExecute");
UBTTask_BlueprintBase_ReceiveExecute_Params params {};
params.OwnerActor = OwnerActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTTask_BlueprintBase.ReceiveAbortAI
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AAIController* OwnerController (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class APawn* ControlledPawn (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTTask_BlueprintBase::ReceiveAbortAI(class AAIController* OwnerController, class APawn* ControlledPawn)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.ReceiveAbortAI");
UBTTask_BlueprintBase_ReceiveAbortAI_Params params {};
params.OwnerController = OwnerController;
params.ControlledPawn = ControlledPawn;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.BTTask_BlueprintBase.ReceiveAbort
// Flags -> (Event, Protected, BlueprintEvent)
// Parameters:
// class AActor* OwnerActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTTask_BlueprintBase::ReceiveAbort(class AActor* OwnerActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.ReceiveAbort");
UBTTask_BlueprintBase_ReceiveAbort_Params params {};
params.OwnerActor = OwnerActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F718B0
// Name -> Function AIModule.BTTask_BlueprintBase.IsTaskExecuting
// Flags -> (Final, Native, Protected, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBTTask_BlueprintBase::IsTaskExecuting()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.IsTaskExecuting");
UBTTask_BlueprintBase_IsTaskExecuting_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F71880
// Name -> Function AIModule.BTTask_BlueprintBase.IsTaskAborting
// Flags -> (Final, Native, Protected, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UBTTask_BlueprintBase::IsTaskAborting()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.IsTaskAborting");
UBTTask_BlueprintBase_IsTaskAborting_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F70B60
// Name -> Function AIModule.BTTask_BlueprintBase.FinishExecute
// Flags -> (Final, Native, Protected, BlueprintCallable)
// Parameters:
// bool bSuccess (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UBTTask_BlueprintBase::FinishExecute(bool bSuccess)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.FinishExecute");
UBTTask_BlueprintBase_FinishExecute_Params params {};
params.bSuccess = bSuccess;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F70B40
// Name -> Function AIModule.BTTask_BlueprintBase.FinishAbort
// Flags -> (Final, Native, Protected, BlueprintCallable)
void UBTTask_BlueprintBase::FinishAbort()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.BTTask_BlueprintBase.FinishAbort");
UBTTask_BlueprintBase_FinishAbort_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UBTTask_BlueprintBase::AfterRead()
{
UBTTaskNode::AfterRead();
READ_PTR_FULL(AIOwner, AAIController);
READ_PTR_FULL(ActorOwner, AActor);
}
void UBTTask_BlueprintBase::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
DELE_PTR_FULL(AIOwner);
DELE_PTR_FULL(ActorOwner);
}
void UBTTask_FinishWithResult::AfterRead()
{
UBTTaskNode::AfterRead();
}
void UBTTask_FinishWithResult::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
}
void UBTTask_GameplayTaskBase::AfterRead()
{
UBTTaskNode::AfterRead();
}
void UBTTask_GameplayTaskBase::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
}
void UBTTask_MakeNoise::AfterRead()
{
UBTTaskNode::AfterRead();
}
void UBTTask_MakeNoise::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
}
void UBTTask_MoveTo::AfterRead()
{
UBTTask_BlackboardBase::AfterRead();
READ_PTR_FULL(FilterClass, UClass);
}
void UBTTask_MoveTo::BeforeDelete()
{
UBTTask_BlackboardBase::BeforeDelete();
DELE_PTR_FULL(FilterClass);
}
void UBTTask_MoveDirectlyToward::AfterRead()
{
UBTTask_MoveTo::AfterRead();
}
void UBTTask_MoveDirectlyToward::BeforeDelete()
{
UBTTask_MoveTo::BeforeDelete();
}
void UBTTask_PawnActionBase::AfterRead()
{
UBTTaskNode::AfterRead();
}
void UBTTask_PawnActionBase::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
}
void UBTTask_PlayAnimation::AfterRead()
{
UBTTaskNode::AfterRead();
READ_PTR_FULL(AnimationToPlay, UAnimationAsset);
READ_PTR_FULL(MyOwnerComp, UBehaviorTreeComponent);
READ_PTR_FULL(CachedSkelMesh, USkeletalMeshComponent);
}
void UBTTask_PlayAnimation::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
DELE_PTR_FULL(AnimationToPlay);
DELE_PTR_FULL(MyOwnerComp);
DELE_PTR_FULL(CachedSkelMesh);
}
void UBTTask_PlaySound::AfterRead()
{
UBTTaskNode::AfterRead();
READ_PTR_FULL(SoundToPlay, USoundCue);
}
void UBTTask_PlaySound::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
DELE_PTR_FULL(SoundToPlay);
}
void UBTTask_PushPawnAction::AfterRead()
{
UBTTask_PawnActionBase::AfterRead();
READ_PTR_FULL(Action, UPawnAction);
}
void UBTTask_PushPawnAction::BeforeDelete()
{
UBTTask_PawnActionBase::BeforeDelete();
DELE_PTR_FULL(Action);
}
void UBTTask_RotateToFaceBBEntry::AfterRead()
{
UBTTask_BlackboardBase::AfterRead();
}
void UBTTask_RotateToFaceBBEntry::BeforeDelete()
{
UBTTask_BlackboardBase::BeforeDelete();
}
void UBTTask_RunBehavior::AfterRead()
{
UBTTaskNode::AfterRead();
READ_PTR_FULL(BehaviorAsset, UBehaviorTree);
}
void UBTTask_RunBehavior::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
DELE_PTR_FULL(BehaviorAsset);
}
void UBTTask_RunBehaviorDynamic::AfterRead()
{
UBTTaskNode::AfterRead();
READ_PTR_FULL(DefaultBehaviorAsset, UBehaviorTree);
READ_PTR_FULL(BehaviorAsset, UBehaviorTree);
}
void UBTTask_RunBehaviorDynamic::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
DELE_PTR_FULL(DefaultBehaviorAsset);
DELE_PTR_FULL(BehaviorAsset);
}
void UBTTask_RunEQSQuery::AfterRead()
{
UBTTask_BlackboardBase::AfterRead();
READ_PTR_FULL(QueryTemplate, UEnvQuery);
}
void UBTTask_RunEQSQuery::BeforeDelete()
{
UBTTask_BlackboardBase::BeforeDelete();
DELE_PTR_FULL(QueryTemplate);
}
void UBTTask_SetTagCooldown::AfterRead()
{
UBTTaskNode::AfterRead();
}
void UBTTask_SetTagCooldown::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
}
void UBTTask_Wait::AfterRead()
{
UBTTaskNode::AfterRead();
}
void UBTTask_Wait::BeforeDelete()
{
UBTTaskNode::BeforeDelete();
}
void UBTTask_WaitBlackboardTime::AfterRead()
{
UBTTask_Wait::AfterRead();
}
void UBTTask_WaitBlackboardTime::BeforeDelete()
{
UBTTask_Wait::BeforeDelete();
}
void UCrowdAgentInterface::AfterRead()
{
UInterface::AfterRead();
}
void UCrowdAgentInterface::BeforeDelete()
{
UInterface::BeforeDelete();
}
// Function:
// Offset -> 0x01F75FB0
// Name -> Function AIModule.CrowdFollowingComponent.SuspendCrowdSteering
// Flags -> (Native, Public, BlueprintCallable)
// Parameters:
// bool bSuspend (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UCrowdFollowingComponent::SuspendCrowdSteering(bool bSuspend)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.CrowdFollowingComponent.SuspendCrowdSteering");
UCrowdFollowingComponent_SuspendCrowdSteering_Params params {};
params.bSuspend = bSuspend;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UCrowdFollowingComponent::AfterRead()
{
UPathFollowingComponent::AfterRead();
READ_PTR_FULL(CharacterMovement, UCharacterMovementComponent);
}
void UCrowdFollowingComponent::BeforeDelete()
{
UPathFollowingComponent::BeforeDelete();
DELE_PTR_FULL(CharacterMovement);
}
void UCrowdManager::AfterRead()
{
UCrowdManagerBase::AfterRead();
READ_PTR_FULL(MyNavData, ANavigationData);
}
void UCrowdManager::BeforeDelete()
{
UCrowdManagerBase::BeforeDelete();
DELE_PTR_FULL(MyNavData);
}
void ADetourCrowdAIController::AfterRead()
{
AAIController::AfterRead();
}
void ADetourCrowdAIController::BeforeDelete()
{
AAIController::BeforeDelete();
}
void UEnvQuery::AfterRead()
{
UDataAsset::AfterRead();
}
void UEnvQuery::BeforeDelete()
{
UDataAsset::BeforeDelete();
}
void UEnvQueryContext::AfterRead()
{
UObject::AfterRead();
}
void UEnvQueryContext::BeforeDelete()
{
UObject::BeforeDelete();
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.EnvQueryContext_BlueprintBase.ProvideSingleLocation
// Flags -> (Event, Public, HasOutParms, HasDefaults, BlueprintEvent, Const)
// Parameters:
// class UObject* QuerierObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* QuerierActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// struct FVector ResultingLocation (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UEnvQueryContext_BlueprintBase::ProvideSingleLocation(class UObject* QuerierObject, class AActor* QuerierActor, struct FVector* ResultingLocation)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryContext_BlueprintBase.ProvideSingleLocation");
UEnvQueryContext_BlueprintBase_ProvideSingleLocation_Params params {};
params.QuerierObject = QuerierObject;
params.QuerierActor = QuerierActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (ResultingLocation != nullptr)
*ResultingLocation = params.ResultingLocation;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.EnvQueryContext_BlueprintBase.ProvideSingleActor
// Flags -> (Event, Public, HasOutParms, BlueprintEvent, Const)
// Parameters:
// class UObject* QuerierObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* QuerierActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* ResultingActor (Parm, OutParm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UEnvQueryContext_BlueprintBase::ProvideSingleActor(class UObject* QuerierObject, class AActor* QuerierActor, class AActor** ResultingActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryContext_BlueprintBase.ProvideSingleActor");
UEnvQueryContext_BlueprintBase_ProvideSingleActor_Params params {};
params.QuerierObject = QuerierObject;
params.QuerierActor = QuerierActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (ResultingActor != nullptr)
*ResultingActor = params.ResultingActor;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.EnvQueryContext_BlueprintBase.ProvideLocationsSet
// Flags -> (Event, Public, HasOutParms, BlueprintEvent, Const)
// Parameters:
// class UObject* QuerierObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* QuerierActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TArray<struct FVector> ResultingLocationSet (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic)
void UEnvQueryContext_BlueprintBase::ProvideLocationsSet(class UObject* QuerierObject, class AActor* QuerierActor, TArray<struct FVector>* ResultingLocationSet)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryContext_BlueprintBase.ProvideLocationsSet");
UEnvQueryContext_BlueprintBase_ProvideLocationsSet_Params params {};
params.QuerierObject = QuerierObject;
params.QuerierActor = QuerierActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (ResultingLocationSet != nullptr)
*ResultingLocationSet = params.ResultingLocationSet;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.EnvQueryContext_BlueprintBase.ProvideActorsSet
// Flags -> (Event, Public, HasOutParms, BlueprintEvent, Const)
// Parameters:
// class UObject* QuerierObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class AActor* QuerierActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TArray<class AActor*> ResultingActorsSet (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic)
void UEnvQueryContext_BlueprintBase::ProvideActorsSet(class UObject* QuerierObject, class AActor* QuerierActor, TArray<class AActor*>* ResultingActorsSet)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryContext_BlueprintBase.ProvideActorsSet");
UEnvQueryContext_BlueprintBase_ProvideActorsSet_Params params {};
params.QuerierObject = QuerierObject;
params.QuerierActor = QuerierActor;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (ResultingActorsSet != nullptr)
*ResultingActorsSet = params.ResultingActorsSet;
}
void UEnvQueryContext_BlueprintBase::AfterRead()
{
UEnvQueryContext::AfterRead();
}
void UEnvQueryContext_BlueprintBase::BeforeDelete()
{
UEnvQueryContext::BeforeDelete();
}
void UEnvQueryContext_Item::AfterRead()
{
UEnvQueryContext::AfterRead();
}
void UEnvQueryContext_Item::BeforeDelete()
{
UEnvQueryContext::BeforeDelete();
}
void UEnvQueryContext_Querier::AfterRead()
{
UEnvQueryContext::AfterRead();
}
void UEnvQueryContext_Querier::BeforeDelete()
{
UEnvQueryContext::BeforeDelete();
}
void UEnvQueryDebugHelpers::AfterRead()
{
UObject::AfterRead();
}
void UEnvQueryDebugHelpers::BeforeDelete()
{
UObject::BeforeDelete();
}
void UEnvQueryGenerator::AfterRead()
{
UEnvQueryNode::AfterRead();
READ_PTR_FULL(itemType, UClass);
}
void UEnvQueryGenerator::BeforeDelete()
{
UEnvQueryNode::BeforeDelete();
DELE_PTR_FULL(itemType);
}
void UEnvQueryGenerator_ActorsOfClass::AfterRead()
{
UEnvQueryGenerator::AfterRead();
READ_PTR_FULL(SearchedActorClass, UClass);
READ_PTR_FULL(SearchCenter, UClass);
}
void UEnvQueryGenerator_ActorsOfClass::BeforeDelete()
{
UEnvQueryGenerator::BeforeDelete();
DELE_PTR_FULL(SearchedActorClass);
DELE_PTR_FULL(SearchCenter);
}
// Function:
// Offset -> 0x01F75C30
// Name -> Function AIModule.EnvQueryGenerator_BlueprintBase.GetQuerier
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// class UObject* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UObject* UEnvQueryGenerator_BlueprintBase::GetQuerier()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryGenerator_BlueprintBase.GetQuerier");
UEnvQueryGenerator_BlueprintBase_GetQuerier_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x00B73C40
// Name -> Function AIModule.EnvQueryGenerator_BlueprintBase.DoItemGeneration
// Flags -> (Event, Public, HasOutParms, BlueprintEvent, Const)
// Parameters:
// TArray<struct FVector> ContextLocations (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, NativeAccessSpecifierPublic)
void UEnvQueryGenerator_BlueprintBase::DoItemGeneration(TArray<struct FVector> ContextLocations)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryGenerator_BlueprintBase.DoItemGeneration");
UEnvQueryGenerator_BlueprintBase_DoItemGeneration_Params params {};
params.ContextLocations = ContextLocations;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F75B10
// Name -> Function AIModule.EnvQueryGenerator_BlueprintBase.AddGeneratedVector
// Flags -> (Final, Native, Public, HasDefaults, BlueprintCallable, Const)
// Parameters:
// struct FVector GeneratedVector (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UEnvQueryGenerator_BlueprintBase::AddGeneratedVector(const struct FVector& GeneratedVector)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryGenerator_BlueprintBase.AddGeneratedVector");
UEnvQueryGenerator_BlueprintBase_AddGeneratedVector_Params params {};
params.GeneratedVector = GeneratedVector;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F75A90
// Name -> Function AIModule.EnvQueryGenerator_BlueprintBase.AddGeneratedActor
// Flags -> (Final, Native, Public, BlueprintCallable, Const)
// Parameters:
// class AActor* GeneratedActor (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UEnvQueryGenerator_BlueprintBase::AddGeneratedActor(class AActor* GeneratedActor)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryGenerator_BlueprintBase.AddGeneratedActor");
UEnvQueryGenerator_BlueprintBase_AddGeneratedActor_Params params {};
params.GeneratedActor = GeneratedActor;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UEnvQueryGenerator_BlueprintBase::AfterRead()
{
UEnvQueryGenerator::AfterRead();
READ_PTR_FULL(Context, UClass);
READ_PTR_FULL(GeneratedItemType, UClass);
}
void UEnvQueryGenerator_BlueprintBase::BeforeDelete()
{
UEnvQueryGenerator::BeforeDelete();
DELE_PTR_FULL(Context);
DELE_PTR_FULL(GeneratedItemType);
}
void UEnvQueryGenerator_Composite::AfterRead()
{
UEnvQueryGenerator::AfterRead();
READ_PTR_FULL(ForcedItemType, UClass);
}
void UEnvQueryGenerator_Composite::BeforeDelete()
{
UEnvQueryGenerator::BeforeDelete();
DELE_PTR_FULL(ForcedItemType);
}
void UEnvQueryGenerator_ProjectedPoints::AfterRead()
{
UEnvQueryGenerator::AfterRead();
}
void UEnvQueryGenerator_ProjectedPoints::BeforeDelete()
{
UEnvQueryGenerator::BeforeDelete();
}
void UEnvQueryGenerator_Cone::AfterRead()
{
UEnvQueryGenerator_ProjectedPoints::AfterRead();
READ_PTR_FULL(CenterActor, UClass);
}
void UEnvQueryGenerator_Cone::BeforeDelete()
{
UEnvQueryGenerator_ProjectedPoints::BeforeDelete();
DELE_PTR_FULL(CenterActor);
}
void UEnvQueryGenerator_CurrentLocation::AfterRead()
{
UEnvQueryGenerator::AfterRead();
READ_PTR_FULL(QueryContext, UClass);
}
void UEnvQueryGenerator_CurrentLocation::BeforeDelete()
{
UEnvQueryGenerator::BeforeDelete();
DELE_PTR_FULL(QueryContext);
}
void UEnvQueryGenerator_Donut::AfterRead()
{
UEnvQueryGenerator_ProjectedPoints::AfterRead();
READ_PTR_FULL(Center, UClass);
}
void UEnvQueryGenerator_Donut::BeforeDelete()
{
UEnvQueryGenerator_ProjectedPoints::BeforeDelete();
DELE_PTR_FULL(Center);
}
void UEnvQueryGenerator_OnCircle::AfterRead()
{
UEnvQueryGenerator_ProjectedPoints::AfterRead();
READ_PTR_FULL(CircleCenter, UClass);
}
void UEnvQueryGenerator_OnCircle::BeforeDelete()
{
UEnvQueryGenerator_ProjectedPoints::BeforeDelete();
DELE_PTR_FULL(CircleCenter);
}
void UEnvQueryGenerator_SimpleGrid::AfterRead()
{
UEnvQueryGenerator_ProjectedPoints::AfterRead();
READ_PTR_FULL(GenerateAround, UClass);
}
void UEnvQueryGenerator_SimpleGrid::BeforeDelete()
{
UEnvQueryGenerator_ProjectedPoints::BeforeDelete();
DELE_PTR_FULL(GenerateAround);
}
void UEnvQueryGenerator_PathingGrid::AfterRead()
{
UEnvQueryGenerator_SimpleGrid::AfterRead();
READ_PTR_FULL(NavigationFilter, UClass);
}
void UEnvQueryGenerator_PathingGrid::BeforeDelete()
{
UEnvQueryGenerator_SimpleGrid::BeforeDelete();
DELE_PTR_FULL(NavigationFilter);
}
// Function:
// Offset -> 0x01F75EE0
// Name -> Function AIModule.EnvQueryInstanceBlueprintWrapper.SetNamedParam
// Flags -> (Final, Native, Public, BlueprintCallable)
// Parameters:
// struct FName ParamName (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float Value (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UEnvQueryInstanceBlueprintWrapper::SetNamedParam(const struct FName& ParamName, float Value)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryInstanceBlueprintWrapper.SetNamedParam");
UEnvQueryInstanceBlueprintWrapper_SetNamedParam_Params params {};
params.ParamName = ParamName;
params.Value = Value;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function:
// Offset -> 0x01F75E60
// Name -> Function AIModule.EnvQueryInstanceBlueprintWrapper.GetResultsAsLocations
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// TArray<struct FVector> ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, NativeAccessSpecifierPublic)
TArray<struct FVector> UEnvQueryInstanceBlueprintWrapper::GetResultsAsLocations()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryInstanceBlueprintWrapper.GetResultsAsLocations");
UEnvQueryInstanceBlueprintWrapper_GetResultsAsLocations_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F75DE0
// Name -> Function AIModule.EnvQueryInstanceBlueprintWrapper.GetResultsAsActors
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// TArray<class AActor*> ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, NativeAccessSpecifierPublic)
TArray<class AActor*> UEnvQueryInstanceBlueprintWrapper::GetResultsAsActors()
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryInstanceBlueprintWrapper.GetResultsAsActors");
UEnvQueryInstanceBlueprintWrapper_GetResultsAsActors_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F75D20
// Name -> Function AIModule.EnvQueryInstanceBlueprintWrapper.GetQueryResultsAsLocations
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, Const)
// Parameters:
// TArray<struct FVector> ResultLocations (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UEnvQueryInstanceBlueprintWrapper::GetQueryResultsAsLocations(TArray<struct FVector>* ResultLocations)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryInstanceBlueprintWrapper.GetQueryResultsAsLocations");
UEnvQueryInstanceBlueprintWrapper_GetQueryResultsAsLocations_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (ResultLocations != nullptr)
*ResultLocations = params.ResultLocations;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F75C60
// Name -> Function AIModule.EnvQueryInstanceBlueprintWrapper.GetQueryResultsAsActors
// Flags -> (Final, Native, Public, HasOutParms, BlueprintCallable, Const)
// Parameters:
// TArray<class AActor*> ResultActors (Parm, OutParm, ZeroConstructor, NativeAccessSpecifierPublic)
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool UEnvQueryInstanceBlueprintWrapper::GetQueryResultsAsActors(TArray<class AActor*>* ResultActors)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryInstanceBlueprintWrapper.GetQueryResultsAsActors");
UEnvQueryInstanceBlueprintWrapper_GetQueryResultsAsActors_Params params {};
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (ResultActors != nullptr)
*ResultActors = params.ResultActors;
return params.ReturnValue;
}
// Function:
// Offset -> 0x01F75BA0
// Name -> Function AIModule.EnvQueryInstanceBlueprintWrapper.GetItemScore
// Flags -> (Final, Native, Public, BlueprintCallable, BlueprintPure, Const)
// Parameters:
// int ItemIndex (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float UEnvQueryInstanceBlueprintWrapper::GetItemScore(int ItemIndex)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryInstanceBlueprintWrapper.GetItemScore");
UEnvQueryInstanceBlueprintWrapper_GetItemScore_Params params {};
params.ItemIndex = ItemIndex;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function:
// Offset -> 0x00B73C40
// Name -> DelegateFunction AIModule.EnvQueryInstanceBlueprintWrapper.EQSQueryDoneSignature__DelegateSignature
// Flags -> (MulticastDelegate, Public, Delegate)
// Parameters:
// class UEnvQueryInstanceBlueprintWrapper* QueryInstance (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EEnvQueryStatus> QueryStatus (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
void UEnvQueryInstanceBlueprintWrapper::EQSQueryDoneSignature__DelegateSignature(class UEnvQueryInstanceBlueprintWrapper* QueryInstance, TEnumAsByte<AIModule_EEnvQueryStatus> QueryStatus)
{
static UFunction* fn = UObject::FindObject<UFunction>("DelegateFunction AIModule.EnvQueryInstanceBlueprintWrapper.EQSQueryDoneSignature__DelegateSignature");
UEnvQueryInstanceBlueprintWrapper_EQSQueryDoneSignature__DelegateSignature_Params params {};
params.QueryInstance = QueryInstance;
params.QueryStatus = QueryStatus;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
void UEnvQueryInstanceBlueprintWrapper::AfterRead()
{
UObject::AfterRead();
READ_PTR_FULL(itemType, UClass);
}
void UEnvQueryInstanceBlueprintWrapper::BeforeDelete()
{
UObject::BeforeDelete();
DELE_PTR_FULL(itemType);
}
void UEnvQueryItemType::AfterRead()
{
UObject::AfterRead();
}
void UEnvQueryItemType::BeforeDelete()
{
UObject::BeforeDelete();
}
void UEnvQueryItemType_VectorBase::AfterRead()
{
UEnvQueryItemType::AfterRead();
}
void UEnvQueryItemType_VectorBase::BeforeDelete()
{
UEnvQueryItemType::BeforeDelete();
}
void UEnvQueryItemType_ActorBase::AfterRead()
{
UEnvQueryItemType_VectorBase::AfterRead();
}
void UEnvQueryItemType_ActorBase::BeforeDelete()
{
UEnvQueryItemType_VectorBase::BeforeDelete();
}
void UEnvQueryItemType_Actor::AfterRead()
{
UEnvQueryItemType_ActorBase::AfterRead();
}
void UEnvQueryItemType_Actor::BeforeDelete()
{
UEnvQueryItemType_ActorBase::BeforeDelete();
}
void UEnvQueryItemType_Direction::AfterRead()
{
UEnvQueryItemType_VectorBase::AfterRead();
}
void UEnvQueryItemType_Direction::BeforeDelete()
{
UEnvQueryItemType_VectorBase::BeforeDelete();
}
void UEnvQueryItemType_Point::AfterRead()
{
UEnvQueryItemType_VectorBase::AfterRead();
}
void UEnvQueryItemType_Point::BeforeDelete()
{
UEnvQueryItemType_VectorBase::BeforeDelete();
}
// Function:
// Offset -> 0x01F7A0B0
// Name -> Function AIModule.EnvQueryManager.RunEQSQuery
// Flags -> (Final, Native, Static, Public, BlueprintCallable)
// Parameters:
// class UObject* WorldContextObject (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UEnvQuery* QueryTemplate (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UObject* Querier (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// TEnumAsByte<AIModule_EEnvQueryRunMode> RunMode (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UClass* WrapperClass (Parm, ZeroConstructor, IsPlainOldData, NoDestructor, AdvancedDisplay, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic)
// class UEnvQueryInstanceBlueprintWrapper* ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
class UEnvQueryInstanceBlueprintWrapper* UEnvQueryManager::STATIC_RunEQSQuery(class UObject* WorldContextObject, class UEnvQuery* QueryTemplate, class UObject* Querier, TEnumAsByte<AIModule_EEnvQueryRunMode> RunMode, class UClass* WrapperClass)
{
static UFunction* fn = UObject::FindObject<UFunction>("Function AIModule.EnvQueryManager.RunEQSQuery");
UEnvQueryManager_RunEQSQuery_Params params {};
params.WorldContextObject = WorldContextObject;
params.QueryTemplate = QueryTemplate;
params.Querier = Querier;
params.RunMode = RunMode;
params.WrapperClass = WrapperClass;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void UEnvQueryManager::AfterRead()
{
UAISubsystem::AfterRead();
}
void UEnvQueryManager::BeforeDelete()
{
UAISubsystem::BeforeDelete();
}
void UEnvQueryOption::AfterRead()
{
UObject::AfterRead();
READ_PTR_FULL(Generator, UEnvQueryGenerator);
}
void UEnvQueryOption::BeforeDelete()
{
UObject::BeforeDelete();
DELE_PTR_FULL(Generator);
}
void UEnvQueryTest_Distance::AfterRead()
{
UEnvQueryTest::AfterRead();
READ_PTR_FULL(DistanceTo, UClass);
}
void UEnvQueryTest_Distance::BeforeDelete()
{
UEnvQueryTest::BeforeDelete();
DELE_PTR_FULL(DistanceTo);
}
void UEnvQueryTest_Dot::AfterRead()
{
UEnvQueryTest::AfterRead();
}
void UEnvQueryTest_Dot::BeforeDelete()
{
UEnvQueryTest::BeforeDelete();
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 36.7815 | 350 | 0.689304 | ResaloliPT |
20c4e2a61e8046783654dd978573fbdee4abd031 | 19,487 | cpp | C++ | plugin/flui/controller.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 2 | 2018-03-19T23:27:47.000Z | 2018-06-24T16:15:19.000Z | plugin/flui/controller.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | null | null | null | plugin/flui/controller.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 1 | 2021-11-28T05:39:05.000Z | 2021-11-28T05:39:05.000Z | // -*- tab-width: 4; indent-tabs-mode: nil; -*-
// vim: tabstop=4:softtabstop=4:expandtab:shiftwidth=4
//
// $Id$
//
#include "zdk/breakpoint_util.h"
#include "zdk/check_ptr.h"
#include "zdk/log.h"
#include "zdk/thread_util.h"
#include "generic/temporary.h"
#include "breakpoint_view.h"
#include "const.h"
#include "code_view.h"
#include "controller.h"
#include "dialog.h"
#include "hotkey.h"
#include "locals_view.h"
#include "stack_view.h"
#include "toolbar.h"
#include "menu.h"
#include "dharma/system_error.h"
#include <pthread.h>
#include <iostream>
// properties
#define WINDOW_X "flui.window.x"
#define WINDOW_Y "flui.window.y"
#define WINDOW_W "flui.window.width"
#define WINDOW_H "flui.window.height"
using namespace std;
/**
* Pass debugger and debuggee state information
* from main thread to UI thread.
*/
class ui::Controller::StateImpl : public ui::State
{
RefPtr<Symbol> currentSymbol_;
RefPtr<Thread> currentThread_;
EventType currentEventType_;
size_t attachedThreadCount_;
bool isTargetStopped_;
public:
StateImpl( )
: currentEventType_(E_NONE)
, attachedThreadCount_(0)
, isTargetStopped_(false)
{ }
virtual void update(Thread*, EventType);
virtual bool is_target_running() const {
bool result = (currentEventType_ == E_TARGET_RESUMED);
return result;
}
virtual bool is_target_stopped() const {
return isTargetStopped_;
}
virtual EventType current_event() const {
return currentEventType_;
}
virtual RefPtr<Symbol> current_symbol() const {
return currentSymbol_;
}
virtual RefPtr<Thread> current_thread() const {
return currentThread_;
}
};
void ui::Controller::StateImpl::update(
Thread* currentThread,
EventType eventType )
{
isTargetStopped_ = false;
currentThread_ = currentThread;
currentEventType_ = eventType;
currentSymbol_.reset();
if (currentThread && eventType != E_TARGET_RESUMED)
{
isTargetStopped_ = thread_stopped(*currentThread)
// core dumps are neither "running" or "stopped"
&& currentThread->is_live();
addr_t pc = currentThread->program_count();
assert(currentThread->symbols());
currentSymbol_ = currentThread->symbols()->lookup_symbol(pc);
}
}
////////////////////////////////////////////////////////////////
class BreakPointUpdater : public EnumCallback<volatile BreakPoint*>
{
public:
explicit BreakPointUpdater(ui::Controller& controller)
: controller_(controller)
{ }
// Add view to the internal list of views to be updated
void push_back(RefPtr<ui::View> view)
{
if (view)
{
views_.push_back(view);
}
}
bool empty() const {
return views_.empty();
}
void notify(volatile BreakPoint* bp)
{
// we only care about user-defined breakpoints,
// the internal breakpoints used by the engine
// are not shown
if (bp->enum_actions("USER"))
{
auto& breakPoint = const_cast<BreakPoint&>(*bp);
if (auto d = controller_.current_dialog())
{
d->update_breakpoint(breakPoint);
}
for (auto v = begin(views_); v != end(views_); ++v)
{
(*v)->update_breakpoint(breakPoint);
}
}
}
private:
typedef vector<RefPtr<ui::View> > Views;
ui::Controller& controller_;
Views views_;
};
////////////////////////////////////////////////////////////////
/**
* An error may occur while executing a command on the main thread.
* Should that happen, the controller replaces the command in the
* mail-slot with this one, so that an error message is shown in
* the UI thread.
*/
class CommandError : public ui::Command
{
ui::Controller& controller_;
string msg_;
public:
CommandError(ui::Controller& controller, const char* m)
: controller_(controller), msg_(m)
{ }
virtual ~CommandError() throw() { }
void continue_on_ui_thread() {
controller_.error_message(msg_);
}
};
////////////////////////////////////////////////////////////////
ui::IdleCommand::IdleCommand() : cancelled_(false)
{
}
void ui::IdleCommand::execute_on_main_thread()
{
Lock<Mutex> lock(mutex_);
for (cancelled_ = false; !cancelled_; )
{
cond_.wait(lock);
}
}
void ui::IdleCommand::cancel()
{
set_cancel();
cond_.broadcast();
}
void ui::IdleCommand::set_cancel()
{
Lock<Mutex> lock(mutex_);
cancelled_ = true;
}
////////////////////////////////////////////////////////////////
//
// Controller implementation
//
ui::Controller::Controller()
: debugger_(nullptr)
, threadId_(0)
, state_(init_state())
, done_(false)
, probing_(false)
, idle_(new IdleCommand)
{
}
////////////////////////////////////////////////////////////////
ui::Controller::~Controller()
{
}
////////////////////////////////////////////////////////////////
unique_ptr<ui::Controller::StateImpl> ui::Controller::init_state( )
{
return unique_ptr<StateImpl>(new StateImpl());
}
////////////////////////////////////////////////////////////////
void ui::Controller::build()
{
Properties& prop = *CHKPTR(debugger_)->properties();
// get coordinates and dimensions from saved properties
const word_t x = prop.get_word(WINDOW_X, 0);
const word_t y = prop.get_word(WINDOW_Y, 0);
const word_t h = prop.get_word(WINDOW_H, Const::default_window_height);
const word_t w = prop.get_word(WINDOW_W, Const::default_window_width);
init_main_window(x, y, w, h);
build_menu();
build_toolbar();
build_layout();
}
////////////////////////////////////////////////////////////////
void ui::Controller::build_layout()
{
layout_ = init_layout();
code_ = init_code_view();
if (code_)
{
layout_->add(*code_);
}
if (auto v = init_stack_view())
{
layout_->add(*v);
}
if (auto v = init_locals_view())
{
layout_->add(*v);
}
breakpoints_ = init_breakpoint_view();
if (breakpoints_)
{
layout_->add(*breakpoints_);
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::build_menu()
{
menu_ = init_menu();
// --------------------------------------------------------
// File
//
menu_->add_ui_item("&File/&Open...", 0, Enable_IfNotRunning,
[this]
{
open_file_dialog("Open", "*", nullptr);
});
menu_->add_item("&File/&Quit", *HotKey::alt('q'), Enable_Always,
[this]
{
CHKPTR(debugger_)->quit();
});
// --------------------------------------------------------
// Run
//
menu_->add_item("&Run/&Continue", *HotKey::fn(5), Enable_IfStopped,
[this]()
{
CHKPTR(debugger_)->resume();
});
menu_->add_item("&Run/&Next", *HotKey::fn(10), Enable_IfStopped,
[this]
{
if (auto t = state_->current_thread())
{
CHKPTR(debugger_)->step(t.get(), Debugger::STEP_OVER_SOURCE_LINE);
CHKPTR(debugger_)->resume();
}
});
menu_->add_item("&Run/&Return from function", 0, Enable_IfStopped,
[this]
{
CHKPTR(debugger_)->command("ret", state_->current_thread().get());
});
menu_->add_item("&Run/&Step", *HotKey::fn(11), Enable_IfStopped,
[this]
{
if (auto t = state_->current_thread())
{
CHKPTR(debugger_)->step(t.get(), Debugger::STEP_SOURCE_LINE);
CHKPTR(debugger_)->resume();
}
});
/* TODO
menu_->add_item("&Run/Ste&p Instruction", *HotKey::fn(11), Enable_IfStopped,
[this]
{
});
*/
menu_->add_item("&Run/&Break", *HotKey::ctrl('c'), Enable_IfRunning,
[this]
{ // nothing to do here, call_main_thread
// will ensure the target breaks into the debugger
}, true /* append divider */);
menu_->add_item("&Run/Restart", 0, Enable_IfStopped,
[this]
{
CHKPTR(debugger_)->command("restart", state_->current_thread().get());
});
// --------------------------------------------------------
// Breakpoints
//
menu_->add_item("&Breakpoints/&Toggle", *HotKey::fn (9), Enable_IfStopped,
[this]
{
toggle_user_breakpoint();
});
// --------------------------------------------------------
// Tools
//
menu_->add_ui_item("&Tools/E&valuate", *HotKey::alt('v'), Enable_IfNotRunning,
[this]
{
show_eval_dialog();
});
}
////////////////////////////////////////////////////////////////
void ui::Controller::build_toolbar()
{
toolbar_ = init_toolbar();
}
////////////////////////////////////////////////////////////////
/**
* UI event loop
*/
void ui::Controller::run()
{
while (wait_for_event() > 0)
{
if (command_) try
{
command_->continue_on_ui_thread();
}
catch (const exception& e)
{
error_message(e.what());
}
if (done_)
{
break;
}
}
}
////////////////////////////////////////////////////////////////
/**
* Parse command line and other initializing stuff
*/
bool ui::Controller::initialize(
Debugger* debugger,
int* /* argc */,
char*** /* argv */)
{
debugger_ = debugger;
if (probe_interactive_plugins())
{
return false; // back off if interactive plugins detected
}
return true;
}
////////////////////////////////////////////////////////////////
void ui::Controller::done()
{
call_main_thread_async(new MainThreadCommand<>([this]() {
CHKPTR(debugger_)->quit();
}));
unlock();
}
////////////////////////////////////////////////////////////////
void ui::Controller::update(
LockedScope& scope,
Thread* thread,
EventType eventType )
{
state_->update(thread, eventType);
// update modal dialog if any
if (auto dialog = current_dialog())
{
dialog->update(*state_);
}
//
// pass updated state info to UI elements
//
if (menu_)
{
menu_->update(*state_);
}
if (toolbar_)
{
toolbar_->update(*state_);
}
if (layout_)
{
layout_->update(*state_);
}
// @note: Updating the layout automatically updates code views
// and we want to update breakpoints last;
// DO NOT CHANGE this order of operations.
if (thread && thread->is_live())
{
BreakPointUpdater updater(*this);
updater.push_back(breakpoints_);
updater.push_back(code_);
if (!updater.empty())
{
if (RefPtr<BreakPointManager> mgr = CHKPTR(debugger_)->breakpoint_manager())
{
mgr->enum_breakpoints(&updater);
}
}
}
if (state_->current_event() == E_TARGET_FINISHED)
{
status_message("Target disconnected");
}
}
////////////////////////////////////////////////////////////////
RefPtr<ui::Command> ui::Controller::update(
Thread* thread,
EventType eventType )
{
LockedScope lock(*this);
update(lock, thread, eventType);
if (command_ && command_->is_complete())
{
command_.reset();
}
if (!command_)
{
command_ = idle_;
}
return command_;
}
/**
* Called from the main debugger thread.
*
* @return true to indicate that the event was handled.
*/
bool ui::Controller::on_event(
Thread* thread,
EventType eventType )
{
if (eventType == E_PROBE_INTERACTIVE)
{
return !probing_;
}
RefPtr<Command> c = update(thread, eventType);
try
{
c->execute_on_main_thread();
}
catch (const exception& e)
{
c = new CommandError(*this, e.what());
}
notify_ui_thread();
return true;
}
////////////////////////////////////////////////////////////////
void* ui::Controller::run(void* p)
{
auto controller = reinterpret_cast<ui::Controller*>(p);
try
{
controller->lock();
controller->build();
controller->run();
}
catch (const exception& e)
{
dbgout(Log::ALWAYS) << __func__ << ": " << e.what() << endl;
}
catch (...)
{
assert(false);
}
controller->done();
return nullptr;
}
////////////////////////////////////////////////////////////////
void ui::Controller::start()
{
int r = pthread_create(&threadId_, nullptr, run, this);
if (r < 0)
{
throw SystemError(__func__, r);
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::shutdown()
{
{
LockedScope lock(*this);
save_configuration();
done_ = true;
}
pthread_join(threadId_, nullptr);
}
////////////////////////////////////////////////////////////////
void ui::Controller::register_streamable_objects(
ObjectFactory* /* factory */)
{
}
////////////////////////////////////////////////////////////////
void ui::Controller::on_table_init(SymbolTable*)
{
}
////////////////////////////////////////////////////////////////
void ui::Controller::on_table_done(SymbolTable*)
{
}
////////////////////////////////////////////////////////////////
void ui::Controller::on_attach(Thread*)
{
}
////////////////////////////////////////////////////////////////
void ui::Controller::on_detach(Thread* t)
{
if (t == 0) // detached from all threads?
{
LockedScope lock(*this);
update(lock, nullptr, E_TARGET_FINISHED);
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::on_syscall(Thread*, int32_t)
{
}
////////////////////////////////////////////////////////////////
void ui::Controller::on_program_resumed()
{
LockedScope lock(*this);
update(lock, nullptr, E_TARGET_RESUMED);
}
////////////////////////////////////////////////////////////////
void ui::Controller::on_insert_breakpoint(volatile BreakPoint* bpnt)
{
if (bpnt->enum_actions("USER"))
{
LockedScope lock(*this);
update(lock, state_->current_thread().get(), E_PROMPT);
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::on_remove_breakpoint(volatile BreakPoint* bpnt)
{
if (bpnt->enum_actions("USER"))
{
LockedScope lock(*this);
update(lock, state_->current_thread().get(), E_PROMPT);
}
}
////////////////////////////////////////////////////////////////
bool ui::Controller::on_progress(
const char* what,
double percent,
word_t cookie)
{
return true;
}
////////////////////////////////////////////////////////////////
bool ui::Controller::on_message (
const char* what,
Debugger::MessageType type,
Thread* thread,
bool async)
{
return false;
}
////////////////////////////////////////////////////////////////
void ui::Controller::call_main_thread_async(RefPtr<Command> c)
{
if (c)
{
if (state_->is_target_running())
{
CHKPTR(debugger_)->stop();
}
else
{
awaken_main_thread();
}
command_ = c;
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::awaken_main_thread()
{
idle_->cancel();
}
////////////////////////////////////////////////////////////////
void ui::Controller::save_configuration()
{
if (!debugger_)
{
return;
}
Properties& prop = *debugger_->properties();
prop.set_word(WINDOW_X, x());
prop.set_word(WINDOW_Y, y());
prop.set_word(WINDOW_H, h());
prop.set_word(WINDOW_W, w());
}
////////////////////////////////////////////////////////////////
ui::State& ui::Controller::state()
{
return *CHKPTR(state_.get());
}
////////////////////////////////////////////////////////////////
void ui::Controller::status_message(const std::string& msg)
{
if (auto dialog = current_dialog())
{
if (dialog->status_message(msg.c_str()))
{
return;
}
}
if (layout_)
{
layout_->status_message(msg);
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::set_current_dialog(Dialog* dialog)
{
if (dialog)
{
dialogStack_.push_back(dialog);
}
else
{
assert(!dialogStack_.empty());
dialogStack_.pop_back();
}
}
////////////////////////////////////////////////////////////////
bool ui::Controller::probe_interactive_plugins()
{
Temporary<bool> temp(probing_, true);
bool result = debugger()->publish_event(nullptr, E_PROBE_INTERACTIVE);
return result;
}
////////////////////////////////////////////////////////////////
void ui::Controller::toggle_user_breakpoint(addr_t addr)
{
if (auto t = state_->current_thread())
{
if (!CHKPTR(debugger_)->set_user_breakpoint(get_runnable(t.get()), addr))
{
// failed to set breakpoint? it means
// that it exists already, so remove it
CHKPTR(debugger_)->remove_user_breakpoint(0, 0, addr);
}
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::toggle_user_breakpoint()
{
if (code_) // have a code view?
{
if (auto listing = code_->get_listing())
{
addr_t addr = listing->selected_addr();
toggle_user_breakpoint(addr);
}
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::enable_user_breakpoint(
addr_t addr,
ui::EnableMode mode )
{
CHKPTR(debugger_);
switch (mode)
{
case ui::Enable:
enable_user_breakpoint_actions(*debugger_, addr);
break;
case ui::Disable:
disable_user_breakpoint_actions(*debugger_, addr);
break;
case ui::Toggle:
mode = has_enabled_user_breakpoint_actions(*debugger_, addr)
? ui::Disable : ui::Enable;
enable_user_breakpoint( addr, mode );
break;
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::set_temp_breakpoint(addr_t addr)
{
if (auto r = get_runnable(state_->current_thread()))
{
CHKPTR(debugger_)->set_temp_breakpoint(r, addr);
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::set_user_breakpoint(addr_t addr, bool set)
{
if (auto r = get_runnable(state_->current_thread()))
{
if (set)
{
CHKPTR(debugger_)->set_user_breakpoint(r, addr);
}
else
{
CHKPTR(debugger_)->remove_user_breakpoint(0, 0, addr);
}
}
}
////////////////////////////////////////////////////////////////
void ui::Controller::show_edit_breakpoint_dialog(addr_t addr)
{
UserBreakPoint ubp = breakpoints_->addr_to_breakpoint(addr);
show_edit_breakpoint_dialog(ubp);
}
| 22.245434 | 88 | 0.492687 | cristivlas |
20c76dcda708b5ad60e471a76e6da3eaa71c0b2b | 9,717 | cc | C++ | src/connectivity/network/tun/network-tun/tun_device.cc | casey/fuchsia | 2b965e9a1e8f2ea346db540f3611a5be16bb4d6b | [
"BSD-3-Clause"
] | 14 | 2020-10-25T05:48:36.000Z | 2021-09-20T02:46:20.000Z | src/connectivity/network/tun/network-tun/tun_device.cc | DamieFC/fuchsia | f78a4a1326f4a4bb5834500918756173c01bab4f | [
"BSD-2-Clause"
] | 1 | 2022-01-14T23:38:40.000Z | 2022-01-14T23:38:40.000Z | src/connectivity/network/tun/network-tun/tun_device.cc | DamieFC/fuchsia | f78a4a1326f4a4bb5834500918756173c01bab4f | [
"BSD-2-Clause"
] | 4 | 2020-12-28T17:04:45.000Z | 2022-03-12T03:20:44.000Z | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "tun_device.h"
#include <lib/async-loop/default.h>
#include <lib/async/cpp/task.h>
#include <lib/syslog/global.h>
#include <zircon/status.h>
#include <fbl/auto_lock.h>
#include "util.h"
namespace network {
namespace tun {
namespace {
bool MacListEquals(const std::vector<fuchsia::net::MacAddress>& l,
const std::vector<fuchsia::net::MacAddress>& r) {
auto li = l.begin();
auto ri = r.begin();
for (; li != l.end() && ri != r.end(); li++, ri++) {
if (memcmp(li->octets.data(), ri->octets.data(), MAC_SIZE) != 0) {
return false;
}
}
return li == l.end() && ri == r.end();
}
} // namespace
TunDevice::TunDevice(fit::callback<void(TunDevice*)> teardown,
fuchsia::net::tun::DeviceConfig config)
: loop_(&kAsyncLoopConfigNoAttachToCurrentThread),
teardown_callback_(std::move(teardown)),
config_(std::move(config)),
binding_(this) {
binding_.set_error_handler([this](zx_status_t) { Teardown(); });
}
zx_status_t TunDevice::Create(fit::callback<void(TunDevice*)> teardown,
fuchsia::net::tun::DeviceConfig config,
std::unique_ptr<TunDevice>* out) {
if (!TryConsolidateDeviceConfig(&config)) {
return ZX_ERR_INVALID_ARGS;
}
std::unique_ptr<TunDevice> tun(new TunDevice(std::move(teardown), std::move(config)));
zx_status_t status = zx::eventpair::create(0, &tun->signals_peer_, &tun->signals_self_);
if (status != ZX_OK) {
FX_LOGF(ERROR, "tun", "TunDevice::Init failed to create eventpair %s",
zx_status_get_string(status));
return status;
}
status = DeviceAdapter::Create(tun->loop_.dispatcher(), tun.get(), tun->config_.online(),
&tun->device_);
if (status != ZX_OK) {
FX_LOGF(ERROR, "tun", "TunDevice::Init device init failed with %s",
zx_status_get_string(status));
return status;
}
if (tun->config_.has_mac()) {
status = MacAdapter::Create(tun.get(), tun->config_.mac(), false, &tun->mac_);
if (status != ZX_OK) {
FX_LOGF(ERROR, "tun", "TunDevice::Init mac init failed with %s",
zx_status_get_string(status));
return status;
}
}
thrd_t thread;
status = tun->loop_.StartThread("tun-device", &thread);
if (status != ZX_OK) {
return status;
}
tun->loop_thread_ = thread;
*out = std::move(tun);
return ZX_OK;
}
TunDevice::~TunDevice() {
if (loop_thread_.has_value()) {
// not allowed to destroy a tun device on the loop thread, will cause deadlock
ZX_ASSERT(loop_thread_.value() != thrd_current());
}
// make sure that device is torn down:
if (device_) {
device_->TeardownSync();
}
if (mac_) {
mac_->TeardownSync();
}
loop_.Shutdown();
FX_VLOG(1, "tun", "TunDevice destroyed");
}
void TunDevice::Bind(fidl::InterfaceRequest<fuchsia::net::tun::Device> req) {
binding_.Bind(std::move(req), loop_.dispatcher());
}
void TunDevice::Teardown() {
if (teardown_callback_) {
teardown_callback_(this);
}
}
void TunDevice::RunWriteFrame() {
while (!pending_write_frame_.empty()) {
size_t avail = 0;
auto& pending = pending_write_frame_.front();
auto result = device_->WriteRxFrame(
pending.frame.frame_type(), pending.frame.data(),
pending.frame.has_meta() ? pending.frame.mutable_meta() : nullptr, &avail);
if (result == ZX_ERR_SHOULD_WAIT && IsBlocking()) {
return;
}
if (result != ZX_OK) {
pending.callback(fit::error(result));
} else {
if (avail == 0) {
// Clear the writable signal if no more buffers are available afterwards.
signals_self_.signal_peer(static_cast<uint32_t>(fuchsia::net::tun::Signals::WRITABLE), 0);
}
pending.callback(fit::ok());
}
pending_write_frame_.pop();
}
}
void TunDevice::RunReadFrame() {
while (!pending_read_frame_.empty()) {
auto success = device_->TryGetTxBuffer([this](Buffer* buff, size_t avail) {
std::vector<uint8_t> data;
zx_status_t status = buff->Read(&data);
if (status != ZX_OK) {
FX_LOGF(ERROR, "tun", "Failed to read from tx buffer: %s", zx_status_get_string(status));
} else if (data.empty()) {
FX_LOG(WARNING, "tun", "Ignoring empty tx buffer");
} else {
auto& callback = pending_read_frame_.front();
fuchsia::net::tun::Device_ReadFrame_Response rsp;
rsp.frame.set_data(std::move(data));
rsp.frame.set_frame_type(buff->frame_type());
auto meta = buff->TakeMetadata();
if (meta) {
rsp.frame.set_meta(std::move(*meta));
}
callback(fuchsia::net::tun::Device_ReadFrame_Result::WithResponse(std::move(rsp)));
pending_read_frame_.pop();
if (avail == 0) {
// clear SIGNAL_READABLE if we don't have any more tx buffers.
signals_self_.signal_peer(static_cast<uint32_t>(fuchsia::net::tun::Signals::READABLE), 0);
}
}
});
if (!success) {
if (IsBlocking()) {
return;
} else {
auto& callback = pending_read_frame_.front();
callback(fuchsia::net::tun::Device_ReadFrame_Result::WithErr(ZX_ERR_SHOULD_WAIT));
pending_read_frame_.pop();
}
}
}
}
void TunDevice::RunStateChange() {
if (!pending_watch_state_) {
return;
}
fuchsia::net::tun::InternalState state;
state.set_has_session(device_->HasSession());
{
if (mac_) {
fuchsia::net::tun::MacState mac_state;
mac_->CloneMacState(&mac_state);
state.set_mac(std::move(mac_state));
}
}
if (last_state_.has_value()) {
auto& last = last_state_.value();
// only continue if any changes actually occurred compared to the last observed state
if (last.has_session() == state.has_session() &&
(!last.has_mac() ||
(last.mac().mode() == state.mac().mode() &&
MacListEquals(last.mac().multicast_filters(), state.mac().multicast_filters())))) {
return;
}
}
fuchsia::net::tun::InternalState clone;
state.Clone(&clone);
// store the last informed state through WatchState
last_state_ = std::move(clone);
pending_watch_state_(std::move(state));
pending_watch_state_ = nullptr;
}
void TunDevice::WriteFrame(fuchsia::net::tun::Frame frame,
fuchsia::net::tun::Device::WriteFrameCallback callback) {
if (pending_write_frame_.size() >= kMaxPendingOps) {
callback(fit::error(ZX_ERR_NO_RESOURCES));
return;
}
if (!(frame.has_frame_type() && frame.has_data() && !frame.data().empty())) {
callback(fit::error(ZX_ERR_INVALID_ARGS));
return;
}
pending_write_frame_.emplace(std::move(frame), std::move(callback));
RunWriteFrame();
}
void TunDevice::ReadFrame(fuchsia::net::tun::Device::ReadFrameCallback callback) {
if (pending_read_frame_.size() >= kMaxPendingOps) {
callback(fit::error(ZX_ERR_NO_RESOURCES));
return;
}
pending_read_frame_.push(std::move(callback));
RunReadFrame();
}
void TunDevice::GetSignals(fuchsia::net::tun::Device::GetSignalsCallback callback) {
zx::eventpair dup;
signals_peer_.duplicate(ZX_RIGHTS_BASIC, &dup);
callback(std::move(dup));
}
void TunDevice::GetState(fuchsia::net::tun::Device::GetStateCallback callback) {
fuchsia::net::tun::InternalState state;
state.set_has_session(device_->HasSession());
if (mac_) {
fuchsia::net::tun::MacState mac_state;
mac_->CloneMacState(&mac_state);
state.set_mac(std::move(mac_state));
}
callback(std::move(state));
}
void TunDevice::WatchState(fuchsia::net::tun::Device::WatchStateCallback callback) {
if (pending_watch_state_) {
// this is a programming error, we enforce that clients don't do this by closing their channel.
binding_.Close(ZX_ERR_INTERNAL);
Teardown();
return;
}
pending_watch_state_ = std::move(callback);
RunStateChange();
}
void TunDevice::SetOnline(bool online, fuchsia::net::tun::Device::SetOnlineCallback callback) {
device_->SetOnline(online);
if (!online) {
// if we just went offline, we need to complete all pending writes.
RunWriteFrame();
}
callback();
}
void TunDevice::ConnectProtocols(fuchsia::net::tun::Protocols protos) {
if (device_ && protos.has_network_device()) {
auto status = device_->Bind(protos.mutable_network_device()->TakeChannel());
if (status != ZX_OK) {
FX_LOGF(ERROR, "tun", "Failed to bind to network device: %s", zx_status_get_string(status));
}
}
if (mac_ && protos.has_mac_addressing()) {
auto status = mac_->Bind(loop_.dispatcher(), protos.mutable_mac_addressing()->TakeChannel());
if (status != ZX_OK) {
FX_LOGF(ERROR, "tun", "Failed to bind to mac addressing: %s", zx_status_get_string(status));
}
}
}
void TunDevice::OnHasSessionsChanged(DeviceAdapter* device) {
async::PostTask(loop_.dispatcher(), [this]() { RunStateChange(); });
}
void TunDevice::OnTxAvail(DeviceAdapter* device) {
signals_self_.signal_peer(0, static_cast<uint32_t>(fuchsia::net::tun::Signals::READABLE));
async::PostTask(loop_.dispatcher(), [this]() { RunReadFrame(); });
}
void TunDevice::OnRxAvail(DeviceAdapter* device) {
signals_self_.signal_peer(0, static_cast<uint32_t>(fuchsia::net::tun::Signals::WRITABLE));
async::PostTask(loop_.dispatcher(), [this]() { RunWriteFrame(); });
}
void TunDevice::OnMacStateChanged(MacAdapter* adapter) {
async::PostTask(loop_.dispatcher(), [this]() {
RunWriteFrame();
RunStateChange();
});
}
} // namespace tun
} // namespace network
| 31.754902 | 100 | 0.652773 | casey |
20c8ee434e3d61bfed242485685487def4f3d90c | 21,599 | cpp | C++ | src/modules/hip/kernel/canny_edge_detector.cpp | shobana-mcw/rpp | e4a5eb622b9abd0a5a936bf7174a84a5e2470b59 | [
"MIT"
] | 26 | 2019-09-04T17:48:41.000Z | 2022-02-23T17:04:24.000Z | src/modules/hip/kernel/canny_edge_detector.cpp | shobana-mcw/rpp | e4a5eb622b9abd0a5a936bf7174a84a5e2470b59 | [
"MIT"
] | 57 | 2019-09-06T21:37:34.000Z | 2022-03-09T02:13:46.000Z | src/modules/hip/kernel/canny_edge_detector.cpp | shobana-mcw/rpp | e4a5eb622b9abd0a5a936bf7174a84a5e2470b59 | [
"MIT"
] | 24 | 2019-09-04T23:12:07.000Z | 2022-03-30T02:06:22.000Z | #include <hip/hip_runtime.h>
#include "rpp_hip_host_decls.hpp"
#define RPPABS(a) ((a < 0) ? (-a) : (a))
#define saturate_8u(value) ((value) > 255 ? 255 : ((value) < 0 ? 0 : (value)))
extern "C" __global__ void canny_ced_pln3_to_pln1(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
if (id_x >= width || id_y >= height)
{
return;
}
int IPpixIdx = id_x + id_y * width;
int ch = height * width;
float value = ((input[IPpixIdx] + input[IPpixIdx + ch] + input[IPpixIdx + ch * 2]) / 3);
output[IPpixIdx] = (unsigned char)value;
}
extern "C" __global__ void canny_ced_pkd3_to_pln1(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
if (id_x >= width || id_y >= height)
{
return;
}
int OPpixIdx = id_x + id_y * width;
int IPpixIdx = id_x * channel + id_y * width * channel;
float value = (input[IPpixIdx] + input[IPpixIdx + 1] + input[IPpixIdx + 2]) / 3;
output[OPpixIdx] = (unsigned char)value;
}
extern "C" __global__ void canny_ced_pln1_to_pln3(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
if (id_x >= width || id_y >= height)
{
return;
}
int IPpixIdx = id_x + id_y * width;
int ch = height * width;
output[IPpixIdx] = input[IPpixIdx];
output[IPpixIdx + ch] = input[IPpixIdx];
output[IPpixIdx + ch * 2] = input[IPpixIdx];
}
extern "C" __global__ void canny_ced_pln1_to_pkd3(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
if (id_x >= width || id_y >= height)
{
return;
}
int IPpixIdx = id_x + id_y * width;
int OPpixIdx = id_x * channel + id_y * width * channel;
output[OPpixIdx] = input[IPpixIdx];
output[OPpixIdx + 1] = input[IPpixIdx];
output[OPpixIdx + 2] = input[IPpixIdx];
}
extern "C" __global__ void ced_pln3_to_pln1_batch(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned long batchIndex)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
if (id_x >= width || id_y >= height)
{
return;
}
unsigned long IPpixIdx = (unsigned long)batchIndex + (unsigned long)id_x + (unsigned long)id_y * (unsigned long)width;
unsigned long OPpixIdx = (unsigned long)id_x + (unsigned long)id_y * (unsigned long)width;
int ch = height * width;
float value = ((input[IPpixIdx] + input[IPpixIdx + ch] + input[IPpixIdx + ch * 2]) / 3);
output[OPpixIdx] = (unsigned char)value;
}
extern "C" __global__ void ced_pkd3_to_pln1_batch(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned long batchIndex)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
if (id_x >= width || id_y >= height)
{
return;
}
unsigned long OPpixIdx = (unsigned long)id_x + (unsigned long)id_y * (unsigned long)width;
unsigned long IPpixIdx = (unsigned long)batchIndex + (unsigned long)id_x * (unsigned long)channel + (unsigned long)id_y * (unsigned long)width * (unsigned long)channel;
float value = (input[IPpixIdx] + input[IPpixIdx + 1] + input[IPpixIdx + 2]) / 3;
output[OPpixIdx] = (unsigned char)value;
}
extern "C" __global__ void ced_pln1_to_pln3_batch(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned long batchIndex)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
if (id_x >= width || id_y >= height)
{
return;
}
unsigned long IPpixIdx = (unsigned long)id_x + (unsigned long)id_y * (unsigned long)width;
unsigned long OPpixIdx = (unsigned long)batchIndex + (unsigned long)id_x + (unsigned long)id_y * (unsigned long)width;
int ch = height * width;
output[OPpixIdx] = input[IPpixIdx];
output[OPpixIdx + ch] = input[IPpixIdx];
output[OPpixIdx + ch * 2] = input[IPpixIdx];
}
extern "C" __global__ void ced_pln1_to_pkd3_batch(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned long batchIndex)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
if (id_x >= width || id_y >= height)
{
return;
}
unsigned long IPpixIdx = (unsigned long)id_x + (unsigned long)id_y * (unsigned long)width;
unsigned long OPpixIdx = (unsigned long)batchIndex + (unsigned long)id_x * (unsigned long)channel + (unsigned long)id_y * (unsigned long)width * (unsigned long)channel;
output[OPpixIdx] = input[IPpixIdx];
output[OPpixIdx + 1] = input[IPpixIdx];
output[OPpixIdx + 2] = input[IPpixIdx];
}
extern "C" __global__ void ced_non_max_suppression(unsigned char *input,
unsigned char *input1,
unsigned char *input2,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned char min,
const unsigned char max)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z;
if (id_x >= width || id_y >= height || id_z >= channel)
{
return;
}
int pixIdx = id_y * channel * width + id_x * channel + id_z;
float gradient = atan((float)input1[pixIdx] / (float)input2[pixIdx]);
unsigned char pixel1, pixel2;
if (RPPABS(gradient) > 1.178097)
{
if(id_x != 0)
pixel1 = input[pixIdx - 1];
else
pixel1 = 0;
if(id_x != width - 1)
pixel2 = input[pixIdx + 1];
else
pixel2 = 0;
}
else if (gradient > 0.392699)
{
if(id_x != 0 && id_y !=0)
pixel1 = input[pixIdx - width - 1];
else
pixel1 = 0;
if(id_x != width - 1 && id_y != height - 1)
pixel2 = input[pixIdx + width + 1];
else
pixel2 = 0;
}
else if (gradient < -0.392699)
{
if(id_x != width - 1 && id_y !=0)
pixel1 = input[pixIdx - width + 1];
else
pixel1 = 0;
if(id_x != 0 && id_y != height - 1)
pixel2 = input[pixIdx + width - 1];
else
pixel2 = 0;
}
else
{
if(id_y != 0)
pixel1 = input[pixIdx - width];
else
pixel1 = 0;
if(id_y != height - 1)
pixel2 = input[pixIdx + width];
else
pixel2 = 0;
}
if(input[pixIdx] >= pixel1 && input[pixIdx] >= pixel2)
{
if(input[pixIdx] >= max)
output[pixIdx] = 255;
else if(input[pixIdx] <= min)
output[pixIdx] = 0;
else
output[pixIdx] = 128;
}
else
output[pixIdx] = 0;
}
extern "C" __global__ void ced_non_max_suppression_batch(unsigned char *input,
unsigned char *input1,
unsigned char *input2,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned char min,
const unsigned char max)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z;
if (id_x >= width || id_y >= height || id_z >= channel)
{
return;
}
int pixIdx = id_y * channel * width + id_x * channel + id_z;
float gradient = atan((float)input1[pixIdx] / (float)input2[pixIdx]);
unsigned char pixel1, pixel2;
if (RPPABS(gradient) > 1.178097)
{
if(id_x != 0)
pixel1 = input[pixIdx - 1];
else
pixel1 = 0;
if(id_x != width - 1)
pixel2 = input[pixIdx + 1];
else
pixel2 = 0;
}
else if (gradient > 0.392699)
{
if(id_x != 0 && id_y !=0)
pixel1 = input[pixIdx - width - 1];
else
pixel1 = 0;
if(id_x != width - 1 && id_y != height - 1)
pixel2 = input[pixIdx + width + 1];
else
pixel2 = 0;
}
else if (gradient < -0.392699)
{
if(id_x != width - 1 && id_y !=0)
pixel1 = input[pixIdx - width + 1];
else
pixel1 = 0;
if(id_x != 0 && id_y != height - 1)
pixel2 = input[pixIdx + width - 1];
else
pixel2 = 0;
}
else
{
if(id_y != 0)
pixel1 = input[pixIdx - width];
else
pixel1 = 0;
if(id_y != height - 1)
pixel2 = input[pixIdx + width];
else
pixel2 = 0;
}
if(input[pixIdx] >= pixel1 && input[pixIdx] >= pixel2)
{
if(input[pixIdx] >= max)
output[pixIdx] = 255;
else if(input[pixIdx] <= min)
output[pixIdx] = 0;
else
output[pixIdx] = 128;
}
else
output[pixIdx] = 0;
}
extern "C" __global__ void canny_edge(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned char min,
const unsigned char max)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z;
int pixIdx = id_y * width + id_x + id_z * width * height;
if (id_x >= width || id_y >= height || id_z >= channel)
{
return;
}
if(input[pixIdx] == 0 || input[pixIdx] == 255)
{
output[pixIdx] = input[pixIdx];
}
else
{
for(int i = -1; i <= 1; i++)
{
for(int j = -1; j <= 1; j++)
{
if(id_x != 0 && id_x != width - 1 && id_y != 0 && id_y != height -1)
{
unsigned int index = pixIdx + j + (i * width);
if(input[index] == 255)
{
output[pixIdx] = 255;
break;
}
}
}
}
}
}
extern "C" __global__ void canny_edge_batch(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned char min,
const unsigned char max,
const unsigned long batchIndex,
const unsigned int originalChannel)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z;
if (id_x >= width || id_y >= height || id_z >= channel)
{
return;
}
unsigned long IPpixIdx, OPpixIdx;
IPpixIdx = (unsigned long)id_y * (unsigned long)width + (unsigned long)id_x;
if(originalChannel == 1)
{
OPpixIdx = (unsigned long)batchIndex + (unsigned long)id_y * (unsigned long)width + (unsigned long)id_x;
}
else
{
OPpixIdx = (unsigned long)IPpixIdx;
}
if(input[IPpixIdx] == 0 || input[IPpixIdx] == 255)
{
output[OPpixIdx] = input[IPpixIdx];
}
else
{
for(int i = -1; i <= 1; i++)
{
for(int j = -1; j <= 1; j++)
{
if(id_x != 0 && id_x != width - 1 && id_y != 0 && id_y != height -1)
{
unsigned long index = (unsigned long)IPpixIdx + (unsigned long)j + ((unsigned long)i * (unsigned long)width);
if(input[index] == 255)
{
output[OPpixIdx] = 255;
break;
}
}
}
}
}
}
RppStatus hip_exec_canny_ced_pln3_to_pln1(Rpp8u *srcPtr, Rpp8u *gsin, Rpp32u height, Rpp32u width, rpp::Handle& handle, Rpp32u channel)
{
int localThreads_x = 32;
int localThreads_y = 32;
int localThreads_z = 1;
int globalThreads_x = width;
int globalThreads_y = height;
int globalThreads_z = 1;
hipLaunchKernelGGL(canny_ced_pln3_to_pln1,
dim3(ceil((float)globalThreads_x/localThreads_x), ceil((float)globalThreads_y/localThreads_y), ceil((float)globalThreads_z/localThreads_z)),
dim3(localThreads_x, localThreads_y, localThreads_z),
0,
handle.GetStream(),
srcPtr,
gsin,
height,
width,
channel);
return RPP_SUCCESS;
}
RppStatus hip_exec_canny_ced_pkd3_to_pln1(Rpp8u *srcPtr, Rpp8u *gsin, Rpp32u height, Rpp32u width, rpp::Handle& handle, Rpp32u channel)
{
int localThreads_x = 32;
int localThreads_y = 32;
int localThreads_z = 1;
int globalThreads_x = width;
int globalThreads_y = height;
int globalThreads_z = 1;
hipLaunchKernelGGL(canny_ced_pkd3_to_pln1,
dim3(ceil((float)globalThreads_x/localThreads_x), ceil((float)globalThreads_y/localThreads_y), ceil((float)globalThreads_z/localThreads_z)),
dim3(localThreads_x, localThreads_y, localThreads_z),
0,
handle.GetStream(),
srcPtr,
gsin,
height,
width,
channel);
return RPP_SUCCESS;
}
RppStatus hip_exec_canny_ced_pln1_to_pkd3(Rpp8u *gsout, Rpp8u *dstPtr, Rpp32u height, Rpp32u width, rpp::Handle& handle, Rpp32u channel)
{
int localThreads_x = 32;
int localThreads_y = 32;
int localThreads_z = 1;
int globalThreads_x = width;
int globalThreads_y = height;
int globalThreads_z = 1;
hipLaunchKernelGGL(canny_ced_pln1_to_pkd3,
dim3(ceil((float)globalThreads_x/localThreads_x), ceil((float)globalThreads_y/localThreads_y), ceil((float)globalThreads_z/localThreads_z)),
dim3(localThreads_x, localThreads_y, localThreads_z),
0,
handle.GetStream(),
gsout,
dstPtr,
height,
width,
channel);
return RPP_SUCCESS;
}
RppStatus hip_exec_canny_ced_pln1_to_pln3(Rpp8u *gsout, Rpp8u *dstPtr, Rpp32u height, Rpp32u width, rpp::Handle& handle, Rpp32u channel)
{
int localThreads_x = 32;
int localThreads_y = 32;
int localThreads_z = 1;
int globalThreads_x = width;
int globalThreads_y = height;
int globalThreads_z = 1;
hipLaunchKernelGGL(canny_ced_pln1_to_pln3,
dim3(ceil((float)globalThreads_x/localThreads_x), ceil((float)globalThreads_y/localThreads_y), ceil((float)globalThreads_z/localThreads_z)),
dim3(localThreads_x, localThreads_y, localThreads_z),
0,
handle.GetStream(),
gsout,
dstPtr,
height,
width,
channel);
return RPP_SUCCESS;
}
RppStatus hip_exec_ced_non_max_suppression(Rpp8u *srcPtr, Rpp8u *sobelX, Rpp8u *sobelY, Rpp8u *dstPtr, Rpp32u height, Rpp32u width, rpp::Handle& handle, Rpp32u channel, Rpp32s i)
{
int localThreads_x = 32;
int localThreads_y = 32;
int localThreads_z = 1;
int globalThreads_x = width;
int globalThreads_y = height;
int globalThreads_z = 1;
hipLaunchKernelGGL(ced_non_max_suppression,
dim3(ceil((float)globalThreads_x/localThreads_x), ceil((float)globalThreads_y/localThreads_y), ceil((float)globalThreads_z/localThreads_z)),
dim3(localThreads_x, localThreads_y, localThreads_z),
0,
handle.GetStream(),
srcPtr,
sobelX,
sobelY,
dstPtr,
height,
width,
channel,
handle.GetInitHandle()->mem.mcpu.ucharArr[0].ucharmem[i],
handle.GetInitHandle()->mem.mcpu.ucharArr[1].ucharmem[i]);
return RPP_SUCCESS;
}
RppStatus hip_exec_canny_edge(Rpp8u *srcPtr, Rpp8u *dstPtr, Rpp32u height, Rpp32u width, rpp::Handle& handle, Rpp32u channel, Rpp32s i)
{
int localThreads_x = 32;
int localThreads_y = 32;
int localThreads_z = 1;
int globalThreads_x = width;
int globalThreads_y = height;
int globalThreads_z = 1;
hipLaunchKernelGGL(canny_edge,
dim3(ceil((float)globalThreads_x/localThreads_x), ceil((float)globalThreads_y/localThreads_y), ceil((float)globalThreads_z/localThreads_z)),
dim3(localThreads_x, localThreads_y, localThreads_z),
0,
handle.GetStream(),
srcPtr,
dstPtr,
height,
width,
channel,
handle.GetInitHandle()->mem.mcpu.ucharArr[0].ucharmem[i],
handle.GetInitHandle()->mem.mcpu.ucharArr[1].ucharmem[i]);
return RPP_SUCCESS;
} | 36.795571 | 178 | 0.499097 | shobana-mcw |
20c99886879623ac6c6683b1e64e4a062f1d7b4a | 3,424 | hpp | C++ | linux-x86/host/x86_64-linux-glibc2.11-4.6/x86_64-linux/include/c++/4.6/ext/pb_ds/detail/constructors_destructor_fn_imps.hpp | HelixOS/prebuilts-gcc | b678ca6f7f5494d9e0a4fd76064ccb4227241e48 | [
"Apache-2.0"
] | 112 | 2015-02-05T20:18:29.000Z | 2022-03-16T07:59:41.000Z | linux-x86/host/x86_64-linux-glibc2.11-4.6/x86_64-linux/include/c++/4.6/ext/pb_ds/detail/constructors_destructor_fn_imps.hpp | HelixOS/prebuilts-gcc | b678ca6f7f5494d9e0a4fd76064ccb4227241e48 | [
"Apache-2.0"
] | 9 | 2015-03-29T03:34:31.000Z | 2021-08-05T02:05:58.000Z | linux-x86/host/x86_64-linux-glibc2.11-4.6/x86_64-linux/include/c++/4.6/ext/pb_ds/detail/constructors_destructor_fn_imps.hpp | HelixOS/prebuilts-gcc | b678ca6f7f5494d9e0a4fd76064ccb4227241e48 | [
"Apache-2.0"
] | 51 | 2015-03-26T04:56:06.000Z | 2022-02-10T08:54:08.000Z | // -*- C++ -*-
// Copyright (C) 2005, 2006, 2009 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file constructors_destructor_fn_imps.hpp
* Contains constructors_destructor_fn_imps applicable to different containers.
*/
inline
PB_DS_CLASS_NAME()
{ }
inline
PB_DS_CLASS_NAME(const PB_DS_CLASS_NAME& other)
: base_type((const base_type&)other)
{ }
template<typename T0>
inline
PB_DS_CLASS_NAME(T0 t0) : base_type(t0)
{ }
template<typename T0, typename T1>
inline
PB_DS_CLASS_NAME(T0 t0, T1 t1) : base_type(t0, t1)
{ }
template<typename T0, typename T1, typename T2>
inline
PB_DS_CLASS_NAME(T0 t0, T1 t1, T2 t2) : base_type(t0, t1, t2)
{ }
template<typename T0, typename T1, typename T2, typename T3>
inline
PB_DS_CLASS_NAME(T0 t0, T1 t1, T2 t2, T3 t3)
: base_type(t0, t1, t2, t3)
{ }
template<typename T0, typename T1, typename T2, typename T3, typename T4>
inline
PB_DS_CLASS_NAME(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4)
: base_type(t0, t1, t2, t3, t4)
{ }
template<typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5>
inline
PB_DS_CLASS_NAME(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5)
: base_type(t0, t1, t2, t3, t4, t5)
{ }
template<typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6>
inline
PB_DS_CLASS_NAME(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6)
: base_type(t0, t1, t2, t3, t4, t5, t6)
{ }
template<typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7>
inline
PB_DS_CLASS_NAME(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7)
: base_type(t0, t1, t2, t3, t4, t5, t6, t7)
{ }
template<typename T0, typename T1, typename T2, typename T3, typename T4,
typename T5, typename T6, typename T7, typename T8>
inline
PB_DS_CLASS_NAME(T0 t0, T1 t1, T2 t2, T3 t3, T4 t4, T5 t5, T6 t6, T7 t7, T8 t8)
: base_type(t0, t1, t2, t3, t4, t5, t6, t7, t8)
{ }
| 32.923077 | 79 | 0.72868 | HelixOS |
20ccd2fede826b3d29e1aba3d5e679cb814a3688 | 6,628 | cpp | C++ | ModelGenerator/src/model_generator_tests.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | ModelGenerator/src/model_generator_tests.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | ModelGenerator/src/model_generator_tests.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2021 Adam Lafontaine
*/
#include "../src/ModelGenerator.hpp"
#include "../src/pixel_conversion.hpp"
#include "../../utils/dirhelper.hpp"
#include "../../utils/test_dir.hpp"
#include <string>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <cstdio>
namespace dir = dirhelper;
namespace gen = model_generator;
std::string src_fail_root;
std::string src_pass_root;
std::string data_fail_root;
std::string data_pass_root;
std::string model_root;
bool get_directories()
{
TestDirConfig config;
if (!config.has_all_keys())
return false;
src_fail_root = config.get(TestDir::SRC_FAIL_ROOT);
src_pass_root = config.get(TestDir::SRC_PASS_ROOT);
data_fail_root = config.get(TestDir::DATA_FAIL_ROOT);
data_pass_root = config.get(TestDir::DATA_PASS_ROOT);
model_root = config.get(TestDir::MODEL_ROOT);
return true;
}
const auto img_ext = ".png";
bool data_fail_exists_test();
bool data_pass_exists_test();
bool model_exists_test();
bool data_fail_files_test();
bool data_pass_files_test();
bool no_class_data_test();
bool add_class_data_test();
bool add_class_data_one_class_test();
bool purge_class_data_test();
bool save_model_no_data_test();
bool save_model_one_class_test();
bool save_model_one_file_test();
bool pixel_conversion_test();
bool save_model_active_test();
int main()
{
const auto run_test = [&](const char* name, const auto& test)
{ std::cout << name << ": " << (test() ? "Pass" : "Fail") << '\n'; };
if (!get_directories())
{
std::cout << "Failed to get directories from configuration file\n";
return EXIT_FAILURE;
}
run_test("data_fail_exists_test() dir exists", data_fail_exists_test);
run_test("data_pass_exists_test() dir exists", data_pass_exists_test);
run_test("model_exists_test() dir exists", model_exists_test);
run_test("data_fail_files_test() files exist", data_fail_files_test);
run_test("data_pass_files_test() files exist", data_pass_files_test);
run_test("no_class_data_test() ", no_class_data_test);
run_test("add_class_data_test() ", add_class_data_test);
run_test("add_class_data_one_class_test() ", add_class_data_one_class_test);
run_test("purge_class_data_test() ", purge_class_data_test);
run_test("save_model_no_data_test() ", save_model_no_data_test);
run_test("save_model_one_class_test() ", save_model_one_class_test);
run_test("save_model_one_file_test() ", save_model_one_file_test);
run_test("save_model_active_test() ", save_model_active_test);
run_test("pixel_conversion_test() ", pixel_conversion_test);
std::cout << "\nTests complete.";
}
//======= HELPERS =================
bool is_directory(std::string const& path)
{
return fs::exists(path) && fs::is_directory(path);
}
bool image_files_exist(std::string const& dir)
{
return dir::get_files_of_type(dir, img_ext).size() > 0;
}
void delete_files(std::string const& dir)
{
for (auto const& entry : fs::directory_iterator(dir))
{
fs::remove_all(entry);
}
}
//======= TESTS ==============
bool data_fail_exists_test()
{
return is_directory(data_fail_root);
}
bool data_pass_exists_test()
{
return is_directory(data_pass_root);
}
bool model_exists_test()
{
return is_directory(model_root);
}
bool data_fail_files_test()
{
return image_files_exist(data_fail_root);
}
bool data_pass_files_test()
{
return image_files_exist(data_pass_root);
}
// detect if data has not yet been added
bool no_class_data_test()
{
gen::ModelGenerator gen;
return !gen.has_class_data();
}
// data present after adding
bool add_class_data_test()
{
gen::ModelGenerator gen;
gen.add_class_data(data_pass_root.c_str(), MLClass::Pass);
gen.add_class_data(data_fail_root.c_str(), MLClass::Fail);
return gen.has_class_data();
}
// has_class_data() returns false if not all classes have data
bool add_class_data_one_class_test()
{
gen::ModelGenerator gen;
gen.add_class_data(data_pass_root.c_str(), MLClass::Pass);
return !gen.has_class_data();
}
// no class data after purging
bool purge_class_data_test()
{
gen::ModelGenerator gen;
gen.add_class_data(data_pass_root.c_str(), MLClass::Pass);
gen.add_class_data(data_fail_root.c_str(), MLClass::Fail);
gen.purge_class_data();
return !gen.has_class_data();
}
// no model file is created when no class data is available
bool save_model_no_data_test()
{
delete_files(model_root);
gen::ModelGenerator gen;
gen.save_model(model_root.c_str());
return dir::get_files_of_type(model_root, img_ext).empty();
}
// all classes need to have data before a model file is created
bool save_model_one_class_test()
{
delete_files(model_root);
gen::ModelGenerator gen;
gen.add_class_data(data_pass_root.c_str(), MLClass::Pass);
gen.save_model(model_root.c_str());
return dir::get_files_of_type(model_root, img_ext).empty();
}
// one file is created when generating a model
bool save_model_one_file_test()
{
delete_files(model_root);
gen::ModelGenerator gen;
gen.add_class_data(data_pass_root.c_str(), MLClass::Pass);
gen.add_class_data(data_fail_root.c_str(), MLClass::Fail);
gen.save_model(model_root.c_str());
return dir::get_files_of_type(model_root, img_ext).size() == 1;;
}
// at least one item in centroid is flagged as active
bool save_model_active_test()
{
// make sure a model file exists
if (!save_model_one_file_test())
return false;
const auto model_file = dir::get_files_of_type(model_root, img_ext)[0];
img::image_t model;
img::read_image_from_file(model_file, model);
const auto view = img::make_view(model);
unsigned active_count = 0;
const auto row = img::row_view(view, 0);
auto ptr = row.row_begin(0);
for (u32 x = 0; x < row.width; ++x)
{
const auto value = gen::model_pixel_to_model_value(ptr[x]);
active_count += gen::is_relevant(value);
}
return active_count > 0;
}
// convert back and forth between model pixels and values
bool pixel_conversion_test()
{
// make sure a model file exists
if (!save_model_one_file_test())
return false;
const auto model_file = dir::get_files_of_type(model_root, img_ext)[0];
img::image_t model;
img::read_image_from_file(model_file, model);
const auto view = img::make_view(model);
const auto row = img::row_view(view, 0);
auto ptr = row.row_begin(0);
for (u32 x = 0; x < row.width; ++x)
{
const auto value = gen::model_pixel_to_model_value(ptr[x]);
if (!gen::is_relevant(value))
continue;
const auto pixel = gen::model_value_to_model_pixel(value);
if (gen::model_pixel_to_model_value(pixel) != value)
return false;
}
return true;
} | 22.855172 | 80 | 0.731895 | adam-lafontaine |
20ce6819d592761e28249c76c99e406d9b1d64ca | 1,426 | cpp | C++ | cpp/arc054_b/main.cpp | kokosabu/atcoder | 8d512587d234eb45941a2f6341c4dd003e6c9ad3 | [
"Apache-2.0"
] | null | null | null | cpp/arc054_b/main.cpp | kokosabu/atcoder | 8d512587d234eb45941a2f6341c4dd003e6c9ad3 | [
"Apache-2.0"
] | null | null | null | cpp/arc054_b/main.cpp | kokosabu/atcoder | 8d512587d234eb45941a2f6341c4dd003e6c9ad3 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
long double P;
cin >> P;
long double left = 0;
long double right = P;
long double max = P;
//while((right-left) < 0.000000001) {
long double before = P;
//for(int i = 0; i < 1000; i++) {
while((right-left) > 0.000000000000001) {
long double mid = (left + right) / 2;
long double x1 = (left * 2 + right) / 3;
long double x2 = (left + right * 2) / 3;
long double time1 = x1 + pow(2.0, -x1/1.5)*P;
long double time2 = mid + pow(2.0, -mid/1.5)*P;
long double time3 = x2 + pow(2.0, -x2/1.5)*P;
//long double time1 = left + pow(2.0, -left/1.5)*P;
//long double time2 = mid + pow(2.0, -mid/1.5)*P;
//long double time3 = right + pow(2.0, -right/1.5)*P;
//long double time = mid + P / powl(2.0, mid/1.5);
//cout << time1 << ", " << time3 << endl;
if(time1 < time3) {
right = x2;
} else {
left = x1;
}
//if(time > before) {
//if(time < max) {
// max = time;
// left = mid;
//} else {
// right = mid;
//}
//before = time;
//cout << left << ", " << right << "," << time2 << endl;
max = time2;
}
cout << std::fixed << std::setprecision(12) << max << endl;
return 0;
}
| 26.407407 | 64 | 0.463534 | kokosabu |
20cfddaafc69172e6bfe621cc5d77802b557bf0c | 315 | hpp | C++ | library/ATF/PIMAGE_RESOURCE_DIRECTORY_ENTRY.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/PIMAGE_RESOURCE_DIRECTORY_ENTRY.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/PIMAGE_RESOURCE_DIRECTORY_ENTRY.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_IMAGE_RESOURCE_DIRECTORY_ENTRY.hpp>
START_ATF_NAMESPACE
typedef _IMAGE_RESOURCE_DIRECTORY_ENTRY *PIMAGE_RESOURCE_DIRECTORY_ENTRY;
END_ATF_NAMESPACE
| 28.636364 | 108 | 0.828571 | lemkova |
20d0ec7f70f575369ab03c9eb8e0c00aac6c65dd | 17,083 | cpp | C++ | tests/one/arcus/arcus.cpp | i3D-net/ONE-GameHosting-SDK | 060473173136b2c8d9bc43aaad0eb487870dc115 | [
"BSD-3-Clause"
] | 6 | 2020-07-03T09:18:04.000Z | 2021-01-07T17:50:06.000Z | tests/one/arcus/arcus.cpp | i3D-net/ONE-GameHosting-SDK | 060473173136b2c8d9bc43aaad0eb487870dc115 | [
"BSD-3-Clause"
] | null | null | null | tests/one/arcus/arcus.cpp | i3D-net/ONE-GameHosting-SDK | 060473173136b2c8d9bc43aaad0eb487870dc115 | [
"BSD-3-Clause"
] | null | null | null | #include <catch.hpp>
#include <tests/one/arcus/util.h>
#include <functional>
#include <utility>
#include <one/arcus/array.h>
#include <one/arcus/internal/codec.h>
#include <one/arcus/internal/connection.h>
#include <one/arcus/internal/socket.h>
#include <one/arcus/internal/version.h>
#include <one/arcus/error.h>
#include <one/arcus/message.h>
#include <one/arcus/object.h>
#include <one/arcus/opcode.h>
#include <one/arcus/c_platform.h>
#include <one/arcus/types.h>
using namespace i3d::one;
TEST_CASE("current arcus version", "[arcus]") {
REQUIRE(arcus_protocol::current_version() == ArcusVersion::V2);
}
TEST_CASE("opcode version V2 validation", "[arcus]") {
REQUIRE(is_opcode_supported_v2(Opcode::health));
REQUIRE(is_opcode_supported_v2(Opcode::hello));
REQUIRE(is_opcode_supported_v2(Opcode::soft_stop));
REQUIRE(is_opcode_supported_v2(Opcode::allocated));
REQUIRE(is_opcode_supported_v2(Opcode::metadata));
REQUIRE(is_opcode_supported_v2(Opcode::reverse_metadata));
REQUIRE(is_opcode_supported_v2(Opcode::host_information));
REQUIRE(is_opcode_supported_v2(Opcode::application_instance_information));
REQUIRE(is_opcode_supported_v2(Opcode::application_instance_status));
REQUIRE(is_opcode_supported_v2(Opcode::custom_command));
REQUIRE(is_opcode_supported_v2(Opcode::invalid) == false);
}
TEST_CASE("opcode current version validation", "[arcus]") {
REQUIRE(is_opcode_supported(Opcode::health));
REQUIRE(is_opcode_supported(Opcode::hello));
REQUIRE(is_opcode_supported(Opcode::soft_stop));
REQUIRE(is_opcode_supported(Opcode::allocated));
REQUIRE(is_opcode_supported(Opcode::metadata));
REQUIRE(is_opcode_supported(Opcode::reverse_metadata));
REQUIRE(is_opcode_supported(Opcode::host_information));
REQUIRE(is_opcode_supported(Opcode::application_instance_information));
REQUIRE(is_opcode_supported(Opcode::application_instance_status));
REQUIRE(is_opcode_supported(Opcode::custom_command));
REQUIRE(is_opcode_supported(Opcode::invalid) == false);
}
//------------------------------------------------------------------------------
// Message tests.
TEST_CASE("message handling", "[arcus]") {
Message m;
const String payload = "{\"timeout\":1000}";
REQUIRE(!is_error(m.init(Opcode::soft_stop, {payload.c_str(), payload.size()})));
REQUIRE(m.code() == Opcode::soft_stop);
REQUIRE(m.payload().is_empty() == false);
REQUIRE(is_error(m.init(Opcode::soft_stop, {nullptr, 0})));
m.reset();
REQUIRE(m.code() == Opcode::invalid);
REQUIRE(m.payload().is_empty());
REQUIRE(!is_error(m.init(Opcode::soft_stop, {"{}", 2})));
REQUIRE(m.code() == Opcode::soft_stop);
REQUIRE(m.payload().is_empty());
m.reset();
REQUIRE(m.code() == Opcode::invalid);
REQUIRE(m.payload().is_empty());
}
//------------------------------------------------------------------------------
// Socket and Connection tests.
void wait_ready_for_read(Socket &socket) {
bool is_ready;
REQUIRE(!is_error(socket.ready_for_read(0.1f, is_ready)));
REQUIRE(is_ready);
};
void wait_ready_for_send(Socket &socket) {
bool is_ready;
REQUIRE(!is_error(socket.ready_for_send(0.1f, is_ready)));
REQUIRE(is_ready);
};
void listen(Socket &server, unsigned int &port) {
REQUIRE(!is_error(server.init()));
REQUIRE(!is_error(server.bind(0)));
String server_ip;
REQUIRE(!is_error(server.address(server_ip, port)));
REQUIRE(server_ip.length() > 0);
REQUIRE(port != 0);
REQUIRE(!is_error(server.listen(1)));
}
void connect(Socket &client, unsigned int port) {
client.init();
REQUIRE(!is_error(client.connect("127.0.0.1", port)));
}
void accept(Socket &server, Socket &in_client) {
// Accept client on server.
wait_ready_for_read(server);
String client_ip;
unsigned int client_port;
REQUIRE(!is_error(server.accept(in_client, client_ip, client_port)));
REQUIRE(client_ip.length() > 0);
REQUIRE(client_port != 0);
}
// Socket and Connection normal external behavior.
TEST_CASE("connection", "[arcus]") {
init_socket_system();
Socket server;
//-----------
// Lifecycle.
REQUIRE(server.is_initialized() == false);
REQUIRE(!is_error(server.init()));
REQUIRE(server.is_initialized() == true);
REQUIRE(!is_error(server.close()));
REQUIRE(server.is_initialized() == false);
//---------------
// Server listen.
unsigned int server_port;
listen(server, server_port);
#ifdef ONE_WINDOWS // On linux, listen may succeed even if already listened on.
// Confirm a second server listen on same port fails appropriately.
{
Socket server_b;
REQUIRE(!is_error(server_b.init()));
REQUIRE(server_b.bind(server_port) == ONE_ERROR_SOCKET_BIND_FAILED);
}
#endif
// Confirm no incoming connections.
Socket in_client;
String client_ip;
unsigned int client_port;
REQUIRE(!is_error(server.accept(in_client, client_ip, client_port)));
REQUIRE(in_client.is_initialized() == false);
//--------------------------
// Client connect to server.
// Init client socket.
Socket out_client;
connect(out_client, server_port);
// Accept client on server.
accept(server, in_client);
//------------------
// Send and receive.
// Send to server.
wait_ready_for_send(out_client);
const unsigned char out_data = 'a';
size_t sent = 0;
auto result = out_client.send(&out_data, 1, sent);
REQUIRE(!is_error(result));
REQUIRE(sent == 1);
// Receive on accepted server-side client socket.
wait_ready_for_read(in_client);
unsigned char in_data[128] = {0};
size_t received = 0;
result = in_client.receive(in_data, 128, received);
REQUIRE(!is_error(result));
REQUIRE(received == 1);
REQUIRE(in_data[0] == out_data);
//-------------
// Handshaking.
// Arcus connections around the server-side and client-side sockets that
// are connected to each other.
Connection server_connection(2, 2);
server_connection.init(in_client);
Connection client_connection(2, 2);
client_connection.init(out_client);
server_connection.initiate_handshake();
for (auto i = 0; i < 10; ++i) {
REQUIRE(server_connection.update() == ONE_ERROR_NONE);
REQUIRE(client_connection.update() == ONE_ERROR_NONE);
sleep(10);
if (server_connection.status() == Connection::Status::ready &&
client_connection.status() == Connection::Status::ready)
break;
}
REQUIRE(server_connection.status() == Connection::Status::ready);
REQUIRE(client_connection.status() == Connection::Status::ready);
// After handshake, the connection is ready to send and receive only
// Messages. Sending an invalid message should result in a error on server
// connection.
wait_ready_for_send(out_client);
// Send at last the size of a full message header or else the data will
// just wait in incoming buffer and be be processed.
const unsigned char bad_data[codec::header_size()] = {0xF};
auto err = out_client.send(&bad_data, codec::header_size(), sent);
REQUIRE(!is_error(err));
REQUIRE(sent == codec::header_size());
bool received_bad_header_error = false;
for_sleep(10, 10, [&]() {
err = server_connection.update();
// The update may succeed if the message isn't read during this update,
// or it should fail with the invalid message code.
received_bad_header_error =
received_bad_header_error || (err == ONE_ERROR_CODEC_INVALID_HEADER);
const bool is_expected =
(err == ONE_ERROR_CODEC_INVALID_HEADER) || (err == ONE_ERROR_NONE);
REQUIRE(is_expected);
if (server_connection.status() == Connection::Status::error) return true;
return false;
});
REQUIRE(received_bad_header_error);
REQUIRE(server_connection.status() == Connection::Status::error);
server.close();
out_client.close();
in_client.close();
shutdown_socket_system();
}
struct ClientServerTestObjects {
Socket server;
Socket out_client;
Socket in_client;
Connection *server_connection;
Connection *client_connection;
unsigned int server_port;
};
void init_client_server_test(ClientServerTestObjects &objects,
size_t message_queue_length) {
init_socket_system();
listen(objects.server, objects.server_port);
connect(objects.out_client, objects.server_port);
accept(objects.server, objects.in_client);
objects.server_connection =
new Connection(message_queue_length, message_queue_length);
objects.server_connection->init(objects.in_client);
objects.client_connection =
new Connection(message_queue_length, message_queue_length);
objects.client_connection->init(objects.out_client);
}
void shutdown_client_server_test(ClientServerTestObjects &objects) {
delete objects.server_connection;
delete objects.client_connection;
objects.server.close();
objects.out_client.close();
objects.in_client.close();
shutdown_socket_system();
}
void handshake_client_server_test(ClientServerTestObjects &objects) {
objects.server_connection->initiate_handshake();
for_sleep(10, 1, [&]() {
REQUIRE(!is_error(objects.server_connection->update()));
REQUIRE(!is_error(objects.client_connection->update()));
if (objects.server_connection->status() == Connection::Status::ready &&
objects.client_connection->status() == Connection::Status::ready)
return true;
return false;
});
REQUIRE(objects.server_connection->status() == Connection::Status::ready);
REQUIRE(objects.client_connection->status() == Connection::Status::ready);
}
TEST_CASE("handshake early hello", "[arcus]") {
ClientServerTestObjects objects;
init_client_server_test(objects, 2);
objects.server_connection->initiate_handshake();
wait_ready_for_send(objects.out_client);
codec::Hello hello = codec::valid_hello();
size_t sent = 0;
auto result = objects.out_client.send(&hello, codec::hello_size(), sent);
REQUIRE(!is_error(result));
REQUIRE(sent == codec::hello_size());
auto err = ONE_ERROR_NONE;
for (int i = 0; i < 5; i++) {
err = objects.server_connection->update();
if (is_error(err)) break;
sleep(10);
}
REQUIRE(is_error(err));
shutdown_client_server_test(objects);
}
TEST_CASE("handshake hello bad response", "[arcus]") {
ClientServerTestObjects objects;
init_client_server_test(objects, 2);
// Wait for server to enter sent state.
objects.server_connection->initiate_handshake();
for (int i = 0; i < 10; i++) {
REQUIRE(!is_error(objects.server_connection->update()));
if (objects.server_connection->status() ==
Connection::Status::handshake_hello_sent) {
break;
}
sleep(1);
}
REQUIRE(objects.server_connection->status() ==
Connection::Status::handshake_hello_sent);
// Receive the hello from server.
codec::Hello hello = {0};
size_t received = 0;
auto result = objects.out_client.receive(&hello, codec::hello_size(), received);
REQUIRE(!is_error(result));
REQUIRE(received == codec::hello_size());
REQUIRE(codec::validate_hello(hello));
// Send wrong opcode back.
static codec::Header hello_header = {0};
hello_header.opcode = static_cast<char>(Opcode::soft_stop);
size_t sent = 0;
result = objects.out_client.send(&hello_header, codec::header_size(), sent);
REQUIRE(!is_error(result));
REQUIRE(sent == codec::header_size());
// Ensure the server connection enters an error state.
OneError err;
for (int i = 0; i < 10; i++) {
err = (objects.server_connection->update());
if (is_error(err)) {
break;
}
sleep(1);
}
REQUIRE(err == ONE_ERROR_CONNECTION_HELLO_MESSAGE_REPLY_INVALID);
shutdown_client_server_test(objects);
}
//--------------------------
// Test - handshake timeout.
TEST_CASE("handshake timeout", "[arcus]") {}
//--------------------------------
// Message send and receive tests.
TEST_CASE("message send and receive", "[arcus]") {
ClientServerTestObjects objects;
constexpr size_t queue_length = 1024;
init_client_server_test(objects, queue_length);
handshake_client_server_test(objects);
// Ensure no messages waiting anywhere.
unsigned int count = 0;
REQUIRE(!is_error(objects.server_connection->incoming_count(count)));
REQUIRE(count == 0);
REQUIRE(!is_error(objects.client_connection->incoming_count(count)));
REQUIRE(count == 0);
auto err = objects.server_connection->remove_incoming(
[](const Message &) { return ONE_ERROR_NONE; });
REQUIRE(err == ONE_ERROR_CONNECTION_QUEUE_EMPTY);
err = objects.client_connection->remove_incoming(
[](const Message &) { return ONE_ERROR_NONE; });
REQUIRE(err == ONE_ERROR_CONNECTION_QUEUE_EMPTY);
// Send a message from client to server.
Message message;
messages::prepare_soft_stop(1000, message);
err = objects.client_connection->add_outgoing(message);
const auto pump_messages = [&]() {
for_sleep(10, 1, [&]() {
REQUIRE(!is_error(objects.server_connection->update()));
REQUIRE(!is_error(objects.client_connection->update()));
return false;
});
};
pump_messages();
// Check it on server.
REQUIRE(!is_error(objects.server_connection->incoming_count(count)));
REQUIRE(count == 1);
// Message pointer was consumed by client connection, can re-use var safely without
// leak.
err = objects.server_connection->remove_incoming([](const Message &message) {
REQUIRE(message.code() == Opcode::soft_stop);
int timeout = 0;
REQUIRE(!is_error(message.payload().val_int("timeout", timeout)));
REQUIRE(timeout == 1000);
return ONE_ERROR_NONE;
});
REQUIRE(!is_error(err));
// Fill up the outgoing messages.
for (unsigned int i = 0; i < queue_length; ++i) {
Message message;
messages::prepare_soft_stop(1000, message);
err = objects.client_connection->add_outgoing(message);
REQUIRE(!is_error(err));
}
// Add one more message, which should not fit in the outgoing message queue.
Array array;
messages::prepare_allocated(array, message);
err = objects.client_connection->add_outgoing(message);
REQUIRE(err == ONE_ERROR_CONNECTION_OUTGOING_QUEUE_INSUFFICIENT_SPACE);
// Ensure server received the initial messages and not the dropped one.
pump_messages();
REQUIRE(!is_error(objects.server_connection->incoming_count(count)));
REQUIRE(count == queue_length);
for (unsigned int i = 0; i < queue_length; ++i) {
err = objects.server_connection->remove_incoming([](const Message &message) {
REQUIRE(message.code() == Opcode::soft_stop);
int timeout = 0;
REQUIRE(!is_error(message.payload().val_int("timeout", timeout)));
REQUIRE(timeout == 1000);
return ONE_ERROR_NONE;
});
REQUIRE(!is_error(err));
}
shutdown_client_server_test(objects);
}
TEST_CASE("message send bad json", "[arcus]") {
ClientServerTestObjects objects;
constexpr size_t queue_length = 1024;
init_client_server_test(objects, queue_length);
handshake_client_server_test(objects);
// Ensure no messages waiting anywhere.
unsigned int count = 0;
REQUIRE(!is_error(objects.server_connection->incoming_count(count)));
REQUIRE(count == 0);
REQUIRE(!is_error(objects.client_connection->incoming_count(count)));
REQUIRE(count == 0);
auto err = objects.server_connection->remove_incoming(
[](const Message &) { return ONE_ERROR_NONE; });
REQUIRE(err == ONE_ERROR_CONNECTION_QUEUE_EMPTY);
err = objects.client_connection->remove_incoming(
[](const Message &) { return ONE_ERROR_NONE; });
REQUIRE(err == ONE_ERROR_CONNECTION_QUEUE_EMPTY);
// Send a message from client to server.
const String invalid_json = "{\"invalid_json\":true";
Message message;
err = message.init(Opcode::metadata, {invalid_json.c_str(), invalid_json.size()});
err = objects.client_connection->add_outgoing(message);
const auto pump_messages = [&]() {
for_sleep(10, 1, [&]() {
REQUIRE(!is_error(objects.server_connection->update()));
auto error = objects.client_connection->update();
if (is_error(error)) {
REQUIRE(error == ONE_ERROR_CODEC_INVALID_HEADER);
return true;
}
return false;
});
};
pump_messages();
// Check it on server.
REQUIRE(!is_error(objects.server_connection->incoming_count(count)));
REQUIRE(count == 0);
shutdown_client_server_test(objects);
}
| 35.295455 | 87 | 0.667447 | i3D-net |
20d5b08375dcb27748e86b9323cc50884bb0e90b | 84 | cpp | C++ | src/test/unit/multiple_translation_units1.cpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | 1 | 2019-07-05T01:40:40.000Z | 2019-07-05T01:40:40.000Z | src/test/unit/multiple_translation_units1.cpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | null | null | null | src/test/unit/multiple_translation_units1.cpp | drezap/stan | 9b319ed125e2a7d14d0c9c246d2f462dad668537 | [
"BSD-3-Clause"
] | 1 | 2018-08-28T12:09:08.000Z | 2018-08-28T12:09:08.000Z | #include <stan/model/model_header.hpp>
stan::math::var function1() {
return 0;
}
| 14 | 38 | 0.690476 | drezap |
20d603ef9954fc79b5eb3e03dd4911a8b7d6748c | 2,138 | hpp | C++ | include/hogl/detail/internal.hpp | maxk-org/hogl | 07a714da00075125cbf930bfacb59645493ad313 | [
"BSD-2-Clause"
] | 14 | 2015-08-25T20:17:16.000Z | 2021-08-24T11:28:02.000Z | include/hogl/detail/internal.hpp | maxk-org/hogl | 07a714da00075125cbf930bfacb59645493ad313 | [
"BSD-2-Clause"
] | 8 | 2016-06-15T16:49:01.000Z | 2019-10-05T19:12:12.000Z | include/hogl/detail/internal.hpp | maxk-org/hogl | 07a714da00075125cbf930bfacb59645493ad313 | [
"BSD-2-Clause"
] | 6 | 2015-09-30T00:00:12.000Z | 2021-08-02T20:43:56.000Z | /*
Copyright (c) 2015-2020 Max Krasnyansky <max.krasnyansky@gmail.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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file hogl/detail/internal.h
* Internal parts (log areas and sections, etc)
*/
#ifndef HOGL_DETAIL_INTERNAL_HPP
#define HOGL_DETAIL_INTERNAL_HPP
#include <hogl/detail/compiler.hpp>
#include <stdint.h>
#include <time.h>
__HOGL_PRIV_NS_OPEN__
namespace hogl {
namespace internal {
/**
* Internal section ids
*/
enum section_ids {
INFO,
WARN,
ERROR,
DROPMARK,
TSOFULLMARK,
ENGINE_DEBUG,
AREA_DEBUG,
RING_DEBUG,
TLS_DEBUG
};
/**
* Internal section names
*/
extern const char *section_names[];
/**
* Internal special record types
*/
enum special_records {
SPR_FLUSH,
SPR_TIMESOURCE_CHANGE
};
} // namespace internal
} // namespace hogl
__HOGL_PRIV_NS_CLOSE__
#endif // HOGL_DETAIL_INTERNAL_HPP
| 27.063291 | 85 | 0.755847 | maxk-org |
20dc8fe5a109dfa4788a33421220bbac0dfb05c7 | 19,172 | cpp | C++ | src/main.cpp | mcleary/GentlemansBattle | daf7d702d4259972f500af07921937c47b20b9b2 | [
"MIT"
] | null | null | null | src/main.cpp | mcleary/GentlemansBattle | daf7d702d4259972f500af07921937c47b20b9b2 | [
"MIT"
] | null | null | null | src/main.cpp | mcleary/GentlemansBattle | daf7d702d4259972f500af07921937c47b20b9b2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include <fstream>
#include <vector>
#include <string>
struct ModelInput
{
double start_army_size; // > 0 Tamanho inicial do exército
double start_enemy_size; // > 0 Tamanho inicial do exército inimigo
double loose_battle_fraction; // 0 < x < 1: Porcentagem do exército que define derrota
double army_skill; // 0 < x <= 1 Perícia do exército em eliminar inimigos
double enemy_skill; // 0 < x <= 1 Perícia do inimigo em eliminar o exército
double start_ammo; // > 0 Quantidade de munição que estará disponível durante a batalha
double army_fire_rate; // 0 < x <= 1 Taxa com que o exército consegue atirar a munição disponível
double ammo_diffusion_coeffient; // > 0 Velocidade com o que a munição é distribuída para o exército
double formation_size; // > 0 Tamanho da formação utilizada na batalha pelo exército
double front_line_fraction; // 0 < x <= 1 Porcentagem do exército que atuará na linha de frente
double enemy_front_line_fraction; // 0 < x <= 1 Porcentagem do exército inimigo que atuará na linha de frente
double delta_time; // > 0
double delta_x; // > 0
/**
* @brief ModelInputData default input data
*/
ModelInput()
{
start_army_size = 500.0;
start_enemy_size = 500.0;
loose_battle_fraction = 0.01;
army_skill = 0.03;
enemy_skill = 0.01;
start_ammo = 1000;
army_fire_rate = 0.05;
ammo_diffusion_coeffient = 0.8;
formation_size = 7;
front_line_fraction = 0.1;
enemy_front_line_fraction = 0.1;
delta_time = 0.07;
delta_x = 0.6;
std::cout << "CFL = " << ammo_diffusion_coeffient * delta_time / (delta_x * delta_x) << std::endl;
}
friend std::ostream& operator<< (std::ostream& out, const ModelInput& input_data)
{
out << "#-------------------------------------------------" << std::endl;
out << "#--- GentlesmanBattle Input Data" << std::endl;
out << "#-------------------------------------------------" << std::endl;
out << "#- Start Army Size : " << input_data.start_army_size << std::endl;
out << "#- Start Enemy Size : " << input_data.start_enemy_size << std::endl;
out << "#- Army Skill : " << input_data.army_skill << std::endl;
out << "#- Enemy Skill : " << input_data.enemy_skill << std::endl;
out << "#- Start Ammo : " << input_data.start_ammo << std::endl;
out << "#- Ammo Diffusion Coef: " << input_data.ammo_diffusion_coeffient << std::endl;
out << "#- Battle Field Size : " << input_data.formation_size << std::endl;
out << "#- Front Line Fraction: " << input_data.front_line_fraction << std::endl;
out << "#- Delta Time : " << input_data.delta_time << std::endl;
out << "#- Delta X : " << input_data.delta_x << std::endl;
out << "#--------------------------------------------------" << std::endl;
return out;
}
};
struct ModelInfo
{
double time = 0.0;
double new_army_size = 0.0;
double old_army_size = 0.0;
double new_enemy_size = 0.0;
double old_enemy_size = 0.0;
std::vector<double> new_ammo_amount;
std::vector<double> old_ammo_amount;
const ModelInput& model_input;
double CFL = 0.0;
ModelInfo(const ModelInput& input_data) :
model_input(input_data)
{
}
void update_input()
{
// Setting up the mesh for the ammo diffusion
new_ammo_amount.resize(static_cast<int>(model_input.formation_size / model_input.delta_x));
old_ammo_amount.resize(new_ammo_amount.size());
// Initial condition
old_army_size = model_input.start_army_size;
old_enemy_size = model_input.start_enemy_size;
// Ammot starts at rear-line
old_ammo_amount[1] = model_input.start_ammo;
CFL = model_input.ammo_diffusion_coeffient * model_input.delta_time / (model_input.delta_x * model_input.delta_x);
}
void advance_time()
{
// Calculates the fraction of the army and enemies currently standing in the front-line
double front_line_size = model_input.front_line_fraction * old_army_size;
double enemy_front_line_size = model_input.front_line_fraction * old_enemy_size;
// Army
new_army_size = old_army_size - model_input.delta_time * model_input.enemy_skill * front_line_size * enemy_front_line_size;
old_army_size = new_army_size;
// Enemy
double shoots_fired = old_ammo_amount.back() * model_input.army_fire_rate;
new_enemy_size = old_enemy_size - model_input.delta_time * model_input.army_skill * shoots_fired * front_line_size * enemy_front_line_size;
old_enemy_size = new_enemy_size;
// Ammo Diffusion
for(size_t i = 1; i < new_ammo_amount.size() - 1; ++i)
{
new_ammo_amount[i] = old_ammo_amount[i] + CFL * (old_ammo_amount[i-1] - 2.0 * old_ammo_amount[i] + old_ammo_amount[i+1]);
}
//
// Ammo boundary conditions
//
// At x=0 there is no flow.
new_ammo_amount[0] = new_ammo_amount[1];
// At x=L the ammo is being used by the soldiers
// Calculates the percentage of ammo used at the frontline.
double ammo_usage_ratio = 1.0 - (1.0 / front_line_size);
new_ammo_amount.back() = new_ammo_amount[new_ammo_amount.size() - 2] * ammo_usage_ratio;
// Swap vectors for next time step
new_ammo_amount.swap(old_ammo_amount);
// Finally, advance the time
time += model_input.delta_time;
}
/**
* @brief True if the battle has came to an end
*
* The condition for the battle to stop is when the army size reaches a fraction defined
* by @ref ModelInputData::loose_battle_fraction. The condition is applied for both the army
* and the enemies.
*
* @return True if the battle has came to an end false otherwise
*/
bool should_stop() const
{
return new_army_size <= model_input.start_army_size * model_input.loose_battle_fraction ||
new_enemy_size <= model_input.start_enemy_size * model_input.loose_battle_fraction;
}
/**
* @brief Returns true if the number of soldiers is bigger than the number of enemies soldiers at this moment
*/
bool is_army_winning() const
{
return old_army_size > old_enemy_size;
}
friend std::ostream& operator<< (std::ostream& out, const ModelInfo& info)
{
out << "#-------------------------------------------------" << std::endl;
out << "#--- GentlesmanBattle Execution Summary" << std::endl;
out << "#-------------------------------------------------" << std::endl;
out << "# Number of Iterations : " << info.time / info.model_input.delta_time << std::endl;
out << "# Total time : " << info.time << std::endl;
out << "# Soldiers Count : " << info.new_army_size << std::endl;
out << "# Enemies Count : " << info.new_enemy_size << std::endl;
out << "# Available Ammo at Fronline: " << info.new_ammo_amount.back() << std::endl;
out << "# Available Ammo at Rearline: " << info.new_ammo_amount.front() << std::endl;
out << "#-------------------------------------------------" << std::endl;
out << "# Battle Result: ";
if(info.is_army_winning())
{
out << "YOU WIN!" << std::endl;
}
else
{
out << "YOU LOOSE!" << std::endl;
}
out << "#-------------------------------------------------" << std::endl;
return out;
}
};
struct ModelOutput
{
std::fstream output_file;
std::fstream phase_plane_file;
const ModelInput& model_input;
const ModelInfo& model_info;
const std::string prefix;
ModelOutput(const ModelInfo& _model_info, const ModelInput& _model_input, const std::string& _prefix = "")
: model_input(_model_input),
model_info(_model_info),
prefix(_prefix)
{
}
void start_execution()
{
output_file.open(prefix + "_gentlemans_battle.dat", std::ios::out);
output_file << model_input << std::endl << std::endl;
output_file << "# Time Army Enemy Rearguard Frontline " << std::endl;
}
void write_output_step()
{
output_file << std::setw(10) << std::setprecision(10) << std::fixed << std::setfill('0') <<
model_info.time << " " <<
model_info.old_army_size << " " <<
model_info.old_enemy_size << " " <<
model_info.old_ammo_amount.front() << " " <<
model_info.old_ammo_amount.back() << " " <<
std::endl;
}
void stop_execution(bool b_show_plots = true)
{
// Write Execution Summary into the output file
output_file << model_info << std::endl;
if(output_file.is_open())
{
output_file.close();
}
if(b_show_plots)
{
std::string output_filename_quotes = "'" + prefix + "_gentlemans_battle.dat'";
std::string gnuplot_reaction_script = prefix + "_gentlemans_battle_result.gnu";
std::string gnuplot_phase_plane_script = prefix + "_gentlemans_battle_phase_plane.gnu";
std::string gnuplot_diffusion_script = prefix + "_gentlemans_battle_diffusion.gnu";
const int title_font_size = 15;
{
std::fstream gnuplot_script_file(gnuplot_reaction_script, std::ios::out);
gnuplot_script_file << "set terminal 'wxt'" << std::endl;
gnuplot_script_file << "set xlabel 'Tempo'" << std::endl;
gnuplot_script_file << "set ylabel 'Número de Soldados'" << std::endl;
gnuplot_script_file << "set zeroaxis" << std::endl;
gnuplot_script_file << "set yrange [0:550]" << std::endl;
gnuplot_script_file << "set title 'Evolução do Número de Soldados no Campo de Batalha' font 'Arial, " << title_font_size << "'" << std::endl;
gnuplot_script_file << "plot " <<
output_filename_quotes << " using 1:2 with lines title 'Soldados'," <<
output_filename_quotes << " using 1:3 with lines title 'Inimigos' linetype rgb '#6f99c8'" << std::endl;
gnuplot_script_file << "set output 'report/figs/battle_reaction.png'" << std::endl;
gnuplot_script_file << "set terminal pngcairo enhanced font 'arial,10' fontscale 1.0" << std::endl;
gnuplot_script_file << "replot" << std::endl;
}
{
std::fstream gnuplot_script_file(gnuplot_diffusion_script, std::ios::out);
gnuplot_script_file << "set terminal 'wxt'" << std::endl;
gnuplot_script_file << "set xlabel 'Tempo'" << std::endl;
gnuplot_script_file << "set ylabel 'Concentração de Munição'" << std::endl;
gnuplot_script_file << "set zeroaxis" << std::endl;
gnuplot_script_file << "set title 'Munição nas linhas de frente e retarguarda' font 'Arial, " << title_font_size << "'" << std::endl;
gnuplot_script_file << "plot " <<
output_filename_quotes << " using 1:4 with lines title 'Retarguarda'," <<
output_filename_quotes << " using 1:5 with lines title 'Linha de frente' linetype rgb '#6f99c8'" << std::endl;
gnuplot_script_file << "set output 'report/figs/battle_ammo_diffusion.png'" << std::endl;
gnuplot_script_file << "set terminal pngcairo enhanced font 'arial,10' fontscale 1.0" << std::endl;
gnuplot_script_file << "replot" << std::endl;
}
{
const ModelInput& input = model_info.model_input;
std::fstream gnuplot_script_file(gnuplot_phase_plane_script, std::ios::out);
gnuplot_script_file << "set terminal 'wxt'" << std::endl;
gnuplot_script_file << "k1 = " << input.enemy_skill << std::endl;
gnuplot_script_file << "k2 = " << input.army_skill << std::endl;
gnuplot_script_file << "alpha = " << input.front_line_fraction << std::endl;
gnuplot_script_file << "beta = " << input.enemy_front_line_fraction << std::endl;
gnuplot_script_file << "vec_scale = 0.5" << std::endl;
gnuplot_script_file << "dEdt(I,E) = -k1 * alpha * E * beta * I" << std::endl;
gnuplot_script_file << "dIdt(I,E) = -k2 * alpha * E * beta * I" << std::endl;
gnuplot_script_file << "vx(x,y) = dEdt(x,y) * vec_scale # * (1 / sqrt(dEdt(x,y)**2 + dIdt(x,y)**2))" << std::endl;
gnuplot_script_file << "vy(x,y) = dIdt(x,y) * vec_scale # * (1 / sqrt(dEdt(x,y)**2 + dIdt(x,y)**2))" << std::endl;
gnuplot_script_file << "set samples 20" << std::endl;
gnuplot_script_file << "set zeroaxis" << std::endl;
gnuplot_script_file << "set xlabel 'Número de Soldados - E(t)'" << std::endl;
gnuplot_script_file << "set ylabel 'Número de Inimigos - I(t)'" << std::endl;
gnuplot_script_file << "set title 'Plano de Fase' font 'Arial, " << title_font_size << "'" << std::endl;
gnuplot_script_file << "plot '_gentlemans_battle.dat' using 2:3 with lines title 'Número de Soldados x Inimigos'," <<
" '++' u 1:2:(vx($1,$2)):(vy($1,$2)) with vectors notitle linetype rgb '#6f99c8'" <<
std::endl;
gnuplot_script_file << "set output 'report/figs/battle_phase_plane.png'" << std::endl;
gnuplot_script_file << "set terminal pngcairo enhanced font 'Arial,10' fontscale 1.0" << std::endl;
gnuplot_script_file << "replot" << std::endl;
}
// show reaction plot
std::string plot_command = "gnuplot -p " + gnuplot_reaction_script + " > battle_reaction.png";
std::cout << plot_command << std::endl;
system(plot_command.data());
// show diffusion plot
plot_command = "gnuplot -p " + gnuplot_diffusion_script + " > battle_ammo_diffusion.png";
std::cout << plot_command << std::endl;
system(plot_command.data());
// show phase plane plot
plot_command = "gnuplot -p " + gnuplot_phase_plane_script + " > battle_phase_plane.png";
std::cout << plot_command << std::endl;
system(plot_command.data());
}
}
};
struct ModelCondensedOutput
{
int num_executions;
std::string param_name;
std::string graph_title;
std::string output_filename;
std::vector<double> param_value_list;
ModelCondensedOutput(int _num_executions,
const std::string& _param_name,
const std::string& _graph_title,
const std::string& _output_filename
) :
num_executions(_num_executions),
param_name(_param_name),
graph_title(_graph_title),
output_filename(_output_filename)
{
param_value_list.reserve(num_executions);
}
void add_param_value(double param_value)
{
param_value_list.push_back(param_value);
}
void show_condensed_plot()
{
std::string script_filename = "_condenser.gnu";
std::fstream gnuplot_script_file(script_filename, std::ios::out);
gnuplot_script_file << "set terminal 'wxt'" << std::endl;
gnuplot_script_file << "set xlabel 'Número de Soldados - E(t)'" << std::endl;
gnuplot_script_file << "set ylabel 'Número de Inimigos - I(t)" << std::endl;
gnuplot_script_file << "set title '" << graph_title << "' font 'Arial, 15'" << std::endl;
gnuplot_script_file << "plot ";
for(int i = 0; i < num_executions; ++i)
{
gnuplot_script_file << "'" << i << "_gentlemans_battle.dat' using 2:3 with lines title '" << param_name << " = " << param_value_list[i] << "',";
}
gnuplot_script_file << std::endl;
gnuplot_script_file << "set terminal pngcairo enhanced font 'Arial, 10' fontscale 1.0" << std::endl;
gnuplot_script_file << "set output 'report/figs/battle_" << output_filename << ".png'" << std::endl;
gnuplot_script_file << "replot" << std::endl;
gnuplot_script_file.close();
std::string plot_command = "gnuplot -p " + script_filename;
std::cout << plot_command << std::endl;
system(plot_command.data());
}
};
struct GentlesmanBattleModel
{
ModelInput input;
ModelOutput output;
ModelInfo info;
GentlesmanBattleModel(const std::string& prefix = "") :
output(info, input, prefix), info(input)
{
}
void run(bool b_show_plots = true)
{
// Print parameters information
std::cout << input << std::endl;
info.update_input();
output.start_execution();
do
{
output.write_output_step();
info.advance_time();
}
while(!info.should_stop());
// Print execution summary
std::cout << info << std::endl;
output.stop_execution(b_show_plots);
}
};
int main()
{
const int num_executions = 1;
std::string param_name = "L";
double param_min = 2;
double param_max = 20;
if(num_executions > 1)
{
ModelCondensedOutput condensend_output(num_executions,
param_name,
"Resultado da Batalha com Variação no Espaçamento da Formação",
"formation_size_variation");
for(int i = 0; i < num_executions; ++i)
{
GentlesmanBattleModel model(std::to_string(i));
double param_value = param_min + (param_max - param_min) * (i / static_cast<double>(num_executions));
model.input.formation_size = param_value;
model.run(false);
condensend_output.add_param_value(model.input.formation_size);
}
condensend_output.show_condensed_plot();
}
else
{
GentlesmanBattleModel model;
model.run();
}
return EXIT_SUCCESS;
}
| 40.791489 | 157 | 0.562383 | mcleary |
20ddfc4d3bd4bc8693b5372cce680ca590fb96f5 | 2,385 | cpp | C++ | Labs/d6t2.cpp | Chalkydoge/FDU_DS | 8d2dec307d8dd641fbe3bcfa633cede9e1a45252 | [
"MIT"
] | 1 | 2020-09-16T06:17:14.000Z | 2020-09-16T06:17:14.000Z | Labs/d6t2.cpp | Chalkydoge/FDU_DS | 8d2dec307d8dd641fbe3bcfa633cede9e1a45252 | [
"MIT"
] | null | null | null | Labs/d6t2.cpp | Chalkydoge/FDU_DS | 8d2dec307d8dd641fbe3bcfa633cede9e1a45252 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
struct TreeNode{
int val;
TreeNode *left, *right;
TreeNode(int v) : val(v), left(NULL), right(NULL){}
};
TreeNode* buildTree(vector<int>& nums){
if(nums.size() == 0)
return NULL;
TreeNode *root = new TreeNode(nums.front());
queue<TreeNode *> q;
q.push(root);
int i = 1;
while(!q.empty() && (i < (int)nums.size())){
TreeNode *node = q.front();
q.pop();
if(node){
TreeNode *lc = (nums[i] != -1) ? new TreeNode(nums[i]) : NULL;
TreeNode *rc = (i + 1 < (int)nums.size() && nums[i + 1] != -1) ? new TreeNode(nums[i + 1]) : NULL;
node->left = lc;
node->right = rc;
q.push(lc);
q.push(rc);
i += 2;
}
}
return root;
}
void pre_trav(TreeNode* root){
stack<TreeNode *> st;
while(root || !st.empty()){
if(root){
cout << root->val << " ";
st.push(root);
root = root->left;
}
else{
root = st.top();
st.pop();
root = root->right;
}
}
}
void trav(TreeNode* root){
if(!root)
return;
cout << root->val << endl;
trav(root->left);
trav(root->right);
}
// t2-recursion
void dfs(TreeNode* root, int level, vector<int>& level_sums, vector<int>& cnt){
if(!root)
return;
if(level < (int)level_sums.size()){
level_sums[level] += root->val;
++cnt[level];
}
else{
level_sums.push_back(root->val);
cnt.push_back(1);
}
dfs(root->left, level + 1, level_sums, cnt);
dfs(root->right, level + 1, level_sums, cnt);
}
vector<double> get_averageII(TreeNode* root){
vector<int> level_sums, cnt;
dfs(root, 0, level_sums, cnt);
vector<double> res;
for (int i = 0; i < (int)level_sums.size(); ++i){
res.push_back((double)level_sums[i] / cnt[i]);
}
return res;
}
int main(){
int v;
vector<int> nums;
while(cin >> v){
nums.push_back(v);
if(cin.get() == '\n')
break;
}
TreeNode *root = buildTree(nums);
// trav(root);
vector<double> res = get_averageII(root);
for (int i = 0; i < (int)res.size(); ++i){
cout << res[i] << " ";
}
return 0;
}
| 22.5 | 110 | 0.501468 | Chalkydoge |