hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18934fb423b7cc76e013c6063daaa33dda91f026 | 1,292 | h | C | lib_graphd/inc/GraphInterface.h | spowers/INDDGO-survey | 860f15376f7be074f47280a74b912a8f0baa37bf | [
"BSD-3-Clause"
] | 9 | 2015-05-30T00:33:04.000Z | 2021-04-23T17:19:58.000Z | lib_graphd/inc/GraphInterface.h | spowers/INDDGO-survey | 860f15376f7be074f47280a74b912a8f0baa37bf | [
"BSD-3-Clause"
] | 3 | 2016-03-04T19:46:40.000Z | 2017-01-14T13:44:21.000Z | lib_graphd/inc/GraphInterface.h | spowers/INDDGO-survey | 860f15376f7be074f47280a74b912a8f0baa37bf | [
"BSD-3-Clause"
] | 5 | 2015-11-29T08:50:50.000Z | 2020-03-14T23:12:22.000Z | /*
This file is part of INDDGO.
Copyright (C) 2012, Oak Ridge National Laboratory
This product includes software produced by UT-Battelle, LLC under Contract No.
DE-AC05-00OR22725 with the Department of Energy.
This program is free software; you can redistribute it and/or modify
it under the terms of the New BSD 3-clause software license (LICENSE).
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
LICENSE for more details.
For more information please contact the INDDGO developers at:
inddgo-info@googlegroups.com
*/
#ifndef GRAPHINTERFACE_H_
#define GRAPHINTERFACE_H_
#include <string>
#include <vector>
namespace Graph {
class GraphInterface
{
virtual bool is_edge(int i, int j) const = 0;
virtual int get_num_nodes() const = 0;
virtual int get_num_edges() const = 0;
virtual std::string get_graph_type() const = 0;
virtual int get_capacity() const = 0;
virtual int get_degree(int v) const = 0;
virtual std::vector <int> get_degree() const = 0;
virtual int *serialize() = 0;
virtual void deserialize(int *buffer) = 0;
};
}
#endif /* GRAPHINTERFACE_H_ */
| 29.363636 | 81 | 0.718266 | [
"vector"
] |
1897f5a58ea8ca1bc5349ef1aaf56e882d76c7e2 | 3,155 | h | C | engine/source/engine/nethelper.h | n4n0lix/Kerosene | cd65f5e4b374a91259e22d41153f44c141d79af3 | [
"0BSD"
] | 2 | 2016-01-17T03:35:39.000Z | 2019-12-23T15:04:47.000Z | engine/source/engine/nethelper.h | n4n0lix/Kerosene | cd65f5e4b374a91259e22d41153f44c141d79af3 | [
"0BSD"
] | null | null | null | engine/source/engine/nethelper.h | n4n0lix/Kerosene | cd65f5e4b374a91259e22d41153f44c141d79af3 | [
"0BSD"
] | 2 | 2016-03-23T09:13:14.000Z | 2019-12-23T15:04:53.000Z | #pragma once
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/* Includes */
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
// Std-Includes
// Other Includes
// Internal Includes
#include "_global.h"
#include "vector2f.h"
#include "vector3f.h"
#include "vector4f.h"
#include "quaternion4f.h"
ENGINE_NAMESPACE_BEGIN
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
/* Helpers */
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
union DoubleNetConverter {
double asDouble;
uint64 asUInt64;
};
union FloatNetConverter {
float asFloat;
uint32 asUInt32;
};
inline void __net_write( std::vector<byte>& v, bool value ) {
v.push_back( value );
}
inline void __net_write( std::vector<byte>& v, char value ) {
v.push_back( value );
}
inline void __net_write( std::vector<byte>& v, int16 value ) {
v.push_back( (value & 0xFF00) >> 8 );
v.push_back( (value & 0x00FF) );
}
inline void __net_write( std::vector<byte>& v, uint16 value ) {
v.push_back( (value & 0xFF00) >> 8 );
v.push_back( (value & 0x00FF) );
}
inline void __net_write( std::vector<byte>& v, int32 value ) {
v.push_back( (value & 0xFF000000) >> 24 );
v.push_back( (value & 0x00FF0000) >> 16 );
v.push_back( (value & 0x0000FF00) >> 8 );
v.push_back( (value & 0x000000FF) );
}
inline void __net_write( std::vector<byte>& v, uint32 value ) {
v.push_back( (value & 0xFF000000) >> 24 );
v.push_back( (value & 0x00FF0000) >> 16 );
v.push_back( (value & 0x0000FF00) >> 8 );
v.push_back( (value & 0x000000FF) );
}
inline void __net_write( std::vector<byte>& v, float value ) {
FloatNetConverter val;
val.asFloat = value;
__net_write( v, val.asUInt32 );
}
inline void __net_write( std::vector<byte>& v, Vector2f value ) {
__net_write( v, value.x );
__net_write( v, value.y );
}
inline void __net_write( std::vector<byte>& v, Vector3f value ) {
__net_write( v, value.x );
__net_write( v, value.y );
__net_write( v, value.z );
}
inline void __net_write( std::vector<byte>& v, Vector4f value ) {
__net_write( v, value.x );
__net_write( v, value.y );
__net_write( v, value.z );
__net_write( v, value.w );
}
inline void __net_write( std::vector<byte>& v, Quaternion4f value ) {
__net_write( v, value.x );
__net_write( v, value.y );
__net_write( v, value.z );
__net_write( v, value.w );
}
inline void __net_write( std::vector<byte>& v, string str ) {
uint16 length = (uint16)std::min( str.length(), size_t( 1024 ) ); // 1024 - Max String Length for net packets
__net_write( v, length );
for ( auto chr : str.substr( 0, length - 1 ) ) {
__net_write( v, chr );
}
}
enum class NetVarType {
SHARED,
SELF,
SERVER
};
enum class NetVarID {
Entity_uid = 0, // SHARED
Entity_transform = 1, // SHARED
Creature_health = 64, // SHARED
Creature_name = 65, // SHARED
Creature_stamina = 66 // SELF
};
ENGINE_NAMESPACE_END
| 23.544776 | 113 | 0.55626 | [
"vector"
] |
18a660cec09ca4437c788a8228fe0622667af714 | 6,024 | h | C | src/OpenVDS/VDS/VolumeDataRequestProcessor.h | wadesalazar/open-vds2 | 71b6a49f39f79c913b1a560be1869c8bd391de19 | [
"Apache-2.0"
] | null | null | null | src/OpenVDS/VDS/VolumeDataRequestProcessor.h | wadesalazar/open-vds2 | 71b6a49f39f79c913b1a560be1869c8bd391de19 | [
"Apache-2.0"
] | null | null | null | src/OpenVDS/VDS/VolumeDataRequestProcessor.h | wadesalazar/open-vds2 | 71b6a49f39f79c913b1a560be1869c8bd391de19 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
** Copyright 2019 The Open Group
** Copyright 2019 Bluware, Inc.
**
** 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 VOLUMEDATAREQUESTPROCESSOR_H
#define VOLUMEDATAREQUESTPROCESSOR_H
#include <OpenVDS/VolumeData.h>
#include <OpenVDS/OpenVDS.h>
#include "DimensionGroup.h"
#include "VolumeDataPageAccessorImpl.h"
#include "VolumeDataChunk.h"
#include "ThreadPool.h"
#include <stdint.h>
#include <map>
#include <functional>
#include <vector>
namespace OpenVDS
{
class VolumeDataPage;
struct PageAccessorKey
{
DimensionsND dimensionsND;
int32_t lod;
int32_t channel;
bool operator<(const PageAccessorKey &other) const
{
return (int(dimensionsND) == int(other.dimensionsND)) ? lod == other.lod ? channel < other.channel : lod < other.lod : int(dimensionsND) < int(other.dimensionsND);
}
};
struct JobPage
{
JobPage(VolumeDataPageImpl *page, const VolumeDataChunk &chunk)
: page(page)
, chunk(chunk)
{}
VolumeDataPageImpl *page;
VolumeDataChunk chunk;
};
struct PageAccessorNotifier
{
PageAccessorNotifier(std::mutex &mutex)
: dirty(false)
, exit(false)
, mutex(mutex)
{}
void setDirty()
{
std::unique_lock<std::mutex> lock(mutex);
dirty = true;
jobNotification.notify_all();
}
void setDirtyNoLock()
{
dirty = true;
jobNotification.notify_all();
}
void setExit()
{
std::unique_lock<std::mutex> lock(mutex);
exit = true;
jobNotification.notify_all();
}
bool dirty;
bool exit;
std::mutex &mutex;
std::condition_variable jobNotification;
};
struct Job
{
Job(int64_t jobId, PageAccessorNotifier &pageAccessorNotifier, VolumeDataPageAccessorImpl &pageAccessor, int pagesCount)
: jobId(jobId)
, pageAccessorNotifier(pageAccessorNotifier)
, pageAccessor(pageAccessor)
, pagesProcessed(0)
, done(false)
, cancelled(false)
, pagesCount(pagesCount)
{}
int64_t jobId;
PageAccessorNotifier &pageAccessorNotifier;
VolumeDataPageAccessorImpl &pageAccessor;
std::vector<JobPage> pages;
std::vector<std::future<Error>> future;
std::atomic_int pagesProcessed;
std::atomic_bool done;
std::atomic_bool cancelled;
int pagesCount;
Error completedError;
};
class VolumeDataRequestProcessor
{
public:
VolumeDataRequestProcessor(VolumeDataAccessManagerImpl &manager);
~VolumeDataRequestProcessor();
int64_t AddJob(const std::vector<VolumeDataChunk> &chunks, std::function<bool(VolumeDataPageImpl *page, const VolumeDataChunk &volumeDataChunk, Error &error)> processor, bool singleThread = false);
bool IsActive(int64_t requestID);
bool IsCompleted(int64_t requestID);
bool IsCanceled(int64_t requestID);
bool WaitForCompletion(int64_t requestID, int millisecondsBeforeTimeout = 0);
void Cancel(int64_t requestID);
float GetCompletionFactor(int64_t requestID);
int CountActivePages();
int64_t RequestVolumeSubset(void *buffer, VolumeDataLayer const *volumeDataLayer, const int32_t(&minRequested)[Dimensionality_Max], const int32_t (&maxRequested)[Dimensionality_Max], int32_t LOD, VolumeDataChannelDescriptor::Format format, bool isReplaceNoValue, float replacementNoValue);
int64_t RequestProjectedVolumeSubset(void *buffer, VolumeDataLayer const *volumeDataLayer, const int32_t (&minRequested)[Dimensionality_Max], const int32_t (&maxRequested)[Dimensionality_Max], FloatVector4 const &voxelPlane, DimensionGroup projectedDimensions, int32_t LOD, VolumeDataChannelDescriptor::Format format, InterpolationMethod interpolationMethod, bool isReplaceNoValue, float replacementNoValue);
int64_t RequestVolumeSamples(void *buffer, VolumeDataLayer const *volumeDataLayer, const float(*samplePositions)[Dimensionality_Max], int32_t samplePosCount, InterpolationMethod interpolationMethod, bool isReplaceNoValue, float replacementNoValue);
int64_t RequestVolumeTraces(void *buffer, VolumeDataLayer const *volumeDataLayer, const float(*tracePositions)[Dimensionality_Max], int32_t tracePositionsCount, int32_t LOD, InterpolationMethod interpolationMethod, int32_t traceDimension, bool isReplaceNoValue, float replacementNoValue);
int64_t PrefetchVolumeChunk(VolumeDataLayer const *volumeDataLayer, int64_t chunkIndex);
static int64_t StaticGetVolumeSubsetBufferSize(VolumeDataLayout const *volumeDataLayout, const int (&minVoxelCoordinates)[Dimensionality_Max], const int (&maxVoxelCoordinates)[Dimensionality_Max], VolumeDataChannelDescriptor::Format format, int LOD, int channel);
static int64_t StaticGetProjectedVolumeSubsetBufferSize(VolumeDataLayout const *volumeDataLayout, const int (&minVoxelCoordinates)[Dimensionality_Max], const int (&maxVoxelCoordinates)[Dimensionality_Max], DimensionGroup projectedDimensions, VolumeDataChannelDescriptor::Format format, int LOD, int channel);
static int64_t StaticGetVolumeSamplesBufferSize(VolumeDataLayout const *volumeDataLayout, int sampleCount, int channel);
static int64_t StaticGetVolumeTracesBufferSize(VolumeDataLayout const *volumeDataLayout, int traceCount, int traceDimension, int LOD, int channel);
private:
VolumeDataAccessManagerImpl &m_manager;
std::map<PageAccessorKey, VolumeDataPageAccessorImpl *> m_pageAccessors;
std::vector<std::unique_ptr<Job>> m_jobs;
std::mutex m_mutex;
ThreadPool m_threadPool;
PageAccessorNotifier m_pageAccessorNotifier;
std::thread m_cleanupThread;
};
}
#endif
| 38.615385 | 410 | 0.764608 | [
"vector"
] |
18b75e3d9ee76c9e839875c88684627c936d265c | 46,535 | h | C | dash/include/dash/pattern/DynamicPattern.h | MarkusVelten/dash | bbb703202aba2131e52b312a585225bf2b54c1f5 | [
"BSD-3-Clause"
] | 1 | 2019-05-19T20:31:20.000Z | 2019-05-19T20:31:20.000Z | dash/include/dash/pattern/DynamicPattern.h | MarkusVelten/dash | bbb703202aba2131e52b312a585225bf2b54c1f5 | [
"BSD-3-Clause"
] | null | null | null | dash/include/dash/pattern/DynamicPattern.h | MarkusVelten/dash | bbb703202aba2131e52b312a585225bf2b54c1f5 | [
"BSD-3-Clause"
] | 2 | 2019-10-02T23:19:22.000Z | 2020-06-27T09:23:31.000Z | #ifndef DASH__DYNAMIC_PATTERN_H__INCLUDED
#define DASH__DYNAMIC_PATTERN_H__INCLUDED
#include <functional>
#include <array>
#include <type_traits>
#include <dash/Types.h>
#include <dash/Distribution.h>
#include <dash/Exception.h>
#include <dash/Dimensional.h>
#include <dash/Cartesian.h>
#include <dash/Team.h>
#include <dash/PatternProperties.h>
#include <dash/internal/Math.h>
#include <dash/internal/Logging.h>
#include <dash/internal/PatternArguments.h>
namespace dash {
#ifndef DOXYGEN
/**
* Irregular dynamic pattern.
*
* \concept{DashPatternConcept}
*/
template<
dim_t NumDimensions,
MemArrange Arrangement = dash::ROW_MAJOR,
typename IndexType = dash::default_index_t >
class DynamicPattern;
#endif // DOXYGEN
/**
* Irregular dynamic pattern.
* Specialization for 1-dimensional data.
*
* \concept{DashPatternConcept}
*/
template<
MemArrange Arrangement,
typename IndexType >
class DynamicPattern<1, Arrangement, IndexType>
{
private:
static const dim_t NumDimensions = 1;
public:
static constexpr char const * PatternName = "DynamicPattern1D";
public:
/// Satisfiable properties in pattern property category Partitioning:
typedef pattern_partitioning_properties<
// Minimal number of blocks in every dimension, i.e. one block
// per unit.
pattern_partitioning_tag::minimal,
// Block extents are constant for every dimension.
pattern_partitioning_tag::rectangular,
// Identical number of elements in every block.
pattern_partitioning_tag::balanced,
// Size of blocks may differ.
pattern_partitioning_tag::unbalanced,
// Partitioning is dynamic.
pattern_partitioning_tag::dynamic
> partitioning_properties;
/// Satisfiable properties in pattern property category Mapping:
typedef pattern_mapping_properties<
// Number of blocks assigned to a unit may differ.
pattern_mapping_tag::unbalanced
> mapping_properties;
/// Satisfiable properties in pattern property category Layout:
typedef pattern_layout_properties<
// Elements are contiguous in local memory within single block.
pattern_layout_tag::blocked,
// Local element order corresponds to a logical linearization
// within single blocks.
pattern_layout_tag::linear
> layout_properties;
private:
/// Fully specified type definition of self
typedef DynamicPattern<NumDimensions, Arrangement, IndexType>
self_t;
/// Derive size type from given signed index / ptrdiff type
typedef typename std::make_unsigned<IndexType>::type
SizeType;
typedef CartesianIndexSpace<NumDimensions, Arrangement, IndexType>
MemoryLayout_t;
typedef CartesianIndexSpace<NumDimensions, Arrangement, IndexType>
LocalMemoryLayout_t;
typedef CartesianSpace<NumDimensions, SizeType>
BlockSpec_t;
typedef DistributionSpec<NumDimensions>
DistributionSpec_t;
typedef TeamSpec<NumDimensions, IndexType>
TeamSpec_t;
typedef SizeSpec<NumDimensions, SizeType>
SizeSpec_t;
typedef ViewSpec<NumDimensions, IndexType>
ViewSpec_t;
typedef internal::PatternArguments<NumDimensions, IndexType>
PatternArguments_t;
public:
typedef IndexType index_type;
typedef SizeType size_type;
typedef ViewSpec_t viewspec_type;
typedef struct {
team_unit_t unit;
IndexType index;
} local_index_t;
typedef struct {
team_unit_t unit;
std::array<index_type, NumDimensions> coords;
} local_coords_t;
public:
/**
* Constructor, initializes a pattern from an argument list consisting
* of the pattern size (extent, number of elements) followed by an optional
* distribution type.
*
*/
template<typename ... Args>
DynamicPattern(
/// Argument list consisting of the pattern size (extent, number of
/// elements) in every dimension followed by optional distribution
/// types.
SizeType arg,
/// Argument list consisting of the pattern size (extent, number of
/// elements) in every dimension followed by optional distribution
/// types.
Args && ... args)
: DynamicPattern(PatternArguments_t(arg, args...))
{
DASH_LOG_TRACE("DynamicPattern()", "Constructor with argument list");
DASH_ASSERT_EQ(
_local_sizes.size(), _nunits,
"Number of given local sizes " << _local_sizes.size() << " " <<
"does not match number of units" << _nunits);
initialize_local_range();
DASH_LOG_TRACE("DynamicPattern()", "DynamicPattern initialized");
}
/**
* Constructor, initializes a pattern from explicit instances of
* \c SizeSpec, \c DistributionSpec, \c TeamSpec and \c Team.
*
*/
DynamicPattern(
/// Size spec of the pattern.
const SizeSpec_t & sizespec,
/// Distribution spec.
const DistributionSpec_t & distspec,
/// Cartesian arrangement of units within the team
const TeamSpec_t & teamspec,
/// Team containing units to which this pattern maps its elements.
Team & team = dash::Team::All())
: _size(sizespec.size()),
_local_sizes(initialize_local_sizes(
_size,
distspec,
team)),
_block_offsets(initialize_block_offsets(
_local_sizes)),
_memory_layout(std::array<SizeType, 1> { _size }),
_blockspec(initialize_blockspec(
_size,
_local_sizes)),
_distspec(DistributionSpec_t()),
_team(&team),
_myid(_team->myid()),
_teamspec(
teamspec,
_distspec,
*_team),
_nunits(_team->size()),
_blocksize(initialize_blocksize(
_size,
_distspec,
_nunits)),
_nblocks(_nunits),
_local_size(
initialize_local_extent(_team->myid())),
_local_memory_layout(std::array<SizeType, 1> { _local_size }),
_local_capacity(initialize_local_capacity())
{
DASH_LOG_TRACE("DynamicPattern()", "(sizespec, dist, team)");
DASH_ASSERT_EQ(
_local_sizes.size(), _nunits,
"Number of given local sizes " << _local_sizes.size() << " " <<
"does not match number of units" << _nunits);
initialize_local_range();
DASH_LOG_TRACE("DynamicPattern()", "DynamicPattern initialized");
}
/**
* Constructor, initializes a pattern from explicit instances of
* \c SizeSpec, \c DistributionSpec and \c Team.
*
*/
DynamicPattern(
/// Size spec of the pattern.
const SizeSpec_t & sizespec,
/// Distribution spec.
const DistributionSpec_t & distspec,
/// Team containing units to which this pattern maps its elements.
Team & team = dash::Team::All())
: _size(sizespec.size()),
_local_sizes(initialize_local_sizes(
_size,
distspec,
team)),
_block_offsets(initialize_block_offsets(
_local_sizes)),
_memory_layout(std::array<SizeType, 1> { _size }),
_blockspec(initialize_blockspec(
_size,
_local_sizes)),
_distspec(DistributionSpec_t()),
_team(&team),
_myid(_team->myid()),
_teamspec(_distspec, *_team),
_nunits(_team->size()),
_blocksize(initialize_blocksize(
_size,
_distspec,
_nunits)),
_nblocks(_nunits),
_local_size(
initialize_local_extent(_team->myid())),
_local_memory_layout(std::array<SizeType, 1> { _local_size }),
_local_capacity(initialize_local_capacity())
{
DASH_LOG_TRACE("DynamicPattern()", "(sizespec, dist, team)");
DASH_ASSERT_EQ(
_local_sizes.size(), _nunits,
"Number of given local sizes " << _local_sizes.size() << " " <<
"does not match number of units" << _nunits);
initialize_local_range();
DASH_LOG_TRACE("DynamicPattern()", "DynamicPattern initialized");
}
/**
* Constructor, initializes a pattern from an argument list consisting
* of the pattern size (extent, number of elements) followed by an optional
* distribution type.
*
*/
template<typename ... Args>
DynamicPattern(
/// Number of local elements for every unit in the active team.
const std::vector<size_type> & local_sizes,
/// Argument list consisting of the pattern size (extent, number of
/// elements) in every dimension followed by optional distribution
/// types.
SizeType arg,
/// Argument list consisting of the pattern size (extent, number of
/// elements) in every dimension followed by optional distribution
/// types.
Args && ... args)
: DynamicPattern(local_sizes, PatternArguments_t(arg, args...))
{
DASH_LOG_TRACE("DynamicPattern()", "Constructor with argument list");
DASH_ASSERT_EQ(
_local_sizes.size(), _nunits,
"Number of given local sizes " << _local_sizes.size() << " " <<
"does not match number of units" << _nunits);
initialize_local_range();
DASH_LOG_TRACE("DynamicPattern()", "DynamicPattern initialized");
}
/**
* Constructor, initializes a pattern from explicit instances of
* \c SizeSpec, \c DistributionSpec, \c TeamSpec and a \c Team.
*
*/
DynamicPattern(
/// Number of local elements for every unit in the active team.
const std::vector<size_type> & local_sizes,
/// Cartesian arrangement of units within the team
const TeamSpec_t & teamspec,
/// Team containing units to which this pattern maps its elements
dash::Team & team = dash::Team::All())
: _size(initialize_size(
local_sizes)),
_local_sizes(local_sizes),
_block_offsets(initialize_block_offsets(
_local_sizes)),
_memory_layout(std::array<SizeType, 1> { _size }),
_blockspec(initialize_blockspec(
_size,
_local_sizes)),
_distspec(DistributionSpec_t()),
_team(&team),
_myid(_team->myid()),
_teamspec(
teamspec,
_distspec,
*_team),
_nunits(_team->size()),
_blocksize(initialize_blocksize(
_size,
_distspec,
_nunits)),
_nblocks(_nunits),
_local_size(
initialize_local_extent(_team->myid())),
_local_memory_layout(std::array<SizeType, 1> { _local_size }),
_local_capacity(initialize_local_capacity())
{
DASH_LOG_TRACE("DynamicPattern()", "(sizespec, dist, teamspec, team)");
DASH_ASSERT_EQ(
_local_sizes.size(), _nunits,
"Number of given local sizes " << _local_sizes.size() << " " <<
"does not match number of units" << _nunits);
initialize_local_range();
DASH_LOG_TRACE("DynamicPattern()", "DynamicPattern initialized");
}
/**
* Constructor, initializes a pattern from explicit instances of
* \c SizeSpec, \c DistributionSpec, \c TeamSpec and a \c Team.
*
*/
DynamicPattern(
/// Number of local elements for every unit in the active team.
const std::vector<size_type> & local_sizes,
/// Team containing units to which this pattern maps its elements
Team & team = dash::Team::All())
: _size(initialize_size(
local_sizes)),
_local_sizes(local_sizes),
_block_offsets(initialize_block_offsets(
_local_sizes)),
_memory_layout(std::array<SizeType, 1> { _size }),
_blockspec(initialize_blockspec(
_size,
_local_sizes)),
_distspec(DistributionSpec_t()),
_team(&team),
_myid(_team->myid()),
_teamspec(_distspec, *_team),
_nunits(_team->size()),
_blocksize(initialize_blocksize(
_size,
_distspec,
_nunits)),
_nblocks(_nunits),
_local_size(
initialize_local_extent(_team->myid())),
_local_memory_layout(std::array<SizeType, 1> { _local_size }),
_local_capacity(initialize_local_capacity())
{
DASH_LOG_TRACE("DynamicPattern()", "(sizespec, dist, team)");
DASH_ASSERT_EQ(
_local_sizes.size(), _nunits,
"Number of given local sizes " << _local_sizes.size() << " " <<
"does not match number of units" << _nunits);
initialize_local_range();
DASH_LOG_TRACE("DynamicPattern()", "DynamicPattern initialized");
}
/**
* Copy constructor.
*/
DynamicPattern(const self_t & other)
: _size(other._size),
_local_sizes(other._local_sizes),
_block_offsets(other._block_offsets),
_memory_layout(other._memory_layout),
_blockspec(other._blockspec),
_distspec(other._distspec),
_team(other._team),
_myid(other._myid),
_teamspec(other._teamspec),
_nunits(other._nunits),
_blocksize(other._blocksize),
_nblocks(other._nblocks),
_local_size(other._local_size),
_local_memory_layout(other._local_memory_layout),
_local_capacity(other._local_capacity),
_lbegin(other._lbegin),
_lend(other._lend)
{
// No need to copy _arguments as it is just used to
// initialize other members.
DASH_LOG_TRACE("DynamicPattern(other)", "DynamicPattern copied");
}
/**
* Copy constructor using non-const lvalue reference parameter.
*
* Introduced so variadic constructor is not a better match for
* copy-construction.
*/
DynamicPattern(self_t & other)
: DynamicPattern(static_cast<const self_t &>(other))
{ }
/**
* Equality comparison operator.
*/
bool operator==(
/// Pattern instance to compare for equality
const self_t & other) const
{
if (this == &other) {
return true;
}
// no need to compare all members as most are derived from
// constructor arguments.
return(
_size == other._size &&
_local_sizes == other._local_sizes &&
_distspec == other._distspec &&
_teamspec == other._teamspec &&
_nblocks == other._nblocks &&
_blocksize == other._blocksize &&
_nunits == other._nunits
);
}
/**
* Inquality comparison operator.
*/
bool operator!=(
/// Pattern instance to compare for inequality
const self_t & other) const
{
return !(*this == other);
}
/**
* Assignment operator.
*/
self_t & operator=(const self_t & other) = default;
/**
* Resolves the global index of the first local element in the pattern.
*
* \see DashPatternConcept
*/
IndexType lbegin() const
{
return _lbegin;
}
/**
* Resolves the global index past the last local element in the pattern.
*
* \see DashPatternConcept
*/
IndexType lend() const
{
return _lend;
}
////////////////////////////////////////////////////////////////////////////
/// resize / balance
////////////////////////////////////////////////////////////////////////////
/**
* Update the number of local elements of the specified unit.
*/
inline void local_resize(team_unit_t unit, size_type local_size)
{
_local_sizes[unit] = local_size;
}
/**
* Update the number of local elements of the active unit.
*/
inline void local_resize(size_type local_size)
{
_local_sizes[_myid] = local_size;
}
/**
* Balance the number of local elements across all units in the pattern's
* associated team.
*/
inline void balance()
{
}
////////////////////////////////////////////////////////////////////////////
/// unit_at
////////////////////////////////////////////////////////////////////////////
/**
* Convert given point in pattern to its assigned unit id.
*
* \see DashPatternConcept
*/
team_unit_t unit_at(
/// Absolute coordinates of the point
const std::array<IndexType, NumDimensions> & coords,
/// View specification (offsets) to apply on \c coords
const ViewSpec_t & viewspec) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at()", coords);
// Apply viewspec offsets to coordinates:
team_unit_t unit_id(((coords[0] + viewspec[0].offset) / _blocksize)
% _nunits);
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at >", unit_id);
return unit_id;
}
/**
* Convert given coordinate in pattern to its assigned unit id.
*
* \see DashPatternConcept
*/
team_unit_t unit_at(
const std::array<IndexType, NumDimensions> & g_coords) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at()", g_coords);
auto g_coord = g_coords[0];
for (team_unit_t unit_idx{0}; unit_idx < _nunits - 1; ++unit_idx) {
if (_block_offsets[unit_idx+1] >= g_coord) {
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at >", unit_idx);
return unit_idx;
}
}
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at >", _nunits-1);
return _nunits-1;
}
/**
* Convert given global linear index to its assigned unit id.
*
* \see DashPatternConcept
*/
team_unit_t unit_at(
/// Global linear element offset
IndexType global_pos,
/// View to apply global position
const ViewSpec_t & viewspec) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at()", global_pos);
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at()", viewspec);
// Apply viewspec offsets to coordinates:
auto g_coord = global_pos + viewspec[0].offset;
for (team_unit_t unit_idx{0}; unit_idx < _nunits - 1; ++unit_idx) {
if (_block_offsets[unit_idx+1] >= static_cast<size_type>(g_coord)) {
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at >", unit_idx);
return unit_idx;
}
}
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at >", _nunits-1);
return _nunits-1;
}
/**
* Convert given global linear index to its assigned unit id.
*
* \see DashPatternConcept
*/
team_unit_t unit_at(
/// Global linear element offset
IndexType g_index) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at()", g_index);
for (team_unit_t unit_idx{0}; unit_idx < _nunits - 1; ++unit_idx) {
if (_block_offsets[unit_idx+1] > static_cast<size_type>(g_index)) {
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at >", unit_idx);
return unit_idx;
}
}
DASH_LOG_TRACE_VAR("DynamicPattern.unit_at >", _nunits-1);
return team_unit_t(_nunits-1);
}
////////////////////////////////////////////////////////////////////////////
/// extent
////////////////////////////////////////////////////////////////////////////
/**
* The number of elements in this pattern in the given dimension.
*
* \see blocksize()
* \see local_size()
* \see local_extent()
*
* \see DashPatternConcept
*/
IndexType extent(dim_t dim) const
{
DASH_ASSERT_EQ(
0, dim,
"Wrong dimension for Pattern::local_extent. " <<
"Expected dimension = 0, got " << dim);
return _size;
}
/**
* The actual number of elements in this pattern that are local to the
* calling unit in the given dimension.
*
* \see local_extents()
* \see blocksize()
* \see local_size()
* \see extent()
*
* \see DashPatternConcept
*/
IndexType local_extent(dim_t dim) const
{
DASH_ASSERT_EQ(
0, dim,
"Wrong dimension for Pattern::local_extent. " <<
"Expected dimension = 0, got " << dim);
return _local_size;
}
/**
* The actual number of elements in this pattern that are local to the
* given unit, by dimension.
*
* \see local_extent()
* \see blocksize()
* \see local_size()
* \see extent()
*
* \see DashPatternConcept
*/
std::array<SizeType, NumDimensions> local_extents(
team_unit_t unit) const
{
DASH_LOG_DEBUG_VAR("DynamicPattern.local_extents()", unit);
DASH_LOG_DEBUG_VAR("DynamicPattern.local_extents >", _local_size);
return std::array<SizeType, 1> { _local_size };
}
////////////////////////////////////////////////////////////////////////////
/// local
////////////////////////////////////////////////////////////////////////////
/**
* Convert given local coordinates and viewspec to linear local offset
* (index).
*
* \see DashPatternConcept
*/
IndexType local_at(
/// Point in local memory
const std::array<IndexType, NumDimensions> & local_coords,
/// View specification (offsets) to apply on \c coords
const ViewSpec_t & viewspec) const
{
return local_coords[0] + viewspec[0].offset;
}
/**
* Convert given local coordinates to linear local offset (index).
*
* \see DashPatternConcept
*/
IndexType local_at(
/// Point in local memory
const std::array<IndexType, NumDimensions> & local_coords) const
{
return local_coords[0];
}
/**
* Converts global coordinates to their associated unit and its respective
* local coordinates.
*
* NOTE: Same as \c local_index.
*
* \see DashPatternConcept
*/
local_coords_t local(
const std::array<IndexType, NumDimensions> & g_coords) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.local()", g_coords);
IndexType g_index = g_coords[0];
local_index_t l_index;
for (auto unit_idx = _nunits-1; unit_idx >= 0; --unit_idx) {
index_type block_offset = _block_offsets[unit_idx];
if (block_offset <= g_index) {
l_index.unit = unit_idx;
l_index.index = g_index - block_offset;
DASH_LOG_TRACE_VAR("DynamicPattern.local >", l_index.unit);
DASH_LOG_TRACE_VAR("DynamicPattern.local >", l_index.index);
return l_index;
}
}
DASH_THROW(
dash::exception::InvalidArgument,
"DynamicPattern.local: global coord " << g_index << " is out of bounds");
}
/**
* Converts global index to its associated unit and respective local index.
*
* NOTE: Same as \c local_index.
*
* \see DashPatternConcept
*/
local_index_t local(
IndexType g_index) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.local()", g_index);
DASH_LOG_TRACE_VAR("DynamicPattern.local", _block_offsets.size());
DASH_ASSERT_GT(_nunits, 0,
"team size is 0");
DASH_ASSERT_GE(_block_offsets.size(), _nunits,
"missing block offsets");
local_index_t l_index;
index_type unit_idx = static_cast<index_type>(_nunits-1);
for (; unit_idx >= 0; --unit_idx) {
DASH_LOG_TRACE_VAR("DynamicPattern.local", unit_idx);
index_type block_offset = _block_offsets[unit_idx];
DASH_LOG_TRACE_VAR("DynamicPattern.local", block_offset);
if (block_offset <= g_index) {
l_index.unit = unit_idx;
l_index.index = g_index - block_offset;
DASH_LOG_TRACE_VAR("DynamicPattern.local >", l_index.unit);
DASH_LOG_TRACE_VAR("DynamicPattern.local >", l_index.index);
return l_index;
}
}
DASH_THROW(
dash::exception::InvalidArgument,
"DynamicPattern.local: global index " << g_index << " is out of bounds");
}
/**
* Converts global coordinates to their associated unit's respective
* local coordinates.
*
* \see DashPatternConcept
*/
std::array<IndexType, NumDimensions> local_coords(
const std::array<IndexType, NumDimensions> & g_coords) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.local_coords()", g_coords);
IndexType g_index = g_coords[0];
index_type unit_idx = static_cast<index_type>(_nunits-1);
for (; unit_idx >= 0; --unit_idx) {
index_type block_offset = _block_offsets[unit_idx];
if (block_offset <= g_index) {
auto l_coord = g_index - block_offset;
DASH_LOG_TRACE_VAR("DynamicPattern.local_coords >", l_coord);
return std::array<IndexType, 1> { l_coord };
}
}
DASH_THROW(
dash::exception::InvalidArgument,
"DynamicPattern.local_coords: global index " << g_index <<
" is out of bounds");
}
/**
* Converts global coordinates to their associated unit and their respective
* local index.
*
* \see DashPatternConcept
*/
local_index_t local_index(
const std::array<IndexType, NumDimensions> & g_coords) const
{
IndexType g_index = g_coords[0];
DASH_LOG_TRACE_VAR("DynamicPattern.local_index()", g_coords);
local_index_t l_index;
index_type unit_idx = static_cast<index_type>(_nunits-1);
for (; unit_idx >= 0; --unit_idx) {
index_type block_offset = _block_offsets[unit_idx];
if (block_offset <= g_index) {
l_index.unit = unit_idx;
l_index.index = g_index - block_offset;
DASH_LOG_TRACE_VAR("DynamicPattern.local >", l_index.unit);
DASH_LOG_TRACE_VAR("DynamicPattern.local >", l_index.index);
return l_index;
}
}
DASH_THROW(
dash::exception::InvalidArgument,
"DynamicPattern.local: global index " << g_index << " is out of bounds");
}
////////////////////////////////////////////////////////////////////////////
/// global
////////////////////////////////////////////////////////////////////////////
/**
* Converts local coordinates of a given unit to global coordinates.
*
* \see DashPatternConcept
*/
std::array<IndexType, NumDimensions> global(
team_unit_t unit,
const std::array<IndexType, NumDimensions> & local_coords) const
{
DASH_LOG_DEBUG_VAR("DynamicPattern.global()", unit);
DASH_LOG_DEBUG_VAR("DynamicPattern.global()", local_coords);
DASH_LOG_TRACE_VAR("DynamicPattern.global", _nunits);
if (_nunits < 2) {
return local_coords;
}
// Initialize global index with element phase (= local coords):
index_type glob_index = _block_offsets[unit] + local_coords[0];
DASH_LOG_TRACE_VAR("DynamicPattern.global >", glob_index);
return std::array<IndexType, 1> { glob_index };
}
/**
* Converts local coordinates of active unit to global coordinates.
*
* \see DashPatternConcept
*/
std::array<IndexType, NumDimensions> global(
const std::array<IndexType, NumDimensions> & l_coords) const
{
return global(_team->myid(), l_coords);
}
/**
* Resolve an element's linear global index from the given unit's local
* index of that element.
*
* \see at Inverse of local()
*
* \see DashPatternConcept
*/
IndexType global(
team_unit_t unit,
IndexType l_index) const
{
return global(unit, std::array<IndexType, 1> { l_index })[0];
}
/**
* Resolve an element's linear global index from the calling unit's local
* index of that element.
*
* \see at Inverse of local()
*
* \see DashPatternConcept
*/
IndexType global(
IndexType l_index) const
{
return global(_team->myid(), std::array<IndexType, 1> { l_index })[0];
}
/**
* Resolve an element's linear global index from a given unit's local
* coordinates of that element.
*
* \see at
*
* \see DashPatternConcept
*/
IndexType global_index(
team_unit_t unit,
const std::array<IndexType, NumDimensions> & l_coords) const
{
auto g_index = global(unit, l_coords[0]);
return g_index;
}
////////////////////////////////////////////////////////////////////////////
/// at
////////////////////////////////////////////////////////////////////////////
/**
* Global coordinates to local index.
*
* Convert given global coordinates in pattern to their respective
* linear local index.
*
* \see DashPatternConcept
*/
IndexType at(
const std::array<IndexType, NumDimensions> & g_coords) const
{
return local_coords(g_coords)[0];
}
/**
* Global coordinates and viewspec to local index.
*
* Convert given global coordinate in pattern to its linear local index.
*
* \see DashPatternConcept
*/
IndexType at(
const std::array<IndexType, NumDimensions> & g_coords,
const ViewSpec_t & viewspec) const
{
auto vs_coords = g_coords;
vs_coords[0] += viewspec[0].offset;
return local_coords(vs_coords)[0];
}
/**
* Global coordinates to local index.
*
* Convert given coordinate in pattern to its linear local index.
*
* \see DashPatternConcept
*/
template<typename ... Values>
IndexType at(IndexType value, Values ... values) const
{
static_assert(
sizeof...(values) == NumDimensions-1,
"Wrong parameter number");
std::array<IndexType, NumDimensions> inputindex = {
value, (IndexType)values...
};
return at(inputindex);
}
////////////////////////////////////////////////////////////////////////////
/// is_local
////////////////////////////////////////////////////////////////////////////
/**
* Whether there are local elements in a dimension at a given offset,
* e.g. in a specific row or column.
*
* \see DashPatternConcept
*/
bool has_local_elements(
/// Dimension to check
dim_t dim,
/// Offset in dimension
IndexType dim_offset,
/// DART id of the unit
team_unit_t unit,
/// Viewspec to apply
const ViewSpec_t & viewspec) const
{
DASH_ASSERT_EQ(
0, dim,
"Wrong dimension for Pattern::has_local_elements. " <<
"Expected dimension = 0, got " << dim);
DASH_LOG_TRACE_VAR("DynamicPattern.has_local_elements()", dim_offset);
DASH_LOG_TRACE_VAR("DynamicPattern.has_local_elements()", unit);
DASH_LOG_TRACE_VAR("DynamicPattern.has_local_elements()", viewspec);
DASH_THROW(
dash::exception::NotImplemented,
"DynamicPattern.has_local_elements is not implemented");
}
/**
* Whether the given global index is local to the specified unit.
*
* \see DashPatternConcept
*/
inline bool is_local(
IndexType index,
team_unit_t unit) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.is_local()", index);
DASH_LOG_TRACE_VAR("DynamicPattern.is_local()", unit);
bool is_loc = index >= _block_offsets[unit] &&
(unit == _nunits-1 ||
index < _block_offsets[unit+1]);
DASH_LOG_TRACE_VAR("DynamicPattern.is_local >", is_loc);
return is_loc;
}
/**
* Whether the given global index is local to the unit that created
* this pattern instance.
*
* \see DashPatternConcept
*/
inline bool is_local(
IndexType index) const
{
auto unit = team().myid();
DASH_LOG_TRACE_VAR("DynamicPattern.is_local()", index);
DASH_LOG_TRACE_VAR("DynamicPattern.is_local", unit);
bool is_loc = index >= _block_offsets[unit] &&
(unit == _nunits-1 ||
index < _block_offsets[unit+1]);
DASH_LOG_TRACE_VAR("DynamicPattern.is_local >", is_loc);
return is_loc;
}
////////////////////////////////////////////////////////////////////////////
/// block
////////////////////////////////////////////////////////////////////////////
/**
* Cartesian arrangement of pattern blocks.
*/
const BlockSpec_t & blockspec() const
{
return _blockspec;
}
/**
* Index of block at given global coordinates.
*
* \see DashPatternConcept
*/
index_type block_at(
/// Global coordinates of element
const std::array<index_type, NumDimensions> & g_coords) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.block_at()", g_coords);
auto g_coord = g_coords[0];
for (index_type block_idx = 0; block_idx < _nunits - 1; ++block_idx) {
if (_block_offsets[block_idx+1] >= g_coord) {
DASH_LOG_TRACE_VAR("DynamicPattern.block_at >", block_idx);
return block_idx;
}
}
DASH_LOG_TRACE_VAR("DynamicPattern.block_at >", _nunits-1);
return _nunits-1;
}
/**
* View spec (offset and extents) of block at global linear block index in
* cartesian element space.
*/
ViewSpec_t block(
index_type g_block_index) const
{
DASH_LOG_DEBUG_VAR("DynamicPattern<1>.block >", g_block_index);
index_type offset = _block_offsets[g_block_index];
auto block_size = _local_sizes[g_block_index];
std::array<index_type, NumDimensions> offsets = { offset };
std::array<size_type, NumDimensions> extents = { block_size };
ViewSpec_t block_vs(offsets, extents);
DASH_LOG_DEBUG_VAR("DynamicPattern<1>.block >", block_vs);
return block_vs;
}
/**
* View spec (offset and extents) of block at local linear block index in
* global cartesian element space.
*/
ViewSpec_t local_block(
index_type l_block_index) const
{
DASH_LOG_DEBUG_VAR("DynamicPattern<1>.local_block()", l_block_index);
DASH_ASSERT_EQ(
0, l_block_index,
"DynamicPattern always assigns exactly 1 block to a single unit");
index_type block_offset = _block_offsets[_team->myid()];
size_type block_size = _local_sizes[_team->myid()];
std::array<index_type, NumDimensions> offsets = { block_offset };
std::array<size_type, NumDimensions> extents = { block_size };
ViewSpec_t block_vs(offsets, extents);
DASH_LOG_DEBUG_VAR("DynamicPattern<1>.local_block >", block_vs);
return block_vs;
}
/**
* View spec (offset and extents) of block at local linear block index in
* local cartesian element space.
*/
ViewSpec_t local_block_local(
index_type l_block_index) const
{
DASH_LOG_DEBUG_VAR("DynamicPattern<1>.local_block_local >", l_block_index);
size_type block_size = _local_sizes[_team->myid()];
std::array<index_type, NumDimensions> offsets = { 0 };
std::array<size_type, NumDimensions> extents = { block_size };
ViewSpec_t block_vs(offsets, extents);
DASH_LOG_DEBUG_VAR("DynamicPattern<1>.local_block_local >", block_vs);
return block_vs;
}
/**
* Maximum number of elements in a single block in the given dimension.
*
* \return The blocksize in the given dimension
*
* \see DashPatternConcept
*/
SizeType blocksize(
/// The dimension in the pattern
dim_t dimension) const
{
return _blocksize;
}
/**
* Maximum number of elements in a single block in all dimensions.
*
* \return The maximum number of elements in a single block assigned to
* a unit.
*
* \see DashPatternConcept
*/
SizeType max_blocksize() const
{
return _blocksize;
}
/**
* Maximum number of elements assigned to a single unit in total,
* equivalent to the local capacity of every unit in this pattern.
*
* \see DashPatternConcept
*/
inline SizeType local_capacity(
team_unit_t unit = UNDEFINED_TEAM_UNIT_ID) const
{
return _local_capacity;
}
/**
* The actual number of elements in this pattern that are local to the
* calling unit in total.
*
* \see blocksize()
* \see local_extent()
* \see local_capacity()
*
* \see DashPatternConcept
*/
inline SizeType local_size(
team_unit_t unit = UNDEFINED_TEAM_UNIT_ID) const
{
return _local_size;
}
/**
* The number of units to which this pattern's elements are mapped.
*
* \see DashPatternConcept
*/
inline IndexType num_units() const
{
return _nunits;
}
/**
* The maximum number of elements arranged in this pattern.
*
* \see DashPatternConcept
*/
inline IndexType capacity() const
{
return _size;
}
/**
* The number of elements arranged in this pattern.
*
* \see DashPatternConcept
*/
inline IndexType size() const
{
return _size;
}
/**
* The Team containing the units to which this pattern's elements are
* mapped.
*/
inline dash::Team & team() const
{
return *_team;
}
/**
* Distribution specification of this pattern.
*/
const DistributionSpec_t & distspec() const
{
return _distspec;
}
/**
* Size specification of the index space mapped by this pattern.
*
* \see DashPatternConcept
*/
SizeSpec_t sizespec() const
{
return SizeSpec_t(std::array<SizeType, 1> { _size });
}
/**
* Size specification of the index space mapped by this pattern.
*
* \see DashPatternConcept
*/
const std::array<SizeType, NumDimensions> & extents() const
{
return std::array<SizeType, 1> { _size };
}
/**
* Cartesian index space representing the underlying memory model of the
* pattern.
*
* \see DashPatternConcept
*/
const MemoryLayout_t & memory_layout() const
{
return _memory_layout;
}
/**
* Cartesian index space representing the underlying local memory model
* of this pattern for the calling unit.
* Not part of DASH Pattern concept.
*/
const LocalMemoryLayout_t & local_memory_layout() const
{
return _local_memory_layout;
}
/**
* Cartesian arrangement of the Team containing the units to which this
* pattern's elements are mapped.
*
* \see DashPatternConcept
*/
const TeamSpec_t & teamspec() const
{
return _teamspec;
}
/**
* Convert given global linear offset (index) to global cartesian
* coordinates.
*
* \see DashPatternConcept
*/
std::array<IndexType, NumDimensions> coords(
IndexType index) const
{
return std::array<IndexType, 1> { index };
}
/**
* Memory order followed by the pattern.
*/
constexpr static MemArrange memory_order()
{
return Arrangement;
}
/**
* Number of dimensions of the cartesian space partitioned by the pattern.
*/
constexpr static dim_t ndim()
{
return 1;
}
private:
DynamicPattern(const PatternArguments_t & arguments)
: DynamicPattern(
initialize_local_sizes(
arguments.sizespec().size(),
arguments.distspec(),
arguments.team()),
arguments)
{}
DynamicPattern(
const std::vector<size_type> & local_sizes,
const PatternArguments_t & arguments)
: _size(arguments.sizespec().size()),
_local_sizes(local_sizes),
_block_offsets(initialize_block_offsets(
_local_sizes)),
_memory_layout(std::array<SizeType, 1> { _size }),
_blockspec(initialize_blockspec(
_size,
_local_sizes)),
_distspec(arguments.distspec()),
_team(&arguments.team()),
_myid(_team->myid()),
_teamspec(arguments.teamspec()),
_nunits(_team->size()),
_blocksize(initialize_blocksize(
_size,
_distspec,
_nunits)),
_nblocks(_nunits),
_local_size(
initialize_local_extent(_team->myid())),
_local_memory_layout(std::array<SizeType, 1> { _local_size }),
_local_capacity(initialize_local_capacity())
{}
/**
* Initialize the size (number of mapped elements) of the Pattern.
*/
SizeType initialize_size(
const std::vector<size_type> & local_sizes) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.init_size()", local_sizes);
size_type size = 0;
for (size_type unit_idx = 0; unit_idx < local_sizes.size(); ++unit_idx) {
size += local_sizes[unit_idx];
}
DASH_LOG_TRACE_VAR("DynamicPattern.init_size >", size);
return size;
}
/**
* Initialize local sizes from pattern size, distribution spec and team
* spec.
*/
std::vector<size_type> initialize_local_sizes(
size_type total_size,
const DistributionSpec_t & distspec,
const dash::Team & team) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.init_local_sizes()", total_size);
std::vector<size_type> l_sizes;
auto nunits = team.size();
DASH_LOG_TRACE_VAR("DynamicPattern.init_local_sizes()", nunits);
if (nunits < 1) {
return l_sizes;
}
auto dist_type = distspec[0].type;
DASH_LOG_TRACE_VAR("DynamicPattern.init_local_sizes()", dist_type);
// Tiled and blocked distribution:
if (dist_type == dash::internal::DIST_BLOCKED ||
dist_type == dash::internal::DIST_TILE) {
auto blocksize = dash::math::div_ceil(total_size, nunits);
for (size_type u = 0; u < nunits; ++u) {
l_sizes.push_back(blocksize);
}
// Unspecified distribution (default-constructed pattern instance),
// set all local sizes to 0:
} else if (dist_type == dash::internal::DIST_UNDEFINED) {
for (size_type u = 0; u < nunits; ++u) {
l_sizes.push_back(0);
}
// No distribution, assign all indices to unit 0:
} else if (dist_type == dash::internal::DIST_NONE) {
l_sizes.push_back(total_size);
for (size_type u = 0; u < nunits-1; ++u) {
l_sizes.push_back(0);
}
// Incompatible distribution type:
} else {
DASH_THROW(
dash::exception::InvalidArgument,
"DynamicPattern expects TILE (" << dash::internal::DIST_TILE << ") " <<
"or BLOCKED (" << dash::internal::DIST_BLOCKED << ") " <<
"distribution, got " << dist_type);
}
DASH_LOG_TRACE_VAR("DynamicPattern.init_local_sizes >", l_sizes);
return l_sizes;
}
BlockSpec_t initialize_blockspec(
size_type size,
const std::vector<size_type> & local_sizes) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.init_blockspec", local_sizes);
BlockSpec_t blockspec({
static_cast<size_type>(local_sizes.size())
});
DASH_LOG_TRACE_VAR("DynamicPattern.init_blockspec >", blockspec);
return blockspec;
}
/**
* Initialize block size specs from memory layout, team spec and
* distribution spec.
*/
std::vector<size_type> initialize_block_offsets(
const std::vector<size_type> & local_sizes) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.init_block_offsets", local_sizes);
std::vector<size_type> block_offsets;
if (local_sizes.size() > 0) {
// NOTE: Assuming 1 block for every unit.
block_offsets.push_back(0);
for (size_type unit_idx = 0;
unit_idx < local_sizes.size()-1;
++unit_idx)
{
auto block_offset = block_offsets[unit_idx] +
local_sizes[unit_idx];
block_offsets.push_back(block_offset);
}
}
DASH_LOG_TRACE_VAR("DynamicPattern.init_block_offsets >", block_offsets);
return block_offsets;
}
/**
* Initialize block size specs from memory layout, team spec and
* distribution spec.
*/
SizeType initialize_blocksize(
SizeType size,
const DistributionSpec_t & distspec,
SizeType nunits) const
{
DASH_LOG_TRACE_VAR("DynamicPattern.init_blocksize", nunits);
if (nunits == 0) {
return 0;
}
// NOTE: Assuming 1 block for every unit.
return 1;
}
/**
* Initialize local block spec from global block spec.
*/
SizeType initialize_num_local_blocks(
SizeType num_blocks,
SizeType blocksize,
const DistributionSpec_t & distspec,
SizeType nunits,
SizeType local_size) const
{
auto num_l_blocks = local_size;
if (blocksize > 0) {
num_l_blocks = dash::math::div_ceil(
num_l_blocks,
blocksize);
} else {
num_l_blocks = 0;
}
DASH_LOG_TRACE_VAR("DynamicPattern.init_num_local_blocks", num_l_blocks);
return num_l_blocks;
}
/**
* Max. elements per unit (local capacity)
*/
SizeType initialize_local_capacity() const
{
SizeType l_capacity = 0;
if (_nunits == 0) {
return 0;
}
DASH_LOG_TRACE_VAR("DynamicPattern.init_lcapacity", _nunits);
// Local capacity is maximum number of elements assigned to a single unit,
// i.e. the maximum local size:
l_capacity = *(std::max_element(_local_sizes.begin(),
_local_sizes.end()));
DASH_LOG_DEBUG_VAR("DynamicPattern.init_lcapacity >", l_capacity);
return l_capacity;
}
/**
* Initialize block- and block size specs from memory layout, team spec
* and distribution spec.
*/
void initialize_local_range()
{
auto l_size = _local_size;
DASH_LOG_DEBUG_VAR("DynamicPattern.init_local_range()", l_size);
if (l_size == 0) {
_lbegin = 0;
_lend = 0;
} else {
// First local index transformed to global index
_lbegin = global(0);
// Index past last local index transformed to global index.
// global(l_size) would be out of range, so we use the global index
// to the last element and increment by 1:
_lend = global(l_size - 1) + 1;
}
DASH_LOG_DEBUG_VAR("DynamicPattern.init_local_range >", _lbegin);
DASH_LOG_DEBUG_VAR("DynamicPattern.init_local_range >", _lend);
}
/**
* Resolve extents of local memory layout for a specified unit.
*/
SizeType initialize_local_extent(
team_unit_t unit) const
{
DASH_LOG_DEBUG_VAR("DynamicPattern.init_local_extent()", unit);
DASH_LOG_DEBUG_VAR("DynamicPattern.init_local_extent()", _nunits);
if (_nunits == 0) {
return 0;
}
// Local size of given unit:
SizeType l_extent = _local_sizes[static_cast<int>(unit)];
DASH_LOG_DEBUG_VAR("DynamicPattern.init_local_extent >", l_extent);
return l_extent;
}
private:
/// Extent of the linear pattern.
SizeType _size;
/// Number of local elements for every unit in the active team.
std::vector<size_type> _local_sizes;
/// Block offsets for every unit. Prefix sum of local sizes.
std::vector<size_type> _block_offsets;
/// Global memory layout of the pattern.
MemoryLayout_t _memory_layout;
/// Number of blocks in all dimensions
BlockSpec_t _blockspec;
/// Distribution type (BLOCKED, CYCLIC, BLOCKCYCLIC or NONE) of
/// all dimensions. Defaults to BLOCKED.
DistributionSpec_t _distspec;
/// Team containing the units to which the patterns element are mapped
dash::Team * _team = nullptr;
/// The active unit's id.
team_unit_t _myid;
/// Cartesian arrangement of units within the team
TeamSpec_t _teamspec;
/// Total amount of units to which this pattern's elements are mapped
SizeType _nunits = 0;
/// Maximum extents of a block in this pattern
SizeType _blocksize = 0;
/// Number of blocks in all dimensions
SizeType _nblocks = 0;
/// Actual number of local elements of the active unit.
SizeType _local_size;
/// Local memory layout of the pattern.
LocalMemoryLayout_t _local_memory_layout;
/// Maximum number of elements assigned to a single unit
SizeType _local_capacity;
/// Corresponding global index to first local index of the active unit
IndexType _lbegin;
/// Corresponding global index past last local index of the active unit
IndexType _lend;
}; // class DynamicPattern<1>
} // namespace dash
#endif // DASH__DYNAMIC_PATTERN_H__INCLUDED
| 30.237167 | 79 | 0.635457 | [
"vector",
"model"
] |
18b85461b40841841fcd0aa56ac7c0777803d4f3 | 6,345 | h | C | include/muffin_core/array.h | brfish/muffin | 18b3f6baeb56a0777e575832366ce3b29caebcb4 | [
"MIT"
] | 3 | 2021-05-27T04:10:55.000Z | 2021-09-15T03:01:13.000Z | include/muffin_core/array.h | brfish/muffin | 18b3f6baeb56a0777e575832366ce3b29caebcb4 | [
"MIT"
] | null | null | null | include/muffin_core/array.h | brfish/muffin | 18b3f6baeb56a0777e575832366ce3b29caebcb4 | [
"MIT"
] | null | null | null | #ifndef _MUFFIN_CORE_ARRAY_H_
#define _MUFFIN_CORE_ARRAY_H_
#include "muffin_core/common.h"
#include "muffin_core/memory.h"
typedef struct MufArray_s {
muf_usize elementSize;
muf_usize capacity;
muf_usize size;
muf_rawptr data;
} MufArray;
typedef struct MufArrayConfig_s {
muf_usize elementSize;
muf_usize initCapacity;
muf_usize initDataCount;
muf_rawptr initData;
} MufArrayConfig;
MUF_API MufArray *_mufCreateArray(muf_usize elementSize);
/**
* @brief Create a dynamic array
* @tparam Type The type of the array
* @return The array object
*/
#define mufCreateArray(Type) _mufCreateArray(sizeof(Type))
MUF_API void mufInitArray(MufArray *array, const MufArrayConfig *config);
MUF_API void mufDestroyArray(MufArray *array);
MUF_API MufArray *mufCloneArray(const MufArray *array);
/**
* @brief Get the capacity of the array
* @param[in] array Array object
* @return Capacity of the array
*/
MUF_API muf_usize mufArrayGetCapacity(const MufArray *array);
/**
* @brief Get the size of the array
* @param[in] array Array object
* @return Size of the array
*/
MUF_API muf_usize mufArrayGetSize(const MufArray *array);
/**
* @brief Check if the array is empty
* @param[in] array The array object
* @return True if the array is empty
*/
MUF_API muf_bool mufArrayIsEmpty(const MufArray *array);
/**
* @brief Get the raw pointer to the underlying data of the array
* @param[in] array The array object
* @return The raw pointer to the data
*/
MUF_API muf_rawptr mufArrayGetData(MufArray *array);
MUF_API muf_index mufArrayFind(const MufArray *array, muf_crawptr element, MufEqualityComparator cmp);
MUF_API void mufArrayInsertRange(MufArray *array, muf_index index, muf_crawptr elements, muf_usize count);
MUF_API void mufArrayInsert(MufArray *array, muf_index index, muf_crawptr element);
MUF_API void mufArrayPush(MufArray *array, muf_crawptr element);
MUF_API void mufArraySet(MufArray *array, muf_index index, muf_crawptr data);
/**
* @brief
* @param[in] array The array object
* @param[in] index The indedx
* @param[out] dataOut The result
*/
MUF_API void mufArrayGet(MufArray *array, muf_index index, muf_rawptr dataOut);
/**
* @brief Get a reference or pointer to the element with index.
* @param[in] array The array object
* @param[in] index The index of the element that needs to be retrieved
* @param[out] dataRefOut The pointer to the target
*/
MUF_API muf_rawptr mufArrayGetRef(MufArray *array, muf_index index);
MUF_API muf_crawptr mufArrayGetCRef(const MufArray *array, muf_index index);
MUF_API void mufArrayGetFront(MufArray *array, muf_rawptr dataOut);
MUF_API muf_rawptr mufArrayGetFrontRef(MufArray *array);
MUF_API muf_crawptr mufArrayGetFrontCRef(const MufArray *array);
MUF_API void mufArrayGetBack(MufArray *array, muf_rawptr dataOut);
MUF_API muf_rawptr mufArrayGetBackRef(MufArray *array);
MUF_API muf_crawptr mufArrayGetBackCRef(const MufArray *array);
MUF_API void mufArrayRemove(MufArray *array, muf_index index);
/**
* @brief Remove an element from the array and call the destructor `Destroy`.
* @param[in] Array Specify the array.
* @param[in] Index Specify the index of the element to be removed.
* @param[in] Destroy Specify the desructor.
*/
#define mufArrayRemoveX(Array, Index, Destroy) \
do { muf_rawptr ref = mufArrayGetRef(Array, Index); Destroy(ref); mufArrayRemove(Array, Index); } while (0)
/**
* @brief Remove the elements in the range [first, last).
* @param[in] array Specify the array.
* @param[in] first Specify the lower bound of range.
* @param[in] last Specify the upper bound of range.
*/
MUF_API void mufArrayRemoveRange(MufArray *array, muf_index first, muf_index last);
/**
* @brief Remove the elements in the range [first, last).
* @param[in] Array Specify the array.
* @param[in] First Specify the lower bound of range.
* @param[in] Last Specify the upper bound of range.
* @param[in] Destroy Specify the destructor.
*/
#define mufArrayRemoveRangeX(Array, First, Last, Destroy) \
do { \
for (muf_index i = First; i < Last; ++i) { \
muf_rawptr ref = mufArrayGetRef(Array, i); Destroy(ref); \
} \
mufArrayRemoveRange(Array, First, Last); \
} while (0);
MUF_API void mufArrayPop(MufArray *array);
#define mufArrayPopX(Array, Destroy) \
do { muf_rawptr ref = mufArrayGetRef(Array, 0); Destroy(ref); mufArrayPop(Array); } while (0)
MUF_API void mufArrayClear(MufArray *array);
#define mufArrayClearX(Array, Destroy) \
mufArrayRemoveRangeX(Array, 0, Array->size, Destroy)
MUF_API muf_bool mufArrayFindAndRemove(MufArray *array, muf_index first, muf_index last, muf_crawptr target, MufComparator cmp);
MUF_API muf_bool mufArrayFindAndRemoveAll(MufArray *array, muf_index first, muf_index last, muf_crawptr target, MufComparator cmp);
MUF_API void mufArrayShrink(MufArray *array, muf_usize newCapacity);
MUF_API void mufArrayReserve(MufArray *array, muf_usize newCapacity);
MUF_API void mufArrayResize(MufArray *array, muf_usize newSize, muf_crawptr fillElement);
#define mufArrayResizeX(Array, NewSize, FillElement, Destroy) \
do { \
if (NewSize <= Array->size) { \
for (muf_index i = NewSize; i < Array->size; ++i) Destroy(mufArrayGetRef(Array, i)); \
} \
mufArrayResize(Array, NewSize, FillElement); \
} while (0)
#define mufArrayForeach(Array, UnaryFunc) \
do { \
for (muf_index i = 0; i < Array->size; ++i) { \
muf_rawptr ref = mufArrayGetRef(Array, i); UnaryFunc(ref); \
} \
} while (0)
typedef struct MufArrayIterator {
} MufArrayIterator;
MUF_API MufArrayIterator mufArrayIteratorBind(MufArray *array);
MUF_API MufArrayIterator mufArrayIteratorNext(MufArrayIterator it);
MUF_API muf_bool mufArrayIteratorHasNext(MufArrayIterator it);
#if defined(__GNUC__) && defined(MUF_ENABLE_GCC_EXTENSION)
# define mufArrayInsert_R(Array, Index, Element) \
do { __typeof__(Element) tmp = Element; mufArrayInsert(Array, Index, &tmp); } while(0)
# define mufArrayPush_R(Array, Element) \
do { __typeof__(Element) tmp = Element; mufArrayPush(Array, &tmp); } while(0)
# define mufArraySet_R(Array, Index, Element) \
do { __typeof__(Element) tmp = Element; mufArraySet(Array, Index, &tmp); } while(0)
#endif
#endif | 33.046875 | 131 | 0.735855 | [
"object"
] |
18c2dc50cedbf83479797d7502db6924e695e1be | 810 | h | C | Includes/Target.h | yurirocha15/Sentry-Gun | e891c4a1884d6ad725671aeac415d92ca11dc88d | [
"Apache-2.0"
] | null | null | null | Includes/Target.h | yurirocha15/Sentry-Gun | e891c4a1884d6ad725671aeac415d92ca11dc88d | [
"Apache-2.0"
] | null | null | null | Includes/Target.h | yurirocha15/Sentry-Gun | e891c4a1884d6ad725671aeac415d92ca11dc88d | [
"Apache-2.0"
] | null | null | null | /*
* Target.h
*
* Created on: Dec 5, 2014
* Author: yuri
*/
#ifndef TARGET_H_
#define TARGET_H_
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
#include <list>
#include <math.h>
using namespace std;
using namespace cv;
class Target {
public:
Target();
virtual ~Target();
int GetX();
int GetY();
void SetX(int);
void SetY(int);
int GetRadius();
int GetDistance();
void FindTarget(Mat);
bool TargetFound();
protected:
vector<Vec3f> FindCircles(Mat);
virtual Mat FindColor(Mat);
virtual void FindDistance();
int x;
int y;
float radius;
int distance;
bool targetFound;
list<float> radiusBuffer;
list<float>::iterator it2;
int counter;
float radiusAvg;
int i;
};
#endif /* TARGET_H_ */
| 15.576923 | 38 | 0.696296 | [
"vector"
] |
18c320a020d9065684790ae1862c647602a370e9 | 1,484 | h | C | src/include/ripscreen.h | prinsij/RogueReborn | 20e6ba4d2e61a47283747ba207a758e604fa89d9 | [
"BSD-3-Clause"
] | null | null | null | src/include/ripscreen.h | prinsij/RogueReborn | 20e6ba4d2e61a47283747ba207a758e604fa89d9 | [
"BSD-3-Clause"
] | null | null | null | src/include/ripscreen.h | prinsij/RogueReborn | 20e6ba4d2e61a47283747ba207a758e604fa89d9 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file ripscreen.h
* @author Team Rogue++
* @date December 08, 2016
*
* @brief Member declarations for the RIPScreen class
*/
#pragma once
#include <sstream>
#include <string>
#include <vector>
#include "../libtcod/include/libtcod.hpp"
#include "level.h"
#include "playerchar.h"
#include "uistate.h"
/** Items in the score table. */
struct ScoreItem;
/** Interface state for post-death/retirement,
* looking at the high-score table.
*
* Environment variables: input device (e.g., keyboard), monitor, and the file system
*/
class RIPScreen : public UIState {
public:
/** Constructor.
* @param cause Cause of death/retirement
* @param level Level on which player died/retired
*/
RIPScreen(PlayerChar*, Level* level, std::string cause);
/** Render. */
virtual void draw(TCODConsole*);
/** Handle player key input. */
virtual UIState* handleInput(TCOD_key_t);
private:
/** Width of grave */
int GRAVE_WIDTH = 14;
/** Leaves at bottom of grave */
std::string leaves;
/** Flowers at bottom of grave */
std::string flowers;
/** Reference to player. */
PlayerChar* player;
/** Vector of score table items read from file
* plus 1 created by recent death/retirement.
*/
std::vector<ScoreItem> scores;
/** Location of score record. */
const std::string SCORE_FILE = "scores.txt";
/** Indicates whether the player beat the game. */
bool wasVictory;
};
| 24.327869 | 86 | 0.648922 | [
"render",
"vector"
] |
18c882cfd7b07221c817b6492e5d274bc0105872 | 7,925 | h | C | sewer_graph/include/sewer_graph/earthlocation.h | robotics-upo/localization_siar | 6b4ca6f2bb56f7071479839dcbb88a6384eca091 | [
"MIT"
] | 4 | 2018-08-15T16:00:32.000Z | 2021-05-17T12:38:42.000Z | sewer_graph/include/sewer_graph/earthlocation.h | robotics-upo/localization_siar | 6b4ca6f2bb56f7071479839dcbb88a6384eca091 | [
"MIT"
] | null | null | null | sewer_graph/include/sewer_graph/earthlocation.h | robotics-upo/localization_siar | 6b4ca6f2bb56f7071479839dcbb88a6384eca091 | [
"MIT"
] | 3 | 2019-01-13T03:15:46.000Z | 2021-09-20T06:54:42.000Z | /*
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef EARTHLOCATION_H
#define EARTHLOCATION_H
#include <string>
#include "config.h"
#ifdef USE_KML
#include <kml/dom.h>
#endif
#include "functions/DegMinSec.h"
#include "functions/RealVector.h"
namespace sewer_graph {
//! @brief This class is used to represent an Earth Location in terms of longitude and latitude.
//! Uses decimal degrees as internal representation of latitude and longitude.
//! The altitude is stored in meters above the sea level.
//! ToString method gives many representations.
class EarthLocation
{
public:
//! @brief Default constructor. Creates a Location with latitude longitude and altitude
//! @param lat Latitude (degrees)
//! @param lon Longitude (degrees)
//! @param alt Altitude (meters)
//! @param time Time (seconds)
EarthLocation(double lat = 0.0, double lon = 0.0, double alt = 0.0, double time = 0.0);
//! @brief Gets an earth location from file
//! @param filename Filename
EarthLocation(const std::string &filename);
EarthLocation(const std::vector<double> &v);
//! @brief Creates a Location with the coordinates stored as DegMinSec
//! @param lat Latitude (degrees)
//! @param lon Longitude (degrees)
//! @param alt Altitude (meters)
//! @param time Time (seconds)
//! @param yaw Yaw angle (rads)
//! @param roll Roll angle (rads)
//! @param pitch Pitch (rads)
EarthLocation(const functions::DegMinSec &lat, const functions::DegMinSec &lon,
double alt = 0.0, double time = 0.0, double yaw = 0.0, double roll = 0.0, double pitch = 0.0);
#ifdef USE_KML
EarthLocation(kmldom::ElementPtr e);
#endif
//! @brief Shifts the position of this location. The distance to shift is given in meters.
//! @param north Shift distance in north direction
//! @param east Shift distance in east direction
//! @param time Shift time (seconds)
void shift(double north = 0.0, double east = 0.0, double alt = 0.0, double time = 0.0);
//! @brief Calculates the cartesian distance between two locations
//! @param e The other location
//! @return The planar distance
double distance(const EarthLocation &e);
//! @brief Represents the content of the class in deg min sec way
//! @return The string that represents the contents
virtual std::string toString(char separator =',') const;
//! @brief Represents the content of the class in a MATLAB row
//! @NOTE format is: latitude longitude altitude yaw roll pitch
//! @NOTE All angles are represented in degrees
//! @return The string that represents the contents
virtual std::string toMatlab() const;
//! @brief Represents the content of the class in a MATLAB row
//! @NOTE format is: x (related to longitude) y(related to latitude) altitude yaw roll pitch
//! @NOTE All angles are represented in degrees
//! @return The string that represents the contents
virtual std::string toMatlab(const EarthLocation ¢er) const;
#ifdef USE_KML
//! @brief Gets the a KML point placemark
//! @param name The name of the placemark
//! @return A pointer to the coordinates.
kmldom::PlacemarkPtr getKMLPlacemark(const std::string &name) const;
//! @brief Gets the a KML line placemark from this to the end
//! @param name The name of the placemark
//! @param end THe end point of the line
//! @param factory a KmlFactory properly initialized
//! @return A pointer to the coordinates.
kmldom::PlacemarkPtr getKMLLine(const string& name, const EarthLocation& end, kmldom::KmlFactory* factory) const;
#endif
//! @brief Gets the longitude coordinate in degrees
//! @return The coordinate
inline double getLongitude() const {return lon;}
//! @brief Gets the latitude coordinate in degrees
//! @return The coordinate
inline double getLatitude() const {return lat;}
//! @brief Gets the altitude coordinate
//! @return The coordinate
inline double getAltitude() const {return altitude;};
//! @brief Gets the altitude coordinate
//! @return The coordinate
inline double getTime() const {return time;};
inline void setLatitude(double lati) {lat = lati;}
inline void setLongitude(double longi) {lon = longi;}
inline void setAltitude(double alt) {altitude = alt;}
enum StringType {
EL_DEGMINSEC,
EL_DECIMAL,
EL_DEGMIN,
EL_ALTITUDE,
EL_RAD
};
//! @brief Sets the type of string returned by toString method
//! @param new_type The new type of string.
inline void setStringType(StringType new_type);
//! @brief Sets the new represent_time
inline void setRepresentTime(bool new_represent);
//! @brief Interpolates the state with another in a det time
//! @param post The other state
//! @param time The instant of time where the interpolation will be performed
//! @return The interpolated state
EarthLocation interpolate(const EarthLocation &post, double time);
//! @brief Translates absolute coordinates into relative coordinates
//! @return A vector whose first component is the north deviation, second the east deviation and finally the altitude (m)
functions::RealVector toRelative(const EarthLocation ¢er, bool reverse = true) const;
void fromRelative(const std::vector< double >& v_, const sewer_graph::EarthLocation& e, bool reverse = true);
protected:
double lon; // Stores the longitude in degrees
double lat; // Stores the latitude in degrees
double altitude; // Stores the altitude in meters above the sea level
double time; // Time when the location was reached (optional)
double pitch;
double yaw;
double roll;
// These will define the information to represent in toString
// And the format
StringType stype; // Defines the format of lat lon and if the altitude will be represented
bool represent_time; // If true, the time is added
//! @brief Initializes the class with latitude and longitude in decimal degrees
void init(double lat, double lon = 0.0, double alt = 0.0, double time = 0.0,
double yaw = 0.0, double roll = 0.0, double pitch = 0.0);
//! @brief Initializes the class with DegMinSec in latitude and longitude
void init(const functions::DegMinSec &lat, const functions::DegMinSec &lon,
double alt = 0.0, double time = 0.0, double yaw = 0.0, double roll = 0.0, double pitch = 0.0);
//! @brief Gets an earth location from MATLAB like file
//! @param filename Filename
//! @retval true Location successfully loaded
//! @retval false Location could not be loaded
bool init(const std::string &filename);
void init(const std::vector<double> &v);
#ifdef USE_KML
bool init(kmldom::ElementPtr e);
#endif
inline void init() {
stype = EL_DEGMIN;
}
static const double equatorial_shift;
static const double latitude_shift;
};
inline void EarthLocation::setStringType(StringType new_type) {
stype = new_type;
}
inline void EarthLocation::setRepresentTime(bool new_represent) {
represent_time = new_represent;
}
}
#endif // EARTHLOCATION_H
| 37.738095 | 129 | 0.705489 | [
"vector"
] |
18cba8c5a69f47ebc47d0b4f34d250e7bda43753 | 6,019 | h | C | chrome/browser/ui/views/panels/panel_stack_view.h | MIPS/external-chromium_org | e31b3128a419654fd14003d6117caa8da32697e7 | [
"BSD-3-Clause"
] | 2 | 2015-08-04T15:17:59.000Z | 2016-10-23T08:11:14.000Z | chrome/browser/ui/views/panels/panel_stack_view.h | carlosavignano/android_external_chromium_org | 2b5652f7889ccad0fbdb1d52b04bad4c23769547 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/views/panels/panel_stack_view.h | carlosavignano/android_external_chromium_org | 2b5652f7889ccad0fbdb1d52b04bad4c23769547 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2017-07-31T19:09:52.000Z | 2019-01-04T18:48:50.000Z | // Copyright (c) 2013 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.
#ifndef CHROME_BROWSER_UI_VIEWS_PANELS_PANEL_STACK_VIEW_H_
#define CHROME_BROWSER_UI_VIEWS_PANELS_PANEL_STACK_VIEW_H_
#include <list>
#include <map>
#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "chrome/browser/ui/panels/native_panel_stack_window.h"
#include "ui/base/animation/animation_delegate.h"
#include "ui/views/focus/widget_focus_manager.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_observer.h"
#if defined(OS_WIN)
#include "chrome/browser/ui/views/panels/taskbar_window_thumbnailer_win.h"
#include "ui/base/win/hwnd_subclass.h"
#endif
namespace ui {
class LinearAnimation;
}
namespace views {
class Widget;
}
// A native window that acts as the owner of all panels in the stack, in order
// to make all panels appear as a single window on the taskbar or launcher.
class PanelStackView : public NativePanelStackWindow,
public views::WidgetObserver,
public views::WidgetDelegateView,
public views::WidgetFocusChangeListener,
#if defined(OS_WIN)
public ui::HWNDMessageFilter,
public TaskbarWindowThumbnailerDelegateWin,
#endif
public ui::AnimationDelegate {
public:
explicit PanelStackView(NativePanelStackWindowDelegate* delegate);
virtual ~PanelStackView();
protected:
// Overridden from NativePanelStackWindow:
virtual void Close() OVERRIDE;
virtual void AddPanel(Panel* panel) OVERRIDE;
virtual void RemovePanel(Panel* panel) OVERRIDE;
virtual void MergeWith(NativePanelStackWindow* another) OVERRIDE;
virtual bool IsEmpty() const OVERRIDE;
virtual bool HasPanel(Panel* panel) const OVERRIDE;
virtual void MovePanelsBy(const gfx::Vector2d& delta) OVERRIDE;
virtual void BeginBatchUpdatePanelBounds(bool animate) OVERRIDE;
virtual void AddPanelBoundsForBatchUpdate(
Panel* panel, const gfx::Rect& new_bounds) OVERRIDE;
virtual void EndBatchUpdatePanelBounds() OVERRIDE;
virtual bool IsAnimatingPanelBounds() const OVERRIDE;
virtual void Minimize() OVERRIDE;
virtual bool IsMinimized() const OVERRIDE;
virtual void DrawSystemAttention(bool draw_attention) OVERRIDE;
virtual void OnPanelActivated(Panel* panel) OVERRIDE;
private:
typedef std::list<Panel*> Panels;
// The map value is old bounds of the panel.
typedef std::map<Panel*, gfx::Rect> BoundsUpdates;
// Overridden from views::WidgetDelegate:
virtual string16 GetWindowTitle() const OVERRIDE;
virtual gfx::ImageSkia GetWindowAppIcon() OVERRIDE;
virtual gfx::ImageSkia GetWindowIcon() OVERRIDE;
virtual views::Widget* GetWidget() OVERRIDE;
virtual const views::Widget* GetWidget() const OVERRIDE;
virtual void DeleteDelegate() OVERRIDE;
// Overridden from views::WidgetObserver:
virtual void OnWidgetDestroying(views::Widget* widget) OVERRIDE;
// Overridden from views::WidgetFocusChangeListener:
virtual void OnNativeFocusChange(gfx::NativeView focused_before,
gfx::NativeView focused_now) OVERRIDE;
// Overridden from AnimationDelegate:
virtual void AnimationEnded(const ui::Animation* animation) OVERRIDE;
virtual void AnimationProgressed(const ui::Animation* animation) OVERRIDE;
// Updates the bounds of panels as specified in batch update data.
void UpdatePanelsBounds();
// Notifies the delegate that the updates of the panel bounds are completed.
void NotifyBoundsUpdateCompleted();
// Computes/updates the minimum bounds that could fit all panels.
gfx::Rect GetStackWindowBounds() const;
void UpdateStackWindowBounds();
views::Widget* CreateWindowWithBounds(const gfx::Rect& bounds);
void EnsureWindowCreated();
// Makes the stack window own the panel window such that multiple panels
// stacked together could appear as a single window on the taskbar or
// launcher.
static void MakeStackWindowOwnPanelWindow(Panel* panel,
PanelStackView* stack_window);
#if defined(OS_WIN)
// Overridden from ui::HWNDMessageFilter:
virtual bool FilterMessage(HWND hwnd,
UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* l_result) OVERRIDE;
// Overridden from TaskbarWindowThumbnailerDelegateWin:
virtual std::vector<HWND> GetSnapshotWindowHandles() const OVERRIDE;
// Updates the live preview snapshot when something changes, like
// adding/removing/moving/resizing a stacked panel.
void RefreshLivePreviewThumbnail();
// Updates the bounds of the widget window in a deferred way.
void DeferUpdateNativeWindowBounds(HDWP defer_window_pos_info,
views::Widget* window,
const gfx::Rect& bounds);
#endif
NativePanelStackWindowDelegate* delegate_;
views::Widget* window_; // Weak pointer, own us.
bool is_closing_;
// Tracks all panels that are enclosed by this window.
Panels panels_;
// Is the taskbar icon of the underlying window being flashed in order to
// draw the user's attention?
bool is_drawing_attention_;
#if defined(OS_WIN)
// The custom live preview snapshot is always provided for the stack window.
// This is because the system might not show the snapshot correctly for
// a small window, like collapsed panel.
scoped_ptr<TaskbarWindowThumbnailerWin> thumbnailer_;
#endif
// For batch bounds update.
bool animate_bounds_updates_;
bool bounds_updates_started_;
BoundsUpdates bounds_updates_;
// Used to animate the bounds changes at a synchronized pace.
scoped_ptr<ui::LinearAnimation> bounds_animator_;
DISALLOW_COPY_AND_ASSIGN(PanelStackView);
};
#endif // CHROME_BROWSER_UI_VIEWS_PANELS_PANEL_STACK_VIEW_H_
| 37.385093 | 78 | 0.733178 | [
"vector"
] |
18cbe7a45d0378a88765dd4537ba448555c08a01 | 901 | h | C | pandatool/src/daeegg/pre_fcollada_include.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | 3 | 2020-01-02T08:43:36.000Z | 2020-07-05T08:59:02.000Z | pandatool/src/daeegg/pre_fcollada_include.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | pandatool/src/daeegg/pre_fcollada_include.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | 1 | 2020-03-11T17:38:45.000Z | 2020-03-11T17:38:45.000Z | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file pre_fcollada_include.h
* @author rdb
* @date 2008-10-04
*/
// This file defines some stuff that need to be defined before one includes
// FCollada.h
#ifndef PRE_FCOLLADA_INCLUDE_H
#define PRE_FCOLLADA_INCLUDE_H
#ifdef FCOLLADA_VERSION
#error You must include pre_fcollada_include.h before including FCollada.h!
#endif
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <winsock2.h>
#endif
// FCollada expects LINUX to be defined on linux
#ifdef IS_LINUX
#ifndef LINUX
#define LINUX
#endif
#endif
#define NO_LIBXML
#define FCOLLADA_NOMINMAX
#endif
| 21.452381 | 77 | 0.758047 | [
"3d"
] |
18d72eac4a2e55981961c3f9819a770721c113e6 | 1,309 | h | C | DataFormats/EgammaCandidates/interface/GsfElectronFwd.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | DataFormats/EgammaCandidates/interface/GsfElectronFwd.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | DataFormats/EgammaCandidates/interface/GsfElectronFwd.h | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z |
#ifndef EgammaReco_GsfElectronFwd_h
#define EgammaReco_GsfElectronFwd_h
#include "DataFormats/Common/interface/Ref.h"
#include "DataFormats/Common/interface/RefProd.h"
#include "DataFormats/Common/interface/RefVector.h"
#include <vector>
#include "DataFormats/EgammaCandidates/interface/GsfElectron.h"
namespace reco {
class GsfElectron;
/// collection of GsfElectron objects
typedef std::vector<GsfElectron> GsfElectronCollection;
//typedef GsfElectronCollection PixelMatchGsfElectronCollection ;
/// reference to an object in a collection of GsfElectron objects
typedef edm::Ref<GsfElectronCollection> GsfElectronRef;
//typedef GsfElectronRef PixelMatchGsfElectronRef ;
/// reference to a collection of GsfElectron objects
typedef edm::RefProd<GsfElectronCollection> GsfElectronRefProd;
//typedef GsfElectronRefProd PixelMatchGsfElectronRefProd ;
/// vector of objects in the same collection of GsfElectron objects
typedef edm::RefVector<GsfElectronCollection> GsfElectronRefVector;
//typedef GsfElectronRefVector PixelMatchGsfElectronRefVector ;
/// iterator over a vector of reference to GsfElectron objects
typedef GsfElectronRefVector::iterator GsfElectron_iterator;
//typedef GsfElectron_iterator PixelMatchGsfElectron_iterator ;
} // namespace reco
#endif
| 33.564103 | 69 | 0.81589 | [
"object",
"vector"
] |
18d93ab8bc6dc6035fb42f6fca5708f34e4270b0 | 1,118 | h | C | villagebus/modules/mod_telephony.h | ithoq/afrimesh | 3f678b224569d90768cba2a84d98a53fd122cbcf | [
"BSD-3-Clause"
] | 2 | 2015-03-30T15:43:00.000Z | 2020-04-28T23:36:25.000Z | villagebus/modules/mod_telephony.h | ithoq/afrimesh | 3f678b224569d90768cba2a84d98a53fd122cbcf | [
"BSD-3-Clause"
] | null | null | null | villagebus/modules/mod_telephony.h | ithoq/afrimesh | 3f678b224569d90768cba2a84d98a53fd122cbcf | [
"BSD-3-Clause"
] | null | null | null | /**
* Afrimesh: easy management for mesh networks
*
* This software is licensed as free software under the terms of the
* New BSD License. See /LICENSE for more information.
*/
#ifndef MOD_TELEPHONY_H
#define MOD_TELEPHONY_H
#include <villagebus.h>
// TODO -> s/mod_telephony/mod_handset
/* - telephony ---------------------------------------------------------- */
typedef struct _telephony {
vtable* _vt[0];
} telephony;
extern vtable* telephony_vt;
extern object* _Telephony;
extern telephony* Telephony;
extern symbol* s_telephony;
extern symbol* s_telephony_sip;
extern symbol* s_telephony_callme;
// base
void telephony_init();
telephony* telephony_print(closure* c, telephony* self);
const fexp* telephony_evaluate(closure* c, telephony* self, const fexp* expression);
// names
const fexp* telephony_sip_asterisk(closure* c, telephony* self, const fexp* message);
const fexp* telephony_callme (closure* c, telephony* self, const fexp* message);
// utilities
struct json_object* asterisk_sip_peers_parser(const char* line, size_t length);
#endif /* MOD_TELEPHONY_H */
| 27.268293 | 85 | 0.703936 | [
"mesh",
"object"
] |
18e161f0b0b12d5a626f0083a7e9478b17825ad2 | 2,639 | h | C | inet/src/inet/power/contract/IEnergySink.h | googleinterns/vectio | 0d8ef1d504c821de733110c82b16b2ae43332c5c | [
"Apache-2.0"
] | 1 | 2020-05-21T07:48:00.000Z | 2020-05-21T07:48:00.000Z | Simulation/OMNeT++/inet/src/inet/power/contract/IEnergySink.h | StarStuffSteve/masters-research-project | 47c1874913d0961508f033ca9a1144850eb8f8b7 | [
"Apache-2.0"
] | 4 | 2020-07-06T15:58:14.000Z | 2020-07-15T21:56:36.000Z | Simulation/OMNeT++/inet/src/inet/power/contract/IEnergySink.h | StarStuffSteve/masters-research-project | 47c1874913d0961508f033ca9a1144850eb8f8b7 | [
"Apache-2.0"
] | 1 | 2020-10-02T04:12:51.000Z | 2020-10-02T04:12:51.000Z | //
// Copyright (C) 2013 OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 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 Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
#ifndef __INET_IENERGYSINK_H
#define __INET_IENERGYSINK_H
#include "IEnergyGenerator.h"
namespace inet {
namespace power {
/**
* This is an interface that should be implemented by energy sink models to
* integrate with other parts of the power model. Energy generators will connect
* to an energy sink, and they will notify it when the amount of power they
* generate changes.
*
* See the corresponding NED file for more details.
*
* @author Levente Meszaros
*/
class INET_API IEnergySink
{
public:
/**
* The signal that is used to publish power generation changes.
*/
static simsignal_t powerGenerationChangedSignal;
public:
virtual ~IEnergySink() {}
/**
* Returns the number of energy generators.
*/
virtual int getNumEnergyGenerators() const = 0;
/**
* Returns the energy generator for the provided id.
*/
virtual const IEnergyGenerator *getEnergyGenerator(int energyGeneratorId) const = 0;
/**
* Adds a new energy generator to the energy sink and returns its id.
*/
virtual int addEnergyGenerator(const IEnergyGenerator *energyGenerator) = 0;
/**
* Removes a previously added energy generator from this energy sink.
*/
virtual void removeEnergyGenerator(int energyGeneratorId) = 0;
/**
* Returns the current total power generation in the range [0, +infinity).
*/
virtual W getTotalPowerGeneration() const = 0;
/**
* Returns the generated power for the provided energy generator in the
* range [0, +infinity).
*/
virtual W getPowerGeneration(int energyGeneratorId) const = 0;
/**
* Changes the generated power for the provided energy generator in the
* range [0, +infinity).
*/
virtual void setPowerGeneration(int energyGeneratorId, W generatedPower) = 0;
};
} // namespace power
} // namespace inet
#endif // ifndef __INET_IENERGYSINK_H
| 28.684783 | 88 | 0.70557 | [
"model"
] |
18e751900032b0b1f9fd34d77d866c7b4f07af20 | 47,719 | h | C | app/src/src/hyppox/mapper.h | paolapesantez/Hyppo-XD | f3a649f2757076224b2d0e1ecfbc9a762b29508e | [
"MIT"
] | null | null | null | app/src/src/hyppox/mapper.h | paolapesantez/Hyppo-XD | f3a649f2757076224b2d0e1ecfbc9a762b29508e | [
"MIT"
] | 3 | 2020-08-27T02:43:30.000Z | 2022-03-15T01:48:39.000Z | app/src/src/hyppox/mapper.h | paolapesantez/Hyppo-XD | f3a649f2757076224b2d0e1ecfbc9a762b29508e | [
"MIT"
] | 1 | 2022-03-14T22:29:59.000Z | 2022-03-14T22:29:59.000Z | /**************************************************************************************************
Copyright © 2016-2018 Md.Kamruzzaman. All rights reserved.
The generated code is released under following licenses:
GNU GENERAL PUBLIC LICENSE, Version 3, 29 June 2007
--------------------------------------------------------------------------------------------------
File name: mapper.h
Objective: Create mapper from high dimensional data
Additional information: NA
--------------------------------------------------------------------------------------------------
Contributors Date Task details
------------------------- ---------- --------------------
Md. Kamruzzaman 01/03/2018 Initial version
**************************************************************************************************/
#ifndef mapper_h
#define mapper_h
#include "unionFindWithPathCompression.h"
#include "simplicialComplex.h"
#include "graph.h"
#include <vector>
namespace hyppox {
namespace mapper{
template<typename PerfType, typename DPType>
class ManageCluster{
public:
std::list<PerfType*> phList;
std::list<DPType*> dpList;
ManageCluster()=default;
~ManageCluster()=default;
void AddToCluster(PerfType* ph){this->phList.push_back(ph);}
void GetPerfTypeListOfThisCluster(std::list<PerfType*> *ph){ph->insert(ph->begin(), this->phList.begin(), this->phList.end());}
void AddToCluster(DPType* dp){this->dpList.push_back(dp);}
void GetPerfTypeListOfThisCluster(std::list<DPType*> *dp){dp->insert(dp->begin(), this->dpList.begin(), this->dpList.end());}
};
template<typename ClusterIDType>
class Grid{
public:
std::vector<float> center;
ClusterIDType _id;
std::unordered_set<ClusterIDType> clusterIdList;
Grid(){
this->clusterIdList.clear();
this->center.assign(hyppox::Config::FILTER, 0);
}
~Grid(){
this->center.clear();
}
void GetClusterID(std::unordered_set<ClusterIDType>* mainClsIDSet){
ClusterIDType ide =0;
for(auto itr=clusterIdList.begin(); itr!=clusterIdList.end(); itr++){
ide = *itr;
mainClsIDSet->insert(ide);
}
}
};
template<typename NodeType>
class AnEdge{
private:
NodeType node1;
NodeType node2;
std::string _id;
public:
AnEdge(NodeType n1, NodeType n2){
this->node1 = n1;
this->node2 = n2;
// An undirected edge from low cluster id to high cluster id
_id = (n1<n2)?std::to_string(n1)+"#"+std::to_string(n2):std::to_string(n2)+"#"+std::to_string(n1);
}
~AnEdge()=default;
NodeType getNode1(){return node1;}
NodeType getNode2(){return node2;}
};
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
class Mapper{
public:
using GRType = Grid<ClusterIDType>;
using EType = AnEdge<ClusterIDType>;
using MCType = ManageCluster<PerfType,DPType>;
using DBType = cluster::DBScan<PerfType,ClusterIDType,RowIDType,ClusterType>;
using SCType = SimplicialComplex<PerfType,ClusterIDType>;
using ClsType = cluster::Cluster<PerfType,ClusterIDType>;
//using MType = Mapper<PerfType,DPType,QTType,GType,ClusterIDType,RowIDType>;
Mapper();
~Mapper();
std::string createMapper(GType* graph);
private:
std::vector<std::vector<GRType>> mesh;
QTType treeRoot; // To store data for nD (n>1) filter
std::vector<float> minPos;
std::vector<float> maxPos;
std::vector<float> gridLength;
std::list<EType*> edgeList;
std::unordered_map<size_t,GRType*> gridMap;
std::unordered_map<long, long> connectedComponents;
int storeData(std::unordered_map<std::string, size_t>& memMap, std::unordered_map<std::string, size_t>& pieMap);
int createFilter(std::unordered_map<std::string, size_t>& memMap, std::unordered_map<std::string, size_t>& pieMap);
void clearClusterInformation();
void createCluster(std::list<PerfType*> *pList, bool setUniqueId);
void assignUniqueClusterIds();
void createUniqueClusters();
bool isEligibleForClustering(std::vector<float> &_min, std::vector<float> &_max, size_t boxID);
bool isValidCluster(std::list<PerfType *> *pList, std::unordered_set<size_t>* mainClsID);
void manageCluster(std::list<PerfType *> *pList, size_t minClsId, size_t maxClsId, std::unordered_set<size_t>* mainClsID);
void assignClusterIdsForOverlapingRegion(std::vector<float> overlap);
void assignClusterIdsForOverlapingRegion(std::list<PerfType*>* overlappedPhList, std::vector<float> overlap);
void setOverlappedIndv(std::unordered_set<size_t> *indvSet, std::list<PerfType *> *clPhList, std::list<PerfType *> *overlappedPhList, std::unordered_set<std::string>* edgeSet);
void generateEdgeListFromOverlappingClusters(std::list<PerfType*>* overlappedPhList, std::vector<float> overlap);
void addSimplicialComplex(SCType *sc, float overlap);
std::string generateSimplicesForPersistentHomology();
void computeConnectedComponents(size_t &ccSize);
void constructGraphComponents(GType*& graph);
void constructGraph(GType*& graph);
void testRange(std::vector<float>& _min, std::vector<float>& _max, std::list<PerfType*>& clPhList);
};
////////////////// Public methods ////////////////////
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::Mapper(){
GRType g;
std::vector<GRType> v(hyppox::Config::WINDOWS[1], g);
this->mesh.assign(hyppox::Config::WINDOWS[0], v);
this->minPos.assign(hyppox::Config::FILTER, 0.0);
this->maxPos.assign(hyppox::Config::FILTER, 0.0);
this->gridLength.assign(hyppox::Config::FILTER, 0.0);
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::~Mapper(){
this->mesh.clear();
this->minPos.clear();
this->maxPos.clear();
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
std::string Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::createMapper(GType* graph){
int a = this->createFilter(graph->memIndexMap, graph->pieIndexMap);
if(a==-1){
return "File dataformat error. Please check data type in the column based on instruction.";
}else if(a==-2){
return "Can not read data file. Please check file path and permission.";
}
clock_t t1, t2;
t1 = clock();
this->createUniqueClusters();
std::string r="";
if(hyppox::Config::PRINT_BARCODE){
r = this->generateSimplicesForPersistentHomology();
}else{
this->constructGraph(graph);
t2 = clock();
std::vector<std::string> _time = getTime((float)(t2-t1)/CLOCKS_PER_SEC);
std::cout<<"Time to complete mapper (filter, cluster, graph construction): "<<_time[0]<<_time[1]<<std::endl;
}
return r;
}
////////////////// Private methods /////////////////////////
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
int Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::storeData(std::unordered_map<std::string, size_t>& memMap, std::unordered_map<std::string, size_t>& pieMap){
clock_t t1, t2;
t1 = clock();
FHType fileHandler(hyppox::Config::DATA_FILE_NAME);
int status;
if((status=fileHandler.ReadFileData(&this->treeRoot, this->minPos, this->maxPos, memMap, pieMap))!=0){
return status;
}
t2 = clock();
std::vector<std::string> _time = getTime((float)(t2-t1)/CLOCKS_PER_SEC);
//cout<<"Total time:"<<_time[0]<<_time[1]<<endl;
//this->treeRoot.PrintQuadTree();
//cout<<"\nTotal data:"<<c<<":"<<QuadNode::totalChildren;
std::cout<<"\nData file read and store in memory time: "<<_time[0]<<_time[1]<<std::endl;
return 0;
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
int Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::createFilter(std::unordered_map<std::string, size_t>& memMap, std::unordered_map<std::string, size_t>& pieMap){
int a = this->storeData(memMap, pieMap);
if(a<0){
return a;
}
for(short i=0; i<hyppox::Config::FILTER; i++){
this->gridLength[i] = (hyppox::Config::WINDOWS[i]>0)?(this->maxPos[i] - this->minPos[i])/hyppox::Config::WINDOWS[i]:(this->maxPos[i] - this->minPos[i]);
}
float start_x = this->minPos[0], start_y = 0;
for(int i=0; i<hyppox::Config::WINDOWS[0]; i++){
if(hyppox::Config::FILTER>1) start_y = this->minPos[1];
else start_y = 0;
for(int j=0; j<hyppox::Config::WINDOWS[1]; j++){
this->mesh[i][j].center[0] = start_x + (this->gridLength[0]/2);
if(hyppox::Config::FILTER>1) this->mesh[i][j].center[1] = start_y + (this->gridLength[1]/2);
else this->mesh[i][j].center[1] = start_y;
if(hyppox::Config::FILTER>1) start_y += this->gridLength[1];
}
start_x += this->gridLength[0];
}
return 0;
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::clearClusterInformation(){
std::list<PerfType*> clPhList;
std::list<DPType*> dpList;
clPhList.clear();
this->treeRoot.ResetClusterInformation();
ClsType::SetClusterID(0);
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::createCluster(std::list<PerfType*> *pList, bool setUniqueId){
//clock_t t1, t2;
//t1 = clock();
ClsType *cluster = new DBType(hyppox::Config::CLUSTER_PARAM[0], hyppox::Config::CLUSTER_PARAM[1], setUniqueId);
cluster->doClustering(pList);
//t2 = clock();
//std::cout<<"\nClustering completed..."<<(t2-t1)/CLOCKS_PER_SEC<<endl;
delete cluster;
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::assignUniqueClusterIds(){
std::cout<<"\nCompleted filtering step"<<std::endl<<"Started clustering...\n";
std::vector<float> _min(hyppox::Config::FILTER, 0.0), _max(hyppox::Config::FILTER, 0.0);
std::list<PerfType*> clPhList;
std::list<DPType*> dpList;
size_t boxID = 1, lastID, thisID;
if(this->mesh.size()>0){
for(int j=0; j<hyppox::Config::WINDOWS[1];j++){
for(int i=0; i<hyppox::Config::WINDOWS[0]; i++){
for(short f=0; f<hyppox::Config::FILTER; f++){
float c = this->mesh[i][j].center[f];
float l = this->gridLength[f]/2;
_min[f] = c - l;
_max[f] = c + l;
if(_min[f] < this->minPos[f]) _min[f] = this->minPos[f];
if(_max[f] > this->maxPos[f]) _max[f] = this->maxPos[f];
}
clPhList.clear();
dpList.clear();
this->treeRoot.SearchSurface(_min, _max, &clPhList, &dpList, boxID);
//std::cout<<"("<<i<<","<<j<<")={("<<_min[0]<<","<<_min[1]<<"),("<<_max[0]<<","<<_max[1]<<")}: ";
if(clPhList.size() > 0){
//testRange(_min, _max, clPhList);
// The following commented code is just to test whether same point contians different PerfTypes or not
/*map<size_t, list<vector<float>>> _tmpCV;
map<size_t, list<vector<float>>>::iterator _tItr;
for(PerfType* ph:clPhList){
vector<float> _clsVal;
ph->getClusterValue(&_clsVal);
if((_tItr=_tmpCV.find(ph->getID()))==_tmpCV.end()){
list<vector<float>> _lv;
_lv.push_back(_clsVal);
_tmpCV.insert(make_pair(ph->getID(), _lv));
}else{
_tItr->second.push_back(_clsVal);
}
}
cout<<"Total:"<<_tmpCV.size()<<endl;
for(_tItr=_tmpCV.begin(); _tItr!=_tmpCV.end(); _tItr++){
cout<<_tItr->first<<"=>{";
for(vector<float> _clsVal:_tItr->second){
cout<<"(";
for(float _cv:_clsVal){
cout<<_cv<<",";
}
cout<<"),";
}
cout<<"}\n";
}
cout<<endl<<"-------------------\n";*/
lastID = ClsType::GetClusterID();
//std::cout<<"Data points:"<<dpList.size()<<", clusterPts:"<<clPhList.size();
time_t _t1 = clock();
this->createCluster(&clPhList, true);
time_t _t2 = clock();
float _time = (float)(_t2-_t1)/CLOCKS_PER_SEC;
std::string unit = "(sec)";
if(_time<1){
_time = ((float)(_t2-_t1)*1000)/CLOCKS_PER_SEC;
unit = "(ms)";
}
//std::cout<<" Total time to cluster:"<<_time<<unit;
thisID = ClsType::GetClusterID();
//std::cout<<" ID:"<<thisID<<std::endl;
GRType* gr = &this->mesh[i][j];
gr->_id = boxID;
if(thisID-lastID>1){
for(ClusterIDType i=lastID+1; i<=thisID; i++){
gr->clusterIdList.insert(i);
}
}else{
gr->clusterIdList.insert(thisID);
}
this->gridMap.insert(std::make_pair(boxID, gr));
}
//std::cout<<":"<<ClsType::GetClusterID()<<std::endl;
boxID++;
}
}
}
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::createUniqueClusters(){
this->clearClusterInformation();
this->assignUniqueClusterIds();
ClsType::SetClusterID(0);
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
bool Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::isEligibleForClustering(std::vector<float> &_min, std::vector<float> &_max, size_t boxID){
std::unordered_set<size_t> bxIdList;
this->treeRoot.SearchDataPoints(_min, _max, &bxIdList);
if(bxIdList.size()>0){
if(bxIdList.find(boxID) != bxIdList.end()){
return true;
}
}
return false;
}
// A valid cluster contains points of both in box and out of box
// Means the points comes from both adjacent boxes
// Invalid cluster contains either in box points or out box points
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
bool Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::isValidCluster(std::list<PerfType *> *pList, std::unordered_set<size_t> *mainClsID){
bool alienPoints = false, knownPoints = false;
for(auto itr=pList->begin(); itr!=pList->end(); itr++){
PerfType* ph = *itr;
if(mainClsID->find(ph->GetUniqueID())==mainClsID->end()){
alienPoints = true;
}else{
knownPoints = true;
}
}
if(hyppox::Config::PRINT_BARCODE){
return knownPoints;
}
return (alienPoints&&knownPoints);
}
/*
When increasing the box sides, there could be few cases:
Case 1: Overlapping area does not contains any new points
Case 2: Overlapping area contains points
When we are doing clustering in a box, for case 1, all points of a box are clustered again and it is redundent
For case 2, when we are clustering a box, it could happen that only new points create a cluster.
This function checks both cases and avoid clustering points at both scenarios.
*/
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::manageCluster(std::list<PerfType *> *pList, size_t minClsId, size_t maxClsId, std::unordered_set<size_t>* mainClsID){
// Create bucket based on newly created cluster ids
MCType* cluster = new MCType[maxClsId-minClsId+1];
std::unordered_set<size_t> clsRange;
for(size_t i=minClsId; i<=maxClsId; i++){
clsRange.insert(i);
}
// assign points at each bucket based on cluster id
for(auto itr=pList->begin(); itr!=pList->end(); itr++){
PerfType* ph = *itr;
std::vector<ClusterIDType> clsIDList(hyppox::Config::TOTAL_CLUSTER_IDS, 0);
ph->GetIDList(clsIDList);
for(short i=0; i<hyppox::Config::TOTAL_CLUSTER_IDS; i++){
if(clsIDList[i] > 0 && clsRange.find(clsIDList[i]) != clsRange.end()){
cluster[clsIDList[i]-minClsId].AddToCluster(ph);
}
}
}
clsRange.clear();
std::list<PerfType *> cphList;
cphList.insert(cphList.begin(), pList->begin(), pList->end());
pList->clear();
std::list<PerfType *> phList;
std::unordered_set<size_t> phListTrack;
for(size_t i=minClsId; i<=maxClsId; i++){
cluster[i-minClsId].GetPerfTypeListOfThisCluster(&phList);
if(!isValidCluster(&phList, mainClsID)){
for(auto itr=phList.begin(); itr!=phList.end(); itr++){
PerfType* ph = *itr;
std::vector<ClusterIDType> idList;
ph->GetIDList(idList);
for(short j=0; j<hyppox::Config::TOTAL_CLUSTER_IDS; j++){
if(idList[j] == i){
ph->DecreaseClusterIndex(j);
break;
}
}
}
}
for(auto itr=phList.begin(); itr!=phList.end(); itr++){
PerfType* ph = *itr;
if(phListTrack.find(ph->getID())==phListTrack.end()){
phListTrack.insert(ph->getID());
pList->push_back(ph);
}
}
phList.clear();
clsRange.clear();
}
//ClsType::SetClusterID(minClsId-1);
delete []cluster;
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::assignClusterIdsForOverlapingRegion(std::vector<float> overlap){
std::vector<float> _min(hyppox::Config::FILTER, 0.0), _max(hyppox::Config::FILTER, 0.0);
std::list<PerfType*> clPhList;
std::list<DPType*> dpList;
size_t boxID = 1, prevClsId, thisClsId;
std::unordered_set<size_t> boxIdSet;
std::unordered_set<size_t> mainClsIDSet;
std::unordered_set<std::string> phListTrack;
if(this->mesh.size()>0){
for(int j=0; j<hyppox::Config::WINDOWS[1];j++){
for(int i=0; i<hyppox::Config::WINDOWS[0]; i++){
for(short f=0; f<hyppox::Config::FILTER; f++){
float c = this->mesh[i][j].center[f];
float l = (this->gridLength[f]*(1+overlap[f]))/2;
_min[f] = c - l;
_max[f] = c + l;
if(_min[f] < this->minPos[f]) _min[f] = this->minPos[f];
if(_max[f] > this->maxPos[f]) _max[f] = this->maxPos[f];
}
clPhList.clear();
dpList.clear();
phListTrack.clear();
if(isEligibleForClustering(_min, _max, boxID)){
this->treeRoot.SearchSurface(_min, _max, &clPhList, &dpList, boxID);
}
//std::cout<<"~~("<<i<<","<<j<<")={("<<_min[0]<<","<<_min[1]<<"),("<<_max[0]<<","<<_max[1]<<")}: ";
if(clPhList.size() > 0){
prevClsId = ClsType::GetClusterID();
//std::cout<<"Data points:"<<dpList.size()<<", clusterPts:"<<clPhList.size();
this->createCluster(&clPhList, false);
thisClsId = ClsType::GetClusterID();
if(thisClsId-prevClsId > 1){
auto itrBRM = this->gridMap.find(boxID);
itrBRM->second->GetClusterID(&mainClsIDSet);
this->manageCluster(&clPhList, prevClsId+1, thisClsId, &mainClsIDSet);
//this->createCluster(&clPhList, false);
}
}
/*cout<<"\nx1="<<_min[0]<<", x2="<<_max[0]<<"=>";
for(list<PerfType*>::iterator itr=clPhList.begin(); itr!=clPhList.end(); itr++){
PerfType* ph = *itr;
cout<<"\n"<<ph->getIndividualId()<<":"<<ph->GetClusterIdList();
}
cout<<"\n";*/
boxID++;
mainClsIDSet.clear();
}
}
}
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::testRange(std::vector<float> &_min, std::vector<float> &_max, std::list<PerfType *> &clPhList){
std::cout<<"\nTesting:"<<std::endl;
for(auto itr=clPhList.begin(); itr!=clPhList.end(); itr++){
PerfType* ph = *itr;
for(size_t i=0; i<_min.size(); i++){
if(_max[i]>_min[i]){
auto f = ph->getFilter(i);
if(f<_min[i] || f>_max[i]){
std::cout<<ph->getID()<<":"<<f<<",";
}
}
}
}
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::assignClusterIdsForOverlapingRegion(std::list<PerfType*>* overlappedPhList, std::vector<float> overlap){
std::cout<<"Still clustering, your patience is appreciating...\n";
std::vector<float> _min(hyppox::Config::FILTER, 0.0), _max(hyppox::Config::FILTER, 0.0);
std::list<PerfType*> clPhList;
std::list<DPType*> dpList;
size_t boxID = 1, prevClsId, thisClsId;
std::unordered_set<size_t> boxIdSet;
std::unordered_set<size_t> mainClsIDSet;
std::unordered_set<std::string> phListTrack;
std::unordered_set<size_t> indvSet;
std::unordered_set<std::string> edgeSet;
//cout<<"\n\n";
if(this->mesh.size()>0){
for(int j=0; j<hyppox::Config::WINDOWS[1];j++){
for(int i=0; i<hyppox::Config::WINDOWS[0]; i++){
for(short f=0; f<hyppox::Config::FILTER; f++){
float c = this->mesh[i][j].center[f];
float l = (this->gridLength[f]*(1+overlap[f]))/2;
_min[f] = c - l;
_max[f] = c + l;
if(_min[f] < this->minPos[f]) _min[f] = this->minPos[f];
if(_max[f] > this->maxPos[f]) _max[f] = this->maxPos[f];
}
clPhList.clear();
dpList.clear();
phListTrack.clear();
if(isEligibleForClustering(_min, _max, boxID)){
this->treeRoot.SearchSurface(_min, _max, &clPhList, &dpList, boxID);
}
//std::cout<<"("<<i<<","<<j<<")={("<<_min[0]<<","<<_min[1]<<"),("<<_max[0]<<","<<_max[1]<<")}: ";
if(clPhList.size() > 0){
/*if(i==6){
testRange(_min, _max, clPhList);
}*/
prevClsId = ClsType::GetClusterID();
//std::cout<<"Data points:"<<dpList.size()<<", clusterPts:"<<clPhList.size();
time_t _t1 = clock();
this->createCluster(&clPhList, false);
time_t _t2 = clock();
float _time = (float)(_t2-_t1)/CLOCKS_PER_SEC;
std::string unit = "(sec)";
if(_time<1){
_time = ((float)(_t2-_t1)*1000)/CLOCKS_PER_SEC;
unit = "(ms)";
}
//std::cout<<" Total time for clustering:"<<_time<<unit;
thisClsId = ClsType::GetClusterID();
//std::cout<<" ID:"<<thisClsId<<std::endl;
if(thisClsId-prevClsId > 1){
auto itrBRM = this->gridMap.find(boxID);
itrBRM->second->GetClusterID(&mainClsIDSet);
this->manageCluster(&clPhList, prevClsId+1, thisClsId, &mainClsIDSet);
//this->createCluster(&clPhList, false);
}
}
/*cout<<"\nx1="<<_min[0]<<", x2="<<_max[0]<<"=>";
for(list<PerfType*>::iterator itr=clPhList.begin(); itr!=clPhList.end(); itr++){
PerfType* ph = *itr;
cout<<"\n"<<ph->getIndividualId()<<":"<<ph->GetClusterIdList();
}
cout<<"\n";*/
boxID++;
mainClsIDSet.clear();
setOverlappedIndv(&indvSet, &clPhList, overlappedPhList, &edgeSet);
}
}
}
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::setOverlappedIndv(std::unordered_set<size_t> *indvSet, std::list<PerfType *> *clPhList, std::list<PerfType *> *overlappedPhList, std::unordered_set<std::string>* edgeSet){
for(auto itr=clPhList->begin(); itr!=clPhList->end(); itr++){
PerfType* ph = *itr;
//if(indvSet->find(ph->getID())==indvSet->end()){
//cout<<"\n"<<key<<":"<<ph->GetClusterIdList();
indvSet->insert(ph->getID());
overlappedPhList->push_back(ph);
std::vector<ClusterIDType> idList(hyppox::Config::TOTAL_CLUSTER_IDS, 0);
std::vector<std::string> typeList(hyppox::Config::TOTAL_CLUSTER_IDS, "");
ph->GetIDList(idList);
ph->GetTypeList(typeList);
std::vector<ClusterIDType> idVector;
std::vector<std::string> typeVector;
for(int i=0;i<hyppox::Config::TOTAL_CLUSTER_IDS;i++){
if(idList[i]>0){
idVector.push_back(idList[i]);
typeVector.push_back(typeList[i]);
}
}
for(ClusterIDType i=0;i<idVector.size(); i++){
for(ClusterIDType j=i+1; j<idVector.size(); j++){
// If this point is not a noise for both clusters
//if(typeVector[i].compare("P")!=0 || typeVector[j].compare("P")!=0){
std::string k = (idVector[i]<idVector[j])?(std::to_string(idVector[i]) + "#" + std::to_string(idVector[j])):(std::to_string(idVector[j]) + "#" + std::to_string(idVector[i]));
if(edgeSet->find(k)==edgeSet->end()){
edgeSet->insert(k);
EType* e = new EType(idVector[i],idVector[j]);
this->edgeList.push_back(e);
}
//}
}
}
//}
}
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::generateEdgeListFromOverlappingClusters(std::list<PerfType*>* overlappedPhList, std::vector<float> overlap){
std::vector<float> _min(hyppox::Config::FILTER,0.0), _max(hyppox::Config::FILTER,0.0);
std::list<PerfType*> clPhList;
std::list<DPType*> dpList;
std::unordered_set<size_t> indvSet;
std::unordered_set<std::string> edgeSet;
ClusterIDType boxID = 1;
std::vector<ClusterIDType> clsRange(hyppox::Config::TOTAL_CLUSTER_IDS+4, 0);
for(int j=0; j<hyppox::Config::WINDOWS[1];j++){
for(int i=0; i<hyppox::Config::WINDOWS[0]; i++){
clPhList.clear();
dpList.clear();
if(i>0){
for(short f=0; f<hyppox::Config::FILTER; f++){
float c2 = this->mesh[i][j].center[f];
float c1 = this->mesh[i-1][j].center[f];
float l = (this->gridLength[f]*(1+overlap[f]))/2;
_min[f] = c2 - l;
_max[f] = c1 + l;
if(_min[f] < this->minPos[f]) _min[f] = this->minPos[f];
if(_max[f] > this->maxPos[f]) _max[f] = this->maxPos[f];
}
this->treeRoot.SearchSurface(_min, _max, &clPhList, &dpList, boxID);
}
if(j>0){
for(short f=0; f<hyppox::Config::FILTER; f++){
float c2 = this->mesh[i][j].center[f];
float c1 = this->mesh[i][j-1].center[f];
float l = (this->gridLength[f]*(1+overlap[f]))/2;
_min[f] = c2 - l;
_max[f] = c1 + l;
if(_min[f] < this->minPos[f]) _min[f] = this->minPos[f];
if(_max[f] > this->maxPos[f]) _max[f] = this->maxPos[f];
}
this->treeRoot.SearchSurface(_min, _max, &clPhList, &dpList, boxID);
}
boxID++;
setOverlappedIndv(&indvSet, &clPhList, overlappedPhList, &edgeSet);
}
}
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::addSimplicialComplex(SCType *sc, float overlap){
std::vector<float> _min(hyppox::Config::FILTER, 0.0), _max(hyppox::Config::FILTER, 0.0);
// Make it 50%
overlap *=50;
if(this->mesh.size()>0){
sc->clearTracker();
std::list<PerfType*> clPhList;
std::list<DPType*> dpList;
ClusterIDType boxID = 1;
for(int j=0; j<hyppox::Config::WINDOWS[1];j++){
for(int i=0; i<hyppox::Config::WINDOWS[0]; i++){
clPhList.clear();
dpList.clear();
for(short f=0; f<hyppox::Config::FILTER; f++){
float c = this->mesh[i][j].center[f];
float l = this->gridLength[f]/2;
_min[f] = c - l;
_max[f] = c + l;
if(_min[f] < this->minPos[f]) _min[f] = this->minPos[f];
if(_max[f] > this->maxPos[f]) _max[f] = this->maxPos[f];
}
this->treeRoot.SearchSurface(_min, _max, &clPhList, &dpList, boxID);
for(auto pItr = clPhList.begin(); pItr!=clPhList.end(); pItr++){
PerfType* ph = *pItr;
sc->AddSimplicialComplex(ph, overlap);
}
boxID++;
}
}
}
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
std::string Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::generateSimplicesForPersistentHomology(){
SCType sc;
std::vector<float> oV(hyppox::Config::FILTER);
// At first create edge
float Ovx=0.05;
for(; Ovx<=1.0; Ovx+=0.05){
for(short i=0; i<hyppox::Config::FILTER; i++){
oV[i] = Ovx;
}
this->clearClusterInformation();
this->assignClusterIdsForOverlapingRegion(oV);
float overlap = Ovx;
this->addSimplicialComplex(&sc, overlap);
}
// Now check and pick nodes which are part of an edge
Ovx=0.0;
for(short i=0; i<hyppox::Config::FILTER; i++){
oV[i] = Ovx;
}
std::string r = "";
if(hyppox::Config::PH_JAVA_PLEX){
FHType* writeToFile = new FHType("");
r = writeToFile->WriteDataToFile(hyppox::Config::WRITE_DIR+"Barcode", ".java", sc.PrintSimplex(), false);
delete writeToFile;
std::cout<<"\nDump the javaplex.jar file to: "<<hyppox::Config::WRITE_DIR<<" and run from terminal: //javac -cp .:javaplex-4.3.4.jar Barcode.java -d . && java -cp .:javaplex-4.3.4.jar barcode.Barcode";
}/*else{
std::vector<float> v = sc.getPersistentOverlap();
r = "\n Persistent overlap: ";
for(size_t i=0; i<v.size(); i++){
r += "\nDimension-" + std::to_string(i) + ", Overlap: " + std::to_string(v[i]) + "%";
}
//std::cout<<"\n Persistent overlap: "<<r<<"\n\n";
}*/
return r;
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::computeConnectedComponents(size_t &ccSize){
graph::UnionFindWithPathCompression<long> ufpc(ClsType::GetClusterID());
for(auto itr = this->edgeList.begin(); itr!=this->edgeList.end(); itr++){
EType* e = *itr;
long node_1 = e->getNode1();
long node_2 = e->getNode2();
//cout<<"\n"<<node_1<<","<<node_2;
ufpc.Union(node_1, node_2);
}
this->connectedComponents = ufpc.getConnectedComponents(ccSize);
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::constructGraphComponents(GType*& graph){
std::cout<<"Started constructing graph...\n";
size_t size;
this->computeConnectedComponents(size);
std::cout<<"Total subgraphs:"<<size<<std::endl;
std::cout<<"Total Nodes:"<<this->connectedComponents.size()<<std::endl;
std::cout<<"Total Edges:"<<this->edgeList.size()<<std::endl;
std::vector<float> _min(hyppox::Config::FILTER, 0.0), _max(hyppox::Config::FILTER,0.0);
if(graph==nullptr) graph = new GType();
graph->setConnectedComponents(size);
if(this->mesh.size()>0){
std::list<PerfType*> clPhList;
std::list<DPType*> dpList;
ClusterIDType boxID = 1;
for(int j=0; j<hyppox::Config::WINDOWS[1];j++){
for(int i=0; i<hyppox::Config::WINDOWS[0]; i++){
clPhList.clear();
dpList.clear();
for(short f=0; f<hyppox::Config::FILTER; f++){
float c = this->mesh[i][j].center[f];
float l = this->gridLength[f]/2;
_min[f] = c - l;
_max[f] = c + l;
if(_min[f] < this->minPos[f]) _min[f] = this->minPos[f];
if(_max[f] > this->maxPos[f]) _max[f] = this->maxPos[f];
}
this->treeRoot.SearchSurface(_min, _max, &clPhList, &dpList, boxID);
for(auto pItr = clPhList.begin(); pItr!=clPhList.end(); pItr++){
PerfType* ph = *pItr;
std::vector<ClusterIDType> idList(hyppox::Config::TOTAL_CLUSTER_IDS, 0);
ph->GetIDList(idList);
/*if(ph->getID()==1805944 || ph->getID()==2149840 || ph->getID()==2100947){
cout<<"";
}*/
idList.erase(remove(idList.begin(), idList.end(), 0), idList.end());
for(ClusterIDType _id:idList){
auto ccItr=this->connectedComponents.find(_id);
if(ccItr!=this->connectedComponents.end()){
short index = (short)ccItr->second;
auto subGraph = graph->getConnectedComponent(index);
subGraph->addPointToNode(_id, ph);
}
}
}
boxID++;
}
}
}
short index_1, index_2;
for(auto itr = this->edgeList.begin(); itr!=this->edgeList.end(); itr++){
EType* e = *itr;
size_t node_1 = e->getNode1();
size_t node_2 = e->getNode2();
if(this->connectedComponents.find(node_1)!=this->connectedComponents.end() && this->connectedComponents.find(node_2)!=this->connectedComponents.end()){
auto ccItr = this->connectedComponents.find(node_1);
index_1 = (short)ccItr->second;
ccItr = this->connectedComponents.find(node_2);
index_2 = (short)ccItr->second;
if(index_1==index_2){
auto subGraph = graph->getConnectedComponent(index_1);
subGraph->addEdge(node_1, node_2);
}
}
}
std::vector<float> sizeRange(2,0.0), _v(2, 0.0);
std::vector<std::vector<float> > weightRange(hyppox::Config::FILTER+hyppox::Config::CLUSTER, _v);
for(short i=0;i<hyppox::Config::FILTER+hyppox::Config::CLUSTER;i++){
weightRange[i][0] = 0.0;
weightRange[i][1] = 0.0;
}
for(size_t i=0; i<size; i++){
std::vector<float> _sizeRange(2,0.0);
std::vector<std::vector<float> > _weightRange(hyppox::Config::FILTER+hyppox::Config::CLUSTER, _v);
auto subGraph = graph->getConnectedComponent(i);
subGraph->setupLinks();
subGraph->getNodeSizeAndWeightRange(_sizeRange, _weightRange);
if(i==0){
sizeRange[0] = _sizeRange[0];
sizeRange[1] = _sizeRange[1];
for(short j=0;j<hyppox::Config::FILTER+hyppox::Config::CLUSTER;j++){
weightRange[j][0] = _weightRange[j][0];
weightRange[j][1] = _weightRange[j][1];
}
}else{
if(_sizeRange[0]<sizeRange[0]) sizeRange[0] = _sizeRange[0];
if(_sizeRange[1]>sizeRange[1]) sizeRange[1] = _sizeRange[1];
for(short j=0;j<hyppox::Config::FILTER+hyppox::Config::CLUSTER;j++){
if(_weightRange[j][0]<weightRange[j][0]) weightRange[j][0] = _weightRange[j][0];
if(_weightRange[j][1]>weightRange[j][1]) weightRange[j][1] = _weightRange[j][1];
}
}
}
graph->setGlobalNodeSizeAndWeightRange(sizeRange, weightRange);
for(size_t i=0; i<size; i++){
auto subGraph = graph->getConnectedComponent(i);
for(int j=0;j<2;j++) subGraph->setGlobalSizeRange(sizeRange[j], j);
for(short j=0;j<hyppox::Config::FILTER+hyppox::Config::CLUSTER;j++) subGraph->setGlobalWeightRange(weightRange[j], j);
}
}
template<typename PerfType, typename DPType, typename QTType, typename GType, typename FHType, typename ClusterIDType, typename RowIDType, typename ClusterType>
void Mapper<PerfType,DPType,QTType,GType,FHType,ClusterIDType,RowIDType,ClusterType>::constructGraph(GType*& graph){
std::list<PerfType*> overlappedIndiv;
overlappedIndiv.clear();
edgeList.clear();
time_t t1 = clock();
this->clearClusterInformation();
this->assignClusterIdsForOverlapingRegion(&overlappedIndiv, hyppox::Config::GAIN);
time_t t2 = clock();
std::vector<std::string> _time = getTime((float)(t2-t1)/CLOCKS_PER_SEC);
std::cout<<"Clusteing completed...\nTotal time for clustering:"<<_time[0]<<_time[1]<<std::endl;
//cout<<"Total time:"<<_time<<unit<<endl;
//overlappedIndiv.clear();
//edgeList.clear();
//this->generateEdgeListFromOverlappingClusters(&overlappedIndiv, hyppox::Config::GAIN);
t1 = clock();
this->constructGraphComponents(graph);
t2 = clock();
_time = getTime((float)(t2-t1)/CLOCKS_PER_SEC);
std::cout<<"Graph construction completed...\nTotal time to construct graph:"<<_time[0]<<_time[1]<<std::endl;
}
}
}
#endif /* mapper_hp */
| 44.431099 | 265 | 0.503405 | [
"mesh",
"vector"
] |
18e7dca0a725f09833c2f0c3adaa5cd814814538 | 916 | h | C | include/engine/subsystems/physics/physics_world.h | ukrainskiysergey/BallMaze | 84d211ec0733fff7d2b13d5ffce707fb1813fe4e | [
"MIT"
] | null | null | null | include/engine/subsystems/physics/physics_world.h | ukrainskiysergey/BallMaze | 84d211ec0733fff7d2b13d5ffce707fb1813fe4e | [
"MIT"
] | null | null | null | include/engine/subsystems/physics/physics_world.h | ukrainskiysergey/BallMaze | 84d211ec0733fff7d2b13d5ffce707fb1813fe4e | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <memory>
#include "engine/math/vector.h"
#include "engine/math/quaternion.h"
class PhysicsBody;
class CollisionShape;
class Constraint;
struct Contact;
struct HitInfo;
class PhysicsWorld
{
public:
virtual ~PhysicsWorld() {};
virtual void update(float dt) = 0;
virtual std::shared_ptr<PhysicsBody> createPhysicsBody(const std::shared_ptr<CollisionShape>& shape, const vec3& position, const Quaternion& rotation, float mass) = 0;
virtual std::vector<Contact> getContacts(PhysicsBody* bodyA, PhysicsBody* bodyB) = 0;
virtual HitInfo rayCast(const vec3& start, const vec3& end) const = 0;
virtual std::vector<HitInfo> rayCastAll(const vec3& start, const vec3& end) const = 0;
virtual std::shared_ptr<Constraint> createPointConstraint(const std::shared_ptr<PhysicsBody>& bodyA, const std::shared_ptr<PhysicsBody>& bodyB, const vec3& pivotA, const vec3& pivotB) = 0;
}; | 33.925926 | 189 | 0.765284 | [
"shape",
"vector"
] |
49e2cb58ad13e620894a2b445e771fef42196b2b | 2,106 | h | C | src/airmap/monitor/submitting_vehicle_monitor.h | YUNEEC/platform-sdk | 5670c5096087e836ecdbde38ae401cbfa7fa5fc7 | [
"Apache-2.0"
] | 13 | 2018-09-05T14:35:01.000Z | 2021-03-04T07:17:40.000Z | src/airmap/monitor/submitting_vehicle_monitor.h | YUNEEC/platform-sdk | 5670c5096087e836ecdbde38ae401cbfa7fa5fc7 | [
"Apache-2.0"
] | 31 | 2018-09-06T13:04:03.000Z | 2021-11-15T22:46:50.000Z | src/airmap/monitor/submitting_vehicle_monitor.h | YUNEEC/platform-sdk | 5670c5096087e836ecdbde38ae401cbfa7fa5fc7 | [
"Apache-2.0"
] | 12 | 2018-11-09T10:09:21.000Z | 2021-10-08T05:28:12.000Z | // AirMap Platform SDK
// Copyright © 2018 AirMap, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an AS IS BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef AIRMAP_MONITOR_SUBMITTING_VEHICLE_MONITOR_H_
#define AIRMAP_MONITOR_SUBMITTING_VEHICLE_MONITOR_H_
#include <airmap/mavlink/vehicle.h>
#include <airmap/monitor/telemetry_submitter.h>
#include <memory>
namespace airmap {
namespace monitor {
/// SubmittingVehicleMonitor monitors a mavlink::Vehicle.
///
/// SubmittingVehicleMonitor translates state changes and carries out
/// the following actions:
/// - vehicle becomes active
/// - create flight
/// - start flight comms
/// - new position estimate
/// - if vehicle active:
/// - submit telemetry
/// - vehicle becomes inactive
/// - end flight comms
/// - end flight
class SubmittingVehicleMonitor : public mavlink::Vehicle::Monitor {
public:
/// SubmittingVehicleMonitor initializes a new instance with 'submitter'.
explicit SubmittingVehicleMonitor(const std::shared_ptr<TelemetrySubmitter>& submitter);
// From Vehicle::Monitor
void on_system_status_changed(const Optional<mavlink::State>& old_state, mavlink::State new_state) override;
void on_position_changed(const Optional<mavlink::GlobalPositionInt>& old_position,
const mavlink::GlobalPositionInt& new_position) override;
void on_mission_received(const airmap::Geometry& geometry) override;
private:
/// @cond
std::shared_ptr<TelemetrySubmitter> submitter_;
/// @endcond
};
} // namespace monitor
} // namespace airmap
#endif // AIRMAP_MONITOR_SUBMITTING_VEHICLE_MONITOR_H_
| 36.310345 | 110 | 0.748813 | [
"geometry"
] |
49f745f8295c71ad5a52a0aed83511dc9034d810 | 6,871 | h | C | src/lib/dhcpsrv/hook_library_manager.h | telekom/dt-kea-netconf | f347df353d58827d6deb09f281d3680ab089e7af | [
"Apache-2.0"
] | 2 | 2021-06-29T09:56:34.000Z | 2021-06-29T09:56:39.000Z | src/lib/dhcpsrv/hook_library_manager.h | telekom/dt-kea-netconf | f347df353d58827d6deb09f281d3680ab089e7af | [
"Apache-2.0"
] | null | null | null | src/lib/dhcpsrv/hook_library_manager.h | telekom/dt-kea-netconf | f347df353d58827d6deb09f281d3680ab089e7af | [
"Apache-2.0"
] | null | null | null | // (C) 2020 Deutsche Telekom AG.
//
// Deutsche Telekom AG and all other contributors /
// copyright owners license 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.
#ifndef DHCPSRV_HOOK_LIBRARY_MANAGER_H
#define DHCPSRV_HOOK_LIBRARY_MANAGER_H
#include <dhcpsrv/configuration.h>
#include <dhcpsrv/shard_config_mgr.h>
namespace isc {
namespace dhcp {
template <DhcpSpaceType D, bool has_IETF>
struct HookLibraryConstants {
static std::regex const& regex() {
static std::regex const _(
"/masters\\[name='(.*?)'\\]/shards\\[name='(.*?)'\\]/shard-config/" +
ConfigurationElements<D, has_IETF>::toplevel() +
"/hooks-libraries\\[library='(.*?)'\\]/"
"(lawful-interception-parameters|policy-engine-parameters|"
"parameters)()");
return _;
}
static std::regex const& subnetRegex() {
static std::regex const _(
"/masters\\[name='(.*?)'\\]/shards\\[name='(.*?)'\\]/shard-config/" +
ConfigurationElements<D, has_IETF>::toplevel() +
"/hooks-libraries\\[library='(.*?)'\\]/"
"(lawful-interception-parameters|policy-engine-parameters|"
"parameters)/config/network-topology/subnets\\[subnet='(.*?)'\\]");
return _;
}
static std::string const xpath(std::string const& master,
std::string const& shard,
std::string const& hook_library,
std::string const& parameters_key,
std::string const& subnet = std::string()) {
std::string result(ShardConstants::xpath(master, shard) + "/" +
ConfigurationElements<D, has_IETF>::toplevel() +
"/hooks-libraries[library='" + hook_library + "']/" + parameters_key +
"/config");
if (!subnet.empty()) {
result += "/network-topology/subnets[subnet='" + subnet + "']";
}
return result;
}
static std::string const
xpath(std::string const& master, std::string const& shard, std::string const& hook_library) {
for (std::string const& p : {"lawful-interception", "policy-engine"}) {
if (hook_library.find(p) != std::string::npos) {
return xpath(master, shard, hook_library, p + "-parameters");
}
}
return xpath(master, shard, hook_library, "parameters");
}
static std::vector<std::string> const
xpaths(std::string const& master, std::string const& shard, std::string const& hook_library) {
std::vector<std::string> result;
for (std::string const& p : {"lawful-interception-parameters", "policy-engine-parameters",
"parameters"}) {
result.push_back(xpath(master, shard, hook_library, p));
}
return result;
}
static auto fromMatch(std::smatch const& match) {
return std::make_tuple(std::string(match[1]), std::string(match[2]), std::string(match[3]),
std::string(match[4]), std::string(match[5]), std::string(match[6]));
}
private:
/// @brief static methods only
HookLibraryConstants() = delete;
/// @brief non-copyable
/// @{
HookLibraryConstants(HookLibraryConstants const&) = delete;
HookLibraryConstants& operator=(HookLibraryConstants const&) = delete;
/// @}
};
template <DhcpSpaceType D, bool has_IETF>
struct HookLibraryManager {
static void removeParameters(isc::data::ElementPtr const& config) {
// Sanity checks
isc::data::ElementPtr const& dhcp(ConfigurationManager<D, has_IETF>::getDhcp(config));
isc::data::ElementPtr const& hooks(dhcp->get("hooks-libraries"));
if (!hooks) {
return;
}
// Set parameters for all hooks.
for (isc::data::ElementPtr const& hook : hooks->listValue()) {
// Determine which YANG-backed parameters key should be changed.
isc::data::ElementPtr parameters;
for (std::string const& p :
{"lawful-interception-parameters", "policy-engine-parameters",
"parameters"}) {
parameters = hook->get(p);
if (parameters && !parameters->empty()) {
break;
}
}
if (!parameters) {
continue;
}
// Effective parameter removal
if (parameters->contains("arguments")) {
parameters->remove("arguments");
}
if (parameters->contains("command")) {
parameters->remove("command");
}
}
}
static void setParameters(isc::data::ElementPtr const& config,
isc::data::ElementPtr const& command,
isc::data::ElementPtr const& arguments) {
// Sanity checks
isc::data::ElementPtr const& dhcp(ConfigurationManager<D, has_IETF>::getDhcp(config));
isc::data::ElementPtr const& hooks(dhcp->get("hooks-libraries"));
if (!hooks) {
return;
}
// Set parameters for all hooks.
for (isc::data::ElementPtr const& hook : hooks->listValue()) {
// Determine which YANG-backed parameters key should be changed.
isc::data::ElementPtr parameters;
for (std::string const& p :
{"lawful-interception-parameters", "policy-engine-parameters",
"parameters"}) {
parameters = hook->get(p);
if (parameters && !parameters->empty()) {
break;
}
}
if (!parameters) {
continue;
}
// Effective parameter setting
parameters->set("arguments", arguments);
parameters->set("command", command);
}
}
private:
/// @brief static methods only
HookLibraryManager() = delete;
/// @brief non-copyable
/// @{
HookLibraryManager(HookLibraryManager const&) = delete;
HookLibraryManager& operator=(HookLibraryManager const&) = delete;
/// @}
};
} // namespace dhcp
} // namespace isc
#endif // DHCPSRV_HOOK_LIBRARY_MANAGER_H
| 37.342391 | 100 | 0.56673 | [
"vector"
] |
49fa6cec389ede6264903c1b85220a8f3bfcf5ec | 19,666 | h | C | eram.h | fengjixuchui/ERAM | f8d490f477903784565243b6a5be8419b2c08403 | [
"MIT"
] | 332 | 2016-07-01T06:34:55.000Z | 2022-03-24T09:42:15.000Z | eram.h | fengjixuchui/ERAM | f8d490f477903784565243b6a5be8419b2c08403 | [
"MIT"
] | 25 | 2016-07-02T03:04:21.000Z | 2021-09-02T11:05:15.000Z | eram.h | fengjixuchui/ERAM | f8d490f477903784565243b6a5be8419b2c08403 | [
"MIT"
] | 61 | 2016-06-28T22:46:32.000Z | 2022-03-17T13:09:41.000Z | /* ERAM.H RAM disk ERAM for WindowsNT/2000/2003/XP/7
Copyright (c) 1999-2020 by *Error15 & Zero3K
Translated into English by Katayama Hirofumi MZ.
*/
#pragma pack(1)
int sprintf(char *s, const char *format, ...);
typedef SIZE_T ULONGPTR, *PULONGPTR;
typedef unsigned int UINT;
typedef UCHAR BYTE, *PBYTE, *LPBYTE;
typedef USHORT WORD, *PWORD, *LPWORD;
typedef ULONG DWORD, *PDWORD, *LPDWORD;
typedef int INT, *PINT, *LPINT;
#define NumberOf(x) ((sizeof(x))/(sizeof((x)[0])))
#define LOBYTE(w) ((BYTE)(w))
#define HIBYTE(w) ((BYTE)(((WORD)(w) >> 8) & 0xFF))
#ifndef max
#define max(a,b) (((a) > (b)) ? (a) : (b))
#endif
#ifndef PARTITION_FAT32
#define PARTITION_FAT32 0x0B
#endif
#define MAXDWORD (MAXULONG)
#ifndef IOCTL_DISK_GET_LENGTH_INFO
#define IOCTL_DISK_GET_LENGTH_INFO CTL_CODE(IOCTL_DISK_BASE, 0x0017, METHOD_BUFFERED, FILE_READ_ACCESS)
typedef struct {
LARGE_INTEGER Length;
} GET_LENGTH_INFORMATION, *PGET_LENGTH_INFORMATION;
#endif
typedef NTSTATUS (*ERAM_READ)(PVOID, PIRP, PIO_STACK_LOCATION, PUCHAR);
typedef NTSTATUS (*ERAM_WRITE)(PVOID, PIRP, PIO_STACK_LOCATION, PUCHAR);
typedef BOOLEAN (*ERAM_NEXT)(PVOID, LPDWORD, LPDWORD);
typedef VOID (*ERAM_UNMAP)(PVOID);
#define FATID_MSG "RAMdisk driver ERAM version 2.23 Copyright(C)1999-2004 by *Error15"
#define SUBKEY_WSTRING L"\\Parameters"
#define NT_DEVNAME L"\\Device\\Eram"
#define WIN32_PATH L"\\DosDevices\\"
#define DEFAULT_DRV L"Z:"
#define DISKMAXCLUSTER_12 (4086) /* FAT12 Max Cluster */
#define DISKMAXCLUSTER_16 (65525) /* FAT16 Max Cluster */
#define DISKMAXCLUSTER_32 (268435455) /* FAT32 Max Cluster */
#define RAMDISK_MEDIA_TYPE 0xf8
#define VOLUME_LABEL_RAMDISK "MS-RAMDRIVE"
#define VOLUME_LABEL_LOCALDISK "ERAM-DRIVE "
#define TEMPDIR_NAME "TEMP "
#define OWNDIR_NAME ". "
#define PARENTDIR_NAME ".. "
#define ERAMEXTFILEPATH L"C:\\ERAMSWAP.$$$"
#define DISKMINPAGE (16)
/* Unable to allocate data area; 2 is minimum at allocation 2 */
#define SECTOR (512)
#define SECTOR_LOG2 (9)
#define RESV_SECTOR_FAT32 (2)
#define SIZE_KILOBYTE (1024) /* 1KB */
#define SIZE_MEGABYTE (SIZE_KILOBYTE * 1024) /* 1MB */
#define PAGE_SIZE_4K (SIZE_KILOBYTE * 4) /* The size of one page */
#define PAGE_SIZE_LOG2 (12)
#define PAGE_SECTOR (PAGE_SIZE_4K / SECTOR) /* Sectors per page */
#define PAGE_SEC_LOG2 (PAGE_SIZE_LOG2 - SECTOR_LOG2)
#define EXT_PAGE_SIZE (SIZE_KILOBYTE * 64) /* 64KB unit switch */
#define EXT_PAGE_SIZE_LOG2 (16)
#define EXT_PAGE_SECTOR (EXT_PAGE_SIZE / SECTOR) /* sectors per bank */
#define EXT_PAGE_SEC_LOG2 (EXT_PAGE_SIZE_LOG2 - SECTOR_LOG2)
#define LIMIT_2GBPAGES (0x7ffff) /* 2GB pages */
#define LIMIT_4GBPAGES (0xfffff) /* 4GB pages */
#define BIOS_ADDRESS_START ((DWORD)(0xe0000)) /* E0000..FFFFF */
#define BIOS_ADDRESS_END ((DWORD)(0xfffff)) /* E0000..FFFFF */
#define BIOS_SIZE ((DWORD)(BIOS_ADDRESS_END - BIOS_ADDRESS_START + 1))
/* BPB array (FAT12,16) */
typedef struct {
WORD wNumSectorByte; // The number of sector bytes (BPB, =SECTOR)
BYTE byAllocUnit; // Allocation unit (alloc)
WORD wNumResvSector; // The number of reserved sectors, FAT12/16=1, FAT32=32
BYTE byNumFat; // The number of FATs (=1)
WORD wNumDirectory; // The number of root directory entries (dir, =128)
WORD wNumAllSector; // The number of all sectors (under 32MB)
BYTE byMediaId; // Media ID(media, =f8)
WORD wNumFatSector; // The number of FAT sectors (FAT)
} bpb_struc1;
typedef struct {
WORD bsSecPerTrack; // Sectors per bank (=PAGE_SECTOR)
WORD bsHeads; // The number of heads (=1)
ULONG bsHiddenSecs; // The number of hidden sectors (=0)
ULONG bsHugeSectors; // The sectors over 32MB
} bpb_struc2;
typedef struct {
BYTE bsDriveNumber; // Drive number
BYTE bsReserved1; // Reserved
BYTE bsBootSignature; // Signature
ULONG bsVolumeID; // Volume ID
CHAR bsLabel[11]; // Label
CHAR bsFileSystemType[8];// File system type
} bpb_struc3;
/* BPB array (FAT32) */
typedef struct {
DWORD dwNumFatSector32; // The number of FAT sectors (FAT32)
WORD wExtFlags; // Extended flags
WORD wFileSystemVersion; // Filesystem version
DWORD dwRootCluster; // Root cluster number (=2)
WORD wFsInfoSector; // FSINFO sector number (=1)
WORD wBackupBootSector; // Backup boot sector number (=6)
BYTE byResv[12]; // Reserved
} bpb_struc4;
typedef union {
DWORD dwOptflag; // ERAM control
struct {
BYTE NonPaged:1; // bit 0:NonPagedPool usage
BYTE External:1; // bit 1:External memory usage
BYTE SkipExternalCheck:1; // bit 2:Don't test memory when using external memory
BYTE Swapable:1; // bit 3:Local disk flag
BYTE EnableFat32:1; // bit 4:Allow FAT32 usage
BYTE SkipReportUsage:1; // bit 5:Don't report when using external memory = 2000:Allow stand-by
BYTE MakeTempDir:1; // bit 6:TEMP directory creation
BYTE byResv7:1; // bit 7:
BYTE byResv8:8; // bit 8:
BYTE byResv16:8; // bit16:
BYTE byResv24:7; // bit24:
BYTE UseExtFile:1; // bit31:External file usage
} Bits;
} ERAM_OPTFLAG, *PERAM_OPTFLAG;
/* ERAM disk device specific info */
typedef struct {
PDEVICE_OBJECT pDevObj;
ERAM_READ EramRead;
ERAM_WRITE EramWrite;
ERAM_NEXT EramNext;
ERAM_UNMAP EramUnmap;
ULONGPTR uNowMapAdr; // OS-Unmanaged/file, the currently mapping address
LPBYTE pExtPage; // OS-Unmanaged/file, the memory mapping address
LPBYTE pPageBase; // OS-Managed Memory
ULONGPTR uSizeTotal; // Total size (4KB unit)
UNICODE_STRING Win32Name;
ULONG uAllSector; // The number of all sectors
ULONGPTR uExternalStart; // External memory starting position
ULONGPTR uExternalEnd; // External memory ending position (of detected)
FAST_MUTEX FastMutex; // Fast mutex
PHYSICAL_ADDRESS MapAdr; // OS-Unmanaged Memory map position top
ULONG bsHiddenSecs; // The number of hidden sectors (=0)
HANDLE hFile; // External file handle (in system process)
HANDLE hSection; // External file mapping handle (in system process)
LIST_ENTRY IrpList; // Irp list top
KSPIN_LOCK IrpSpin; // Irp list spinlock
KSEMAPHORE IrpSem; // Irp list semaphore
PVOID pThreadObject; // Irp list thred object
ERAM_OPTFLAG uOptflag; // Option
BYTE FAT_size; // PARTITION_... FAT_12,FAT_16,HUGE,FAT32
BYTE bThreadStop; // Thread Stop Request
} ERAM_EXTENSION, *PERAM_EXTENSION;
/* MBR-inside partitoin table (PC/AT) */
typedef struct {
BYTE byBootInd;
BYTE byFirstHead;
BYTE byFirstSector;
BYTE byFirstTrack;
BYTE byFileSystem;
BYTE byLastHead;
BYTE byLastSector;
BYTE byLastTrack;
DWORD dwStartSector;
DWORD dwNumSectors;
} MBR_PARTITION, *PMBR_PARTITION;
/* Info for boot sector */
typedef struct {
bpb_struc1 BPB; /* BPB array */
bpb_struc2 BPB_ext; /* DOS5 extended area */
bpb_struc3 BPB_ext2; /* Extended area */
bpb_struc4 BPB_fat32; /* FAT32 only */
TIME_FIELDS TimeInfo; /* date and time */
CHAR bsLabel[11]; /* label */
WCHAR wszExtFile[4]; /* \\??\\ */
WCHAR wszExtFileMain[260]; /* C:\\ERAMSWAP.$$$ */
} FAT_ID, *PFAT_ID;
typedef struct {
BYTE bsJump[3]; // jmp $(=eb, fe, 90)
BYTE bsOemName[8]; // Device name (='ERAM ')
bpb_struc1 BPB; // BPB array
bpb_struc2 BPB_ext; // DOS5 extended area
bpb_struc3 BPB_ext2; // Extended area
BYTE byResv1[194];
BYTE szMsg[128]; // 0x100
BYTE byResv2[126]; // 0x180
BYTE bsSig2[2]; /* 55,AA */
} BOOTSECTOR_FAT16, *PBOOTSECTOR_FAT16;
typedef struct {
BYTE bsJump[3]; // jmp $(=eb, fe, 90)
BYTE bsOemName[8]; // Device name (='ERAM ')
bpb_struc1 BPB; // BPB array
bpb_struc2 BPB_ext; // DOS5 extended area
bpb_struc4 BPB_fat32; // FAT32 only
bpb_struc3 BPB_ext2; // Extended area
BYTE byResv1[166];
BYTE szMsg[128]; // 0x100
BYTE byResv[62]; // 0x180
MBR_PARTITION Parts[4]; // 0x1BE, 1CE, 1DE, 1EE
BYTE bsSig2[2]; /* 55,AA */
} BOOTSECTOR_FAT32, *PBOOTSECTOR_FAT32;
/* FSINFO (FAT32) */
typedef struct {
DWORD bfFSInf_Sig; /* "rrAa" */
DWORD bfFSInf_free_clus_cnt; /* Free clusters -1:Unknown */
DWORD bfFSInf_next_free_clus; /* Cluster reserved last time */
DWORD bfFSInf_resvd[3];
} BIGFATBOOTFSINFO, *PBIGFATBOOTFSINFO;
typedef struct {
DWORD FSInfo_Sig; /* "RRaA" */
BYTE byResv[480];
BIGFATBOOTFSINFO FsInfo; /* 1E4.. */
BYTE byResv2[2];
BYTE bsSig2[2]; /* 55,AA */
} FSINFO_SECTOR, *PFSINFO_SECTOR;
/* Directory entry */
typedef struct {
CHAR sName[11]; /* Filename */
union {
BYTE byAttr; /* File attributes */
struct {
BYTE byR:1;
BYTE byH:1;
BYTE byS:1;
BYTE byVol:1;
BYTE byDir:1;
BYTE byA:1;
} Bits;
} uAttr;
BYTE byResv1[10];
WORD wUpdMinute; /* Update Time */
WORD wUpdDate; /* Update Date */
WORD wCluster; /* First cluster */
DWORD dwFileSize; /* The file size */
} DIR_ENTRY, *PDIR_ENTRY;
/* Root Directory Entry */
typedef struct {
DIR_ENTRY vol;
DIR_ENTRY temp;
} vol_label;
/* Subdirectory Entry */
typedef struct {
DIR_ENTRY own;
DIR_ENTRY parent;
} dir_init;
/* Prototypes */
//------ Oldie hidden API
extern __declspec(dllimport) ULONG NtBuildNumber;
#define BUILD_NUMBER_NT40 (1381)
#define BUILD_NUMBER_NT50 (2195)
#define BUILD_NUMBER_NT51 (2600)
NTSTATUS
NTAPI
ZwCreateSection(
OUT PHANDLE SectionHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
IN PLARGE_INTEGER MaximumSize OPTIONAL,
IN ULONG SectionPageProtection,
IN ULONG AllocationAttributes,
IN HANDLE FileHandle OPTIONAL
);
#ifndef SEC_COMMIT
#define SEC_COMMIT (0x8000000)
#endif
//------ Functions to be used at all times in normal use
NTSTATUS EramCreateClose(
IN PDEVICE_OBJECT pDevObj,
IN PIRP pIrp
);
NTSTATUS EramDeviceControl(
IN PDEVICE_OBJECT pDevObj,
IN PIRP pIrp
);
VOID EramDeviceControlGeometry(
PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN ULONG uLen
);
VOID EramDeviceControlGetPartInfo(
PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN ULONG uLen
);
VOID EramDeviceControlSetPartInfo(
PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN ULONG uLen
);
VOID EramDeviceControlVerify(
PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN ULONG uLen
);
VOID EramDeviceControlDiskCheckVerify(
PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN ULONG uLen
);
VOID EramDeviceControlGetLengthInfo(
PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN ULONG uLen
);
NTSTATUS EramReadWrite(
IN PDEVICE_OBJECT pDevObj,
IN PIRP pIrp
);
VOID EramUnloadDriver(
IN PDRIVER_OBJECT pDrvObj
);
VOID EramUnloadDevice(
IN PDRIVER_OBJECT pDrvObj,
IN PDEVICE_OBJECT pDevObj,
IN PERAM_EXTENSION pEramExt
);
VOID ResourceRelease(
IN PDRIVER_OBJECT pDrvObj,
IN PERAM_EXTENSION pEramExt
);
VOID ReleaseMemResource(
IN PDRIVER_OBJECT pDrvObj,
IN PERAM_EXTENSION pEramExt
);
BOOLEAN EramReportEvent(
IN PVOID pIoObject,
IN NTSTATUS ntErrorCode,
IN PSTR pszString
);
BOOLEAN EramReportEventW(
IN PVOID pIoObject,
IN NTSTATUS ntErrorCode,
IN PWSTR pwStr
);
NTSTATUS ReadPool(
IN PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN PIO_STACK_LOCATION pIrpSp,
IN PUCHAR lpDest
);
NTSTATUS WritePool(
IN PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN PIO_STACK_LOCATION pIrpSp,
IN PUCHAR lpSrc
);
NTSTATUS ExtRead1(
IN PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN PIO_STACK_LOCATION pIrpSp,
IN PUCHAR lpDest
);
NTSTATUS ExtWrite1(
IN PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN PIO_STACK_LOCATION pIrpSp,
IN PUCHAR lpSrc
);
BOOLEAN ExtNext1(
IN PERAM_EXTENSION pEramExt,
IN OUT LPDWORD lpeax,
IN OUT LPDWORD lpebx
);
BOOLEAN ExtMap(
IN PERAM_EXTENSION pEramExt,
IN ULONGPTR uMapAdr
);
VOID ExtUnmap(
IN PERAM_EXTENSION pEramExt
);
NTSTATUS ExtFilePendingRw(
IN PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN PIO_STACK_LOCATION pIrpSp,
IN PUCHAR pTransAddr
);
VOID EramRwThread(
IN PVOID pContext
);
NTSTATUS EramRwThreadIrp(
PERAM_EXTENSION pEramExt,
PLIST_ENTRY pIrpList
);
NTSTATUS ExtFileRead1(
IN PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN PIO_STACK_LOCATION pIrpSp,
IN PUCHAR lpDest
);
NTSTATUS ExtFileWrite1(
IN PERAM_EXTENSION pEramExt,
IN PIRP pIrp,
IN PIO_STACK_LOCATION pIrpSp,
IN PUCHAR lpSrc
);
BOOLEAN ExtFileNext1(
IN PERAM_EXTENSION pEramExt,
IN OUT LPDWORD lpeax,
IN OUT LPDWORD lpebx
);
BOOLEAN ExtFileMap(
IN PERAM_EXTENSION pEramExt,
IN ULONGPTR uMapAdr
);
VOID ExtFileUnmap(
IN PERAM_EXTENSION pEramExt
);
NTSTATUS EramShutdown(
IN PDEVICE_OBJECT pDevObj,
IN PIRP pIrp
);
/* Definitions for paging */
#ifdef ALLOC_PRAGMA
//------ Functions to be used at all times in normal use
#pragma alloc_text(PAGE, EramCreateClose)
#pragma alloc_text(PAGE, EramDeviceControl)
#pragma alloc_text(PAGE, EramDeviceControlGeometry)
#pragma alloc_text(PAGE, EramDeviceControlGetPartInfo)
#pragma alloc_text(PAGE, EramDeviceControlSetPartInfo)
#pragma alloc_text(PAGE, EramDeviceControlVerify)
#pragma alloc_text(PAGE, EramDeviceControlGetLengthInfo)
#pragma alloc_text(PAGE, EramDeviceControlDiskCheckVerify)
#pragma alloc_text(PAGE, EramDeviceControlGetLengthInfo)
#pragma alloc_text(PAGE, EramReadWrite)
#pragma alloc_text(PAGE, EramUnloadDriver)
#pragma alloc_text(PAGE, EramUnloadDevice)
#pragma alloc_text(PAGE, ResourceRelease)
#pragma alloc_text(PAGE, ReleaseMemResource)
#pragma alloc_text(PAGE, EramReportEvent)
#pragma alloc_text(PAGE, EramReportEventW)
#pragma alloc_text(PAGE, ReadPool)
#pragma alloc_text(PAGE, WritePool)
#pragma alloc_text(PAGE, ExtRead1)
#pragma alloc_text(PAGE, ExtWrite1)
#pragma alloc_text(PAGE, ExtNext1)
#pragma alloc_text(PAGE, ExtMap)
#pragma alloc_text(PAGE, ExtUnmap)
#pragma alloc_text(PAGE, ExtFilePendingRw)
#pragma alloc_text(PAGE, EramRwThread)
#pragma alloc_text(PAGE, EramRwThreadIrp)
#pragma alloc_text(PAGE, ExtFileRead1)
#pragma alloc_text(PAGE, ExtFileWrite1)
#pragma alloc_text(PAGE, ExtFileNext1)
#pragma alloc_text(PAGE, ExtFileMap)
#pragma alloc_text(PAGE, ExtFileUnmap)
#pragma alloc_text(PAGE, EramShutdown)
#endif // ALLOC_PRAGMA
//------ Below are the functions used at initialization
NTSTATUS DriverEntry(
IN OUT PDRIVER_OBJECT pDrvObj,
IN PUNICODE_STRING pRegPath
);
VOID InitFatId(
IN PFAT_ID pFatId
);
NTSTATUS EramInitDisk(
IN PDRIVER_OBJECT pDrvObj,
IN PFAT_ID pFatId,
IN PUNICODE_STRING pRegParam
);
NTSTATUS MemSetup(
IN PDRIVER_OBJECT pDrvObj,
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId,
IN SIZE_T uMemSize
);
BOOLEAN OsAlloc(
IN PDRIVER_OBJECT pDrvObj,
IN PERAM_EXTENSION pEramExt,
IN SIZE_T uMemSize
);
VOID CalcAvailSize(
IN PDRIVER_OBJECT pDrvObj,
IN POOL_TYPE fPool,
IN SIZE_T uMemSize
);
DEVICE_TYPE CheckSwapable(
IN PUNICODE_STRING pRegParam
);
VOID CheckDeviceName(
IN PUNICODE_STRING pRegParam,
IN OUT PUNICODE_STRING pNtDevName
);
VOID CheckSwitch(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId,
IN PUNICODE_STRING pRegParam,
IN OUT PUNICODE_STRING pDrvStr
);
VOID GetMaxAddress(
IN PERAM_EXTENSION pEramExt,
IN PUNICODE_STRING pRegParam
);
VOID PrepareVolumeLabel(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId,
IN PUNICODE_STRING pRegParam
);
BOOLEAN CheckVolumeLabel(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId,
IN PUNICODE_STRING pUniVol
);
VOID PrepareExtFileName(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId,
IN PUNICODE_STRING pRegParam
);
BOOLEAN EramFormatFat(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId
);
VOID EramSetup(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId
);
VOID EramLocate(
IN PERAM_EXTENSION pEramExt
);
BOOLEAN EramFormat(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId
);
BOOLEAN EramClearInfo(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId
);
BOOLEAN ExtClear(
IN PERAM_EXTENSION pEramExt,
IN ULONGPTR uSize
);
BOOLEAN ExtFileClear(
IN PERAM_EXTENSION pEramExt,
IN ULONGPTR uSize
);
ULONGPTR CalcEramInfoPage(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId
);
BOOLEAN EramMakeFAT(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId
);
BOOLEAN EramSetLabel(
IN PERAM_EXTENSION pEramExt,
IN PFAT_ID pFatId
);
BOOLEAN GetExternalStart(
IN PDRIVER_OBJECT pDrvObj,
IN PERAM_EXTENSION pEramExt
);
BOOLEAN GetMaxMem(
IN PDRIVER_OBJECT pDrvObj,
IN PERAM_EXTENSION pEramExt,
IN PWSTR pwStr,
OUT PULONG puSize //TODO: 64bit would be required here?
);
BOOLEAN CheckMaxMem(
IN PDRIVER_OBJECT pDrvObj,
IN PERAM_EXTENSION pEramExt,
IN ULONGPTR uSize
);
BOOLEAN CheckExternalSize(
IN PDRIVER_OBJECT pDrvObj,
IN PERAM_EXTENSION pEramExt
);
VOID ResourceInitTiny(
IN PDRIVER_OBJECT pDrvObj,
IN PCM_RESOURCE_LIST pResList,
IN ULONGPTR uStart,
IN ULONGPTR uSize
);
//TODO: what about those not sure if tiny should remain 32bit??
BOOLEAN CheckExternalMemoryExist(
IN PDRIVER_OBJECT pDrvObj,
IN ULONGPTR uStart,
IN ULONGPTR uDiskSize,
OUT PULONGPTR puSize,
IN ULONGPTR dwMaxAdr
);
BOOLEAN ResourceSetupTiny(
IN PDRIVER_OBJECT pDrvObj,
IN ULONGPTR uStart,
IN PPHYSICAL_ADDRESS pMapAdr
);
BOOLEAN ExtReport(
IN PDRIVER_OBJECT pDrvObj,
IN PERAM_EXTENSION pEramExt
);
DWORD GetAcpiReservedMemory(
IN PDRIVER_OBJECT pDrvObj
);
DWORD CheckAcpiRsdt(
IN PDRIVER_OBJECT pDrvObj,
IN DWORD dwMinValue,
IN DWORD dwRsdt
);
DWORD CheckRsdtElements(
IN PDRIVER_OBJECT pDrvObj,
IN DWORD dwMinValue,
IN DWORD dwRsdtElement
);
/* Definitions for releasing after initialization */
#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT, DriverEntry)
#pragma alloc_text(INIT, InitFatId)
#pragma alloc_text(INIT, EramInitDisk)
#pragma alloc_text(INIT, MemSetup)
#pragma alloc_text(INIT, OsAlloc)
#pragma alloc_text(INIT, CalcAvailSize)
#pragma alloc_text(INIT, CheckSwapable)
#pragma alloc_text(INIT, CheckDeviceName)
#pragma alloc_text(INIT, CheckSwitch)
#pragma alloc_text(INIT, GetMaxAddress)
#pragma alloc_text(INIT, PrepareVolumeLabel)
#pragma alloc_text(INIT, CheckVolumeLabel)
#pragma alloc_text(INIT, PrepareExtFileName)
#pragma alloc_text(INIT, EramFormatFat)
#pragma alloc_text(INIT, EramSetup)
#pragma alloc_text(INIT, EramLocate)
#pragma alloc_text(INIT, EramFormat)
#pragma alloc_text(INIT, EramClearInfo)
#pragma alloc_text(INIT, ExtClear)
#pragma alloc_text(INIT, ExtFileClear)
#pragma alloc_text(INIT, CalcEramInfoPage)
#pragma alloc_text(INIT, EramMakeFAT)
#pragma alloc_text(INIT, EramSetLabel)
#pragma alloc_text(INIT, GetExternalStart)
#pragma alloc_text(INIT, GetMaxMem)
#pragma alloc_text(INIT, CheckMaxMem)
#pragma alloc_text(INIT, CheckExternalSize)
#pragma alloc_text(INIT, ResourceInitTiny)
#pragma alloc_text(INIT, CheckExternalMemoryExist)
#pragma alloc_text(INIT, ResourceSetupTiny)
#pragma alloc_text(INIT, ExtReport)
#pragma alloc_text(INIT, GetAcpiReservedMemory)
#pragma alloc_text(INIT, CheckAcpiRsdt)
#pragma alloc_text(INIT, CheckRsdtElements)
#endif // ALLOC_PRAGMA
#pragma pack()
| 26.575676 | 104 | 0.711227 | [
"object"
] |
b700c6e3fe3bbe0a8fa947bf8b275416105099d7 | 63,983 | c | C | ruby-2.1.5/iseq.c | kongseokhwan/kulcloud-elk-sflow-logstash | 80928788546d5d496f83897d56f8d33d99b264b6 | [
"MIT"
] | null | null | null | ruby-2.1.5/iseq.c | kongseokhwan/kulcloud-elk-sflow-logstash | 80928788546d5d496f83897d56f8d33d99b264b6 | [
"MIT"
] | null | null | null | ruby-2.1.5/iseq.c | kongseokhwan/kulcloud-elk-sflow-logstash | 80928788546d5d496f83897d56f8d33d99b264b6 | [
"MIT"
] | null | null | null | /**********************************************************************
iseq.c -
$Author: nagachika $
created at: 2006-07-11(Tue) 09:00:03 +0900
Copyright (C) 2006 Koichi Sasada
**********************************************************************/
#include "ruby/ruby.h"
#include "internal.h"
#include "eval_intern.h"
/* #define RUBY_MARK_FREE_DEBUG 1 */
#include "gc.h"
#include "vm_core.h"
#include "iseq.h"
#include "insns.inc"
#include "insns_info.inc"
#define ISEQ_MAJOR_VERSION 2
#define ISEQ_MINOR_VERSION 1
VALUE rb_cISeq;
#define hidden_obj_p(obj) (!SPECIAL_CONST_P(obj) && !RBASIC(obj)->klass)
static inline VALUE
obj_resurrect(VALUE obj)
{
if (hidden_obj_p(obj)) {
switch (BUILTIN_TYPE(obj)) {
case T_STRING:
obj = rb_str_resurrect(obj);
break;
case T_ARRAY:
obj = rb_ary_resurrect(obj);
break;
}
}
return obj;
}
static void
compile_data_free(struct iseq_compile_data *compile_data)
{
if (compile_data) {
struct iseq_compile_data_storage *cur, *next;
cur = compile_data->storage_head;
while (cur) {
next = cur->next;
ruby_xfree(cur);
cur = next;
}
ruby_xfree(compile_data);
}
}
static void
iseq_free(void *ptr)
{
rb_iseq_t *iseq;
RUBY_FREE_ENTER("iseq");
if (ptr) {
iseq = ptr;
if (!iseq->orig) {
/* It's possible that strings are freed */
if (0) {
RUBY_GC_INFO("%s @ %s\n", RSTRING_PTR(iseq->location.label),
RSTRING_PTR(iseq->location.path));
}
if (iseq->iseq != iseq->iseq_encoded) {
RUBY_FREE_UNLESS_NULL(iseq->iseq_encoded);
}
RUBY_FREE_UNLESS_NULL(iseq->iseq);
RUBY_FREE_UNLESS_NULL(iseq->line_info_table);
RUBY_FREE_UNLESS_NULL(iseq->local_table);
RUBY_FREE_UNLESS_NULL(iseq->is_entries);
RUBY_FREE_UNLESS_NULL(iseq->callinfo_entries);
RUBY_FREE_UNLESS_NULL(iseq->catch_table);
RUBY_FREE_UNLESS_NULL(iseq->arg_opt_table);
RUBY_FREE_UNLESS_NULL(iseq->arg_keyword_table);
compile_data_free(iseq->compile_data);
}
ruby_xfree(ptr);
}
RUBY_FREE_LEAVE("iseq");
}
static void
iseq_mark(void *ptr)
{
RUBY_MARK_ENTER("iseq");
if (ptr) {
rb_iseq_t *iseq = ptr;
RUBY_GC_INFO("%s @ %s\n", RSTRING_PTR(iseq->location.label), RSTRING_PTR(iseq->location.path));
RUBY_MARK_UNLESS_NULL(iseq->mark_ary);
RUBY_MARK_UNLESS_NULL(iseq->location.label);
RUBY_MARK_UNLESS_NULL(iseq->location.base_label);
RUBY_MARK_UNLESS_NULL(iseq->location.path);
RUBY_MARK_UNLESS_NULL(iseq->location.absolute_path);
RUBY_MARK_UNLESS_NULL((VALUE)iseq->cref_stack);
RUBY_MARK_UNLESS_NULL(iseq->klass);
RUBY_MARK_UNLESS_NULL(iseq->coverage);
RUBY_MARK_UNLESS_NULL(iseq->orig);
if (iseq->compile_data != 0) {
struct iseq_compile_data *const compile_data = iseq->compile_data;
RUBY_MARK_UNLESS_NULL(compile_data->mark_ary);
RUBY_MARK_UNLESS_NULL(compile_data->err_info);
RUBY_MARK_UNLESS_NULL(compile_data->catch_table_ary);
}
}
RUBY_MARK_LEAVE("iseq");
}
static size_t
iseq_memsize(const void *ptr)
{
size_t size = sizeof(rb_iseq_t);
const rb_iseq_t *iseq;
if (ptr) {
iseq = ptr;
if (!iseq->orig) {
if (iseq->iseq != iseq->iseq_encoded) {
size += iseq->iseq_size * sizeof(VALUE);
}
size += iseq->iseq_size * sizeof(VALUE);
size += iseq->line_info_size * sizeof(struct iseq_line_info_entry);
size += iseq->local_table_size * sizeof(ID);
size += iseq->catch_table_size * sizeof(struct iseq_catch_table_entry);
size += iseq->arg_opts * sizeof(VALUE);
size += iseq->is_size * sizeof(union iseq_inline_storage_entry);
size += iseq->callinfo_size * sizeof(rb_call_info_t);
if (iseq->compile_data) {
struct iseq_compile_data_storage *cur;
cur = iseq->compile_data->storage_head;
while (cur) {
size += cur->size + sizeof(struct iseq_compile_data_storage);
cur = cur->next;
}
size += sizeof(struct iseq_compile_data);
}
}
}
return size;
}
static const rb_data_type_t iseq_data_type = {
"iseq",
{
iseq_mark,
iseq_free,
iseq_memsize,
}, /* functions */
NULL, NULL,
RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
};
static VALUE
iseq_alloc(VALUE klass)
{
rb_iseq_t *iseq;
return TypedData_Make_Struct(klass, rb_iseq_t, &iseq_data_type, iseq);
}
static rb_iseq_location_t *
iseq_location_setup(rb_iseq_t *iseq, VALUE path, VALUE absolute_path, VALUE name, size_t first_lineno)
{
rb_iseq_location_t *loc = &iseq->location;
RB_OBJ_WRITE(iseq->self, &loc->path, path);
if (RTEST(absolute_path) && rb_str_cmp(path, absolute_path) == 0) {
RB_OBJ_WRITE(iseq->self, &loc->absolute_path, path);
}
else {
RB_OBJ_WRITE(iseq->self, &loc->absolute_path, absolute_path);
}
RB_OBJ_WRITE(iseq->self, &loc->label, name);
RB_OBJ_WRITE(iseq->self, &loc->base_label, name);
loc->first_lineno = first_lineno;
return loc;
}
#define ISEQ_SET_CREF(iseq, cref) RB_OBJ_WRITE((iseq)->self, &(iseq)->cref_stack, (cref))
static void
set_relation(rb_iseq_t *iseq, const VALUE parent)
{
const VALUE type = iseq->type;
rb_thread_t *th = GET_THREAD();
rb_iseq_t *piseq;
/* set class nest stack */
if (type == ISEQ_TYPE_TOP) {
/* toplevel is private */
RB_OBJ_WRITE(iseq->self, &iseq->cref_stack, NEW_CREF(rb_cObject));
iseq->cref_stack->nd_refinements = Qnil;
iseq->cref_stack->nd_visi = NOEX_PRIVATE;
if (th->top_wrapper) {
NODE *cref = NEW_CREF(th->top_wrapper);
cref->nd_refinements = Qnil;
cref->nd_visi = NOEX_PRIVATE;
RB_OBJ_WRITE(cref, &cref->nd_next, iseq->cref_stack);
ISEQ_SET_CREF(iseq, cref);
}
iseq->local_iseq = iseq;
}
else if (type == ISEQ_TYPE_METHOD || type == ISEQ_TYPE_CLASS) {
ISEQ_SET_CREF(iseq, NEW_CREF(0)); /* place holder */
iseq->cref_stack->nd_refinements = Qnil;
iseq->local_iseq = iseq;
}
else if (RTEST(parent)) {
GetISeqPtr(parent, piseq);
ISEQ_SET_CREF(iseq, piseq->cref_stack);
iseq->local_iseq = piseq->local_iseq;
}
if (RTEST(parent)) {
GetISeqPtr(parent, piseq);
iseq->parent_iseq = piseq;
}
if (type == ISEQ_TYPE_MAIN) {
iseq->local_iseq = iseq;
}
}
void
rb_iseq_add_mark_object(rb_iseq_t *iseq, VALUE obj)
{
if (!RTEST(iseq->mark_ary)) {
RB_OBJ_WRITE(iseq->self, &iseq->mark_ary, rb_ary_tmp_new(3));
RBASIC_CLEAR_CLASS(iseq->mark_ary);
}
rb_ary_push(iseq->mark_ary, obj);
}
static VALUE
prepare_iseq_build(rb_iseq_t *iseq,
VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
VALUE parent, enum iseq_type type, VALUE block_opt,
const rb_compile_option_t *option)
{
iseq->type = type;
iseq->arg_rest = -1;
iseq->arg_block = -1;
iseq->arg_keyword = -1;
RB_OBJ_WRITE(iseq->self, &iseq->klass, 0);
set_relation(iseq, parent);
name = rb_fstring(name);
path = rb_fstring(path);
if (RTEST(absolute_path))
absolute_path = rb_fstring(absolute_path);
iseq_location_setup(iseq, path, absolute_path, name, first_lineno);
if (iseq != iseq->local_iseq) {
RB_OBJ_WRITE(iseq->self, &iseq->location.base_label, iseq->local_iseq->location.label);
}
iseq->defined_method_id = 0;
RB_OBJ_WRITE(iseq->self, &iseq->mark_ary, 0);
/*
* iseq->special_block_builder = GC_GUARDED_PTR_REF(block_opt);
* iseq->cached_special_block_builder = 0;
* iseq->cached_special_block = 0;
*/
iseq->compile_data = ALLOC(struct iseq_compile_data);
MEMZERO(iseq->compile_data, struct iseq_compile_data, 1);
RB_OBJ_WRITE(iseq->self, &iseq->compile_data->err_info, Qnil);
RB_OBJ_WRITE(iseq->self, &iseq->compile_data->mark_ary, rb_ary_tmp_new(3));
iseq->compile_data->storage_head = iseq->compile_data->storage_current =
(struct iseq_compile_data_storage *)
ALLOC_N(char, INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE +
sizeof(struct iseq_compile_data_storage));
RB_OBJ_WRITE(iseq->self, &iseq->compile_data->catch_table_ary, rb_ary_new());
iseq->compile_data->storage_head->pos = 0;
iseq->compile_data->storage_head->next = 0;
iseq->compile_data->storage_head->size =
INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE;
iseq->compile_data->storage_head->buff =
(char *)(&iseq->compile_data->storage_head->buff + 1);
iseq->compile_data->option = option;
iseq->compile_data->last_coverable_line = -1;
RB_OBJ_WRITE(iseq->self, &iseq->coverage, Qfalse);
if (!GET_THREAD()->parse_in_eval) {
VALUE coverages = rb_get_coverages();
if (RTEST(coverages)) {
RB_OBJ_WRITE(iseq->self, &iseq->coverage, rb_hash_lookup(coverages, path));
if (NIL_P(iseq->coverage)) RB_OBJ_WRITE(iseq->self, &iseq->coverage, Qfalse);
}
}
return Qtrue;
}
static VALUE
cleanup_iseq_build(rb_iseq_t *iseq)
{
struct iseq_compile_data *data = iseq->compile_data;
VALUE err = data->err_info;
iseq->compile_data = 0;
compile_data_free(data);
if (RTEST(err)) {
rb_funcall2(err, rb_intern("set_backtrace"), 1, &iseq->location.path);
rb_exc_raise(err);
}
return Qtrue;
}
static rb_compile_option_t COMPILE_OPTION_DEFAULT = {
OPT_INLINE_CONST_CACHE, /* int inline_const_cache; */
OPT_PEEPHOLE_OPTIMIZATION, /* int peephole_optimization; */
OPT_TAILCALL_OPTIMIZATION, /* int tailcall_optimization */
OPT_SPECIALISED_INSTRUCTION, /* int specialized_instruction; */
OPT_OPERANDS_UNIFICATION, /* int operands_unification; */
OPT_INSTRUCTIONS_UNIFICATION, /* int instructions_unification; */
OPT_STACK_CACHING, /* int stack_caching; */
OPT_TRACE_INSTRUCTION, /* int trace_instruction */
};
static const rb_compile_option_t COMPILE_OPTION_FALSE = {0};
static void
make_compile_option(rb_compile_option_t *option, VALUE opt)
{
if (opt == Qnil) {
*option = COMPILE_OPTION_DEFAULT;
}
else if (opt == Qfalse) {
*option = COMPILE_OPTION_FALSE;
}
else if (opt == Qtrue) {
int i;
for (i = 0; i < (int)(sizeof(rb_compile_option_t) / sizeof(int)); ++i)
((int *)option)[i] = 1;
}
else if (CLASS_OF(opt) == rb_cHash) {
*option = COMPILE_OPTION_DEFAULT;
#define SET_COMPILE_OPTION(o, h, mem) \
{ VALUE flag = rb_hash_aref((h), ID2SYM(rb_intern(#mem))); \
if (flag == Qtrue) { (o)->mem = 1; } \
else if (flag == Qfalse) { (o)->mem = 0; } \
}
#define SET_COMPILE_OPTION_NUM(o, h, mem) \
{ VALUE num = rb_hash_aref(opt, ID2SYM(rb_intern(#mem))); \
if (!NIL_P(num)) (o)->mem = NUM2INT(num); \
}
SET_COMPILE_OPTION(option, opt, inline_const_cache);
SET_COMPILE_OPTION(option, opt, peephole_optimization);
SET_COMPILE_OPTION(option, opt, tailcall_optimization);
SET_COMPILE_OPTION(option, opt, specialized_instruction);
SET_COMPILE_OPTION(option, opt, operands_unification);
SET_COMPILE_OPTION(option, opt, instructions_unification);
SET_COMPILE_OPTION(option, opt, stack_caching);
SET_COMPILE_OPTION(option, opt, trace_instruction);
SET_COMPILE_OPTION_NUM(option, opt, debug_level);
#undef SET_COMPILE_OPTION
#undef SET_COMPILE_OPTION_NUM
}
else {
rb_raise(rb_eTypeError, "Compile option must be Hash/true/false/nil");
}
}
static VALUE
make_compile_option_value(rb_compile_option_t *option)
{
VALUE opt = rb_hash_new();
#define SET_COMPILE_OPTION(o, h, mem) \
rb_hash_aset((h), ID2SYM(rb_intern(#mem)), (o)->mem ? Qtrue : Qfalse)
#define SET_COMPILE_OPTION_NUM(o, h, mem) \
rb_hash_aset((h), ID2SYM(rb_intern(#mem)), INT2NUM((o)->mem))
{
SET_COMPILE_OPTION(option, opt, inline_const_cache);
SET_COMPILE_OPTION(option, opt, peephole_optimization);
SET_COMPILE_OPTION(option, opt, tailcall_optimization);
SET_COMPILE_OPTION(option, opt, specialized_instruction);
SET_COMPILE_OPTION(option, opt, operands_unification);
SET_COMPILE_OPTION(option, opt, instructions_unification);
SET_COMPILE_OPTION(option, opt, stack_caching);
SET_COMPILE_OPTION(option, opt, trace_instruction);
SET_COMPILE_OPTION_NUM(option, opt, debug_level);
}
#undef SET_COMPILE_OPTION
#undef SET_COMPILE_OPTION_NUM
return opt;
}
VALUE
rb_iseq_new(NODE *node, VALUE name, VALUE path, VALUE absolute_path,
VALUE parent, enum iseq_type type)
{
return rb_iseq_new_with_opt(node, name, path, absolute_path, INT2FIX(0), parent, type,
&COMPILE_OPTION_DEFAULT);
}
VALUE
rb_iseq_new_top(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE parent)
{
return rb_iseq_new_with_opt(node, name, path, absolute_path, INT2FIX(0), parent, ISEQ_TYPE_TOP,
&COMPILE_OPTION_DEFAULT);
}
VALUE
rb_iseq_new_main(NODE *node, VALUE path, VALUE absolute_path)
{
rb_thread_t *th = GET_THREAD();
VALUE parent = th->base_block->iseq->self;
return rb_iseq_new_with_opt(node, rb_str_new2("<main>"), path, absolute_path, INT2FIX(0),
parent, ISEQ_TYPE_MAIN, &COMPILE_OPTION_DEFAULT);
}
static VALUE
rb_iseq_new_with_bopt_and_opt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
VALUE parent, enum iseq_type type, VALUE bopt,
const rb_compile_option_t *option)
{
rb_iseq_t *iseq;
VALUE self = iseq_alloc(rb_cISeq);
GetISeqPtr(self, iseq);
iseq->self = self;
prepare_iseq_build(iseq, name, path, absolute_path, first_lineno, parent, type, bopt, option);
rb_iseq_compile_node(self, node);
cleanup_iseq_build(iseq);
return self;
}
VALUE
rb_iseq_new_with_opt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
VALUE parent, enum iseq_type type,
const rb_compile_option_t *option)
{
/* TODO: argument check */
return rb_iseq_new_with_bopt_and_opt(node, name, path, absolute_path, first_lineno, parent, type,
Qfalse, option);
}
VALUE
rb_iseq_new_with_bopt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno,
VALUE parent, enum iseq_type type, VALUE bopt)
{
/* TODO: argument check */
return rb_iseq_new_with_bopt_and_opt(node, name, path, absolute_path, first_lineno, parent, type,
bopt, &COMPILE_OPTION_DEFAULT);
}
#define CHECK_ARRAY(v) rb_convert_type((v), T_ARRAY, "Array", "to_ary")
#define CHECK_STRING(v) rb_convert_type((v), T_STRING, "String", "to_str")
#define CHECK_SYMBOL(v) rb_convert_type((v), T_SYMBOL, "Symbol", "to_sym")
static inline VALUE CHECK_INTEGER(VALUE v) {(void)NUM2LONG(v); return v;}
static VALUE
iseq_load(VALUE self, VALUE data, VALUE parent, VALUE opt)
{
VALUE iseqval = iseq_alloc(self);
VALUE magic, version1, version2, format_type, misc;
VALUE name, path, absolute_path, first_lineno;
VALUE type, body, locals, args, exception;
st_data_t iseq_type;
static struct st_table *type_map_cache = 0;
struct st_table *type_map = 0;
rb_iseq_t *iseq;
rb_compile_option_t option;
int i = 0;
/* [magic, major_version, minor_version, format_type, misc,
* label, path, first_lineno,
* type, locals, args, exception_table, body]
*/
data = CHECK_ARRAY(data);
magic = CHECK_STRING(rb_ary_entry(data, i++));
version1 = CHECK_INTEGER(rb_ary_entry(data, i++));
version2 = CHECK_INTEGER(rb_ary_entry(data, i++));
format_type = CHECK_INTEGER(rb_ary_entry(data, i++));
misc = rb_ary_entry(data, i++); /* TODO */
((void)magic, (void)version1, (void)version2, (void)format_type, (void)misc);
name = CHECK_STRING(rb_ary_entry(data, i++));
path = CHECK_STRING(rb_ary_entry(data, i++));
absolute_path = rb_ary_entry(data, i++);
absolute_path = NIL_P(absolute_path) ? Qnil : CHECK_STRING(absolute_path);
first_lineno = CHECK_INTEGER(rb_ary_entry(data, i++));
type = CHECK_SYMBOL(rb_ary_entry(data, i++));
locals = CHECK_ARRAY(rb_ary_entry(data, i++));
args = rb_ary_entry(data, i++);
if (FIXNUM_P(args) || (args = CHECK_ARRAY(args))) {
/* */
}
exception = CHECK_ARRAY(rb_ary_entry(data, i++));
body = CHECK_ARRAY(rb_ary_entry(data, i++));
GetISeqPtr(iseqval, iseq);
iseq->self = iseqval;
iseq->local_iseq = iseq;
type_map = type_map_cache;
if (type_map == 0) {
struct st_table *cached_map;
type_map = st_init_numtable();
st_insert(type_map, ID2SYM(rb_intern("top")), ISEQ_TYPE_TOP);
st_insert(type_map, ID2SYM(rb_intern("method")), ISEQ_TYPE_METHOD);
st_insert(type_map, ID2SYM(rb_intern("block")), ISEQ_TYPE_BLOCK);
st_insert(type_map, ID2SYM(rb_intern("class")), ISEQ_TYPE_CLASS);
st_insert(type_map, ID2SYM(rb_intern("rescue")), ISEQ_TYPE_RESCUE);
st_insert(type_map, ID2SYM(rb_intern("ensure")), ISEQ_TYPE_ENSURE);
st_insert(type_map, ID2SYM(rb_intern("eval")), ISEQ_TYPE_EVAL);
st_insert(type_map, ID2SYM(rb_intern("main")), ISEQ_TYPE_MAIN);
st_insert(type_map, ID2SYM(rb_intern("defined_guard")), ISEQ_TYPE_DEFINED_GUARD);
cached_map = ATOMIC_PTR_CAS(type_map_cache, (struct st_table *)0, type_map);
if (cached_map) {
st_free_table(type_map);
type_map = cached_map;
}
}
if (st_lookup(type_map, type, &iseq_type) == 0) {
ID typeid = SYM2ID(type);
VALUE typename = rb_id2str(typeid);
if (typename)
rb_raise(rb_eTypeError, "unsupport type: :%"PRIsVALUE, typename);
else
rb_raise(rb_eTypeError, "unsupport type: %p", (void *)typeid);
}
if (parent == Qnil) {
parent = 0;
}
make_compile_option(&option, opt);
prepare_iseq_build(iseq, name, path, absolute_path, first_lineno,
parent, (enum iseq_type)iseq_type, 0, &option);
rb_iseq_build_from_ary(iseq, locals, args, exception, body);
cleanup_iseq_build(iseq);
return iseqval;
}
/*
* :nodoc:
*/
static VALUE
iseq_s_load(int argc, VALUE *argv, VALUE self)
{
VALUE data, opt=Qnil;
rb_scan_args(argc, argv, "11", &data, &opt);
return iseq_load(self, data, 0, opt);
}
VALUE
rb_iseq_load(VALUE data, VALUE parent, VALUE opt)
{
return iseq_load(rb_cISeq, data, parent, opt);
}
VALUE
rb_iseq_compile_with_option(VALUE src, VALUE file, VALUE absolute_path, VALUE line, rb_block_t *base_block, VALUE opt)
{
int state;
rb_thread_t *th = GET_THREAD();
rb_block_t *prev_base_block = th->base_block;
VALUE iseqval = Qundef;
th->base_block = base_block;
TH_PUSH_TAG(th);
if ((state = EXEC_TAG()) == 0) {
VALUE parser;
int ln = NUM2INT(line);
NODE *node;
rb_compile_option_t option;
StringValueCStr(file);
make_compile_option(&option, opt);
parser = rb_parser_new();
if (RB_TYPE_P((src), T_FILE))
node = rb_parser_compile_file_path(parser, file, src, ln);
else {
node = rb_parser_compile_string_path(parser, file, src, ln);
if (!node) {
rb_exc_raise(GET_THREAD()->errinfo); /* TODO: check err */
}
}
if (base_block && base_block->iseq) {
iseqval = rb_iseq_new_with_opt(node, base_block->iseq->location.label,
file, absolute_path, line, base_block->iseq->self,
ISEQ_TYPE_EVAL, &option);
}
else {
iseqval = rb_iseq_new_with_opt(node, rb_str_new2("<compiled>"), file, absolute_path, line, Qfalse,
ISEQ_TYPE_TOP, &option);
}
}
TH_POP_TAG();
th->base_block = prev_base_block;
if (state) {
JUMP_TAG(state);
}
return iseqval;
}
VALUE
rb_iseq_compile(VALUE src, VALUE file, VALUE line)
{
return rb_iseq_compile_with_option(src, file, Qnil, line, 0, Qnil);
}
VALUE
rb_iseq_compile_on_base(VALUE src, VALUE file, VALUE line, rb_block_t *base_block)
{
return rb_iseq_compile_with_option(src, file, Qnil, line, base_block, Qnil);
}
/*
* call-seq:
* InstructionSequence.compile(source[, file[, path[, line[, options]]]]) -> iseq
* InstructionSequence.new(source[, file[, path[, line[, options]]]]) -> iseq
*
* Takes +source+, a String of Ruby code and compiles it to an
* InstructionSequence.
*
* Optionally takes +file+, +path+, and +line+ which describe the filename,
* absolute path and first line number of the ruby code in +source+ which are
* metadata attached to the returned +iseq+.
*
* +options+, which can be +true+, +false+ or a +Hash+, is used to
* modify the default behavior of the Ruby iseq compiler.
*
* For details regarding valid compile options see ::compile_option=.
*
* RubyVM::InstructionSequence.compile("a = 1 + 2")
* #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
*
*/
static VALUE
iseq_s_compile(int argc, VALUE *argv, VALUE self)
{
VALUE src, file = Qnil, path = Qnil, line = INT2FIX(1), opt = Qnil;
rb_secure(1);
rb_scan_args(argc, argv, "14", &src, &file, &path, &line, &opt);
if (NIL_P(file)) file = rb_str_new2("<compiled>");
if (NIL_P(line)) line = INT2FIX(1);
return rb_iseq_compile_with_option(src, file, path, line, 0, opt);
}
/*
* call-seq:
* InstructionSequence.compile_file(file[, options]) -> iseq
*
* Takes +file+, a String with the location of a Ruby source file, reads,
* parses and compiles the file, and returns +iseq+, the compiled
* InstructionSequence with source location metadata set.
*
* Optionally takes +options+, which can be +true+, +false+ or a +Hash+, to
* modify the default behavior of the Ruby iseq compiler.
*
* For details regarding valid compile options see ::compile_option=.
*
* # /tmp/hello.rb
* puts "Hello, world!"
*
* # elsewhere
* RubyVM::InstructionSequence.compile_file("/tmp/hello.rb")
* #=> <RubyVM::InstructionSequence:<main>@/tmp/hello.rb>
*/
static VALUE
iseq_s_compile_file(int argc, VALUE *argv, VALUE self)
{
VALUE file, line = INT2FIX(1), opt = Qnil;
VALUE parser;
VALUE f;
NODE *node;
const char *fname;
rb_compile_option_t option;
rb_secure(1);
rb_scan_args(argc, argv, "11", &file, &opt);
FilePathValue(file);
fname = StringValueCStr(file);
f = rb_file_open_str(file, "r");
parser = rb_parser_new();
node = rb_parser_compile_file(parser, fname, f, NUM2INT(line));
make_compile_option(&option, opt);
return rb_iseq_new_with_opt(node, rb_str_new2("<main>"), file,
rb_realpath_internal(Qnil, file, 1), line, Qfalse,
ISEQ_TYPE_TOP, &option);
}
/*
* call-seq:
* InstructionSequence.compile_option = options
*
* Sets the default values for various optimizations in the Ruby iseq
* compiler.
*
* Possible values for +options+ include +true+, which enables all options,
* +false+ which disables all options, and +nil+ which leaves all options
* unchanged.
*
* You can also pass a +Hash+ of +options+ that you want to change, any
* options not present in the hash will be left unchanged.
*
* Possible option names (which are keys in +options+) which can be set to
* +true+ or +false+ include:
*
* * +:inline_const_cache+
* * +:instructions_unification+
* * +:operands_unification+
* * +:peephole_optimization+
* * +:specialized_instruction+
* * +:stack_caching+
* * +:tailcall_optimization+
* * +:trace_instruction+
*
* Additionally, +:debug_level+ can be set to an integer.
*
* These default options can be overwritten for a single run of the iseq
* compiler by passing any of the above values as the +options+ parameter to
* ::new, ::compile and ::compile_file.
*/
static VALUE
iseq_s_compile_option_set(VALUE self, VALUE opt)
{
rb_compile_option_t option;
rb_secure(1);
make_compile_option(&option, opt);
COMPILE_OPTION_DEFAULT = option;
return opt;
}
/*
* call-seq:
* InstructionSequence.compile_option -> options
*
* Returns a hash of default options used by the Ruby iseq compiler.
*
* For details, see InstructionSequence.compile_option=.
*/
static VALUE
iseq_s_compile_option_get(VALUE self)
{
return make_compile_option_value(&COMPILE_OPTION_DEFAULT);
}
static rb_iseq_t *
iseq_check(VALUE val)
{
rb_iseq_t *iseq;
GetISeqPtr(val, iseq);
if (!iseq->location.label) {
rb_raise(rb_eTypeError, "uninitialized InstructionSequence");
}
return iseq;
}
/*
* call-seq:
* iseq.eval -> obj
*
* Evaluates the instruction sequence and returns the result.
*
* RubyVM::InstructionSequence.compile("1 + 2").eval #=> 3
*/
static VALUE
iseq_eval(VALUE self)
{
rb_secure(1);
return rb_iseq_eval(self);
}
/*
* Returns a human-readable string representation of this instruction
* sequence, including the #label and #path.
*/
static VALUE
iseq_inspect(VALUE self)
{
rb_iseq_t *iseq;
GetISeqPtr(self, iseq);
if (!iseq->location.label) {
return rb_sprintf("#<%s: uninitialized>", rb_obj_classname(self));
}
return rb_sprintf("<%s:%s@%s>",
rb_obj_classname(self),
RSTRING_PTR(iseq->location.label), RSTRING_PTR(iseq->location.path));
}
/*
* Returns the path of this instruction sequence.
*
* <code><compiled></code> if the iseq was evaluated from a string.
*
* For example, using irb:
*
* iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
* #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
* iseq.path
* #=> "<compiled>"
*
* Using ::compile_file:
*
* # /tmp/method.rb
* def hello
* puts "hello, world"
* end
*
* # in irb
* > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
* > iseq.path #=> /tmp/method.rb
*/
VALUE
rb_iseq_path(VALUE self)
{
rb_iseq_t *iseq;
GetISeqPtr(self, iseq);
return iseq->location.path;
}
/*
* Returns the absolute path of this instruction sequence.
*
* +nil+ if the iseq was evaluated from a string.
*
* For example, using ::compile_file:
*
* # /tmp/method.rb
* def hello
* puts "hello, world"
* end
*
* # in irb
* > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
* > iseq.absolute_path #=> /tmp/method.rb
*/
VALUE
rb_iseq_absolute_path(VALUE self)
{
rb_iseq_t *iseq;
GetISeqPtr(self, iseq);
return iseq->location.absolute_path;
}
/* Returns the label of this instruction sequence.
*
* <code><main></code> if it's at the top level, <code><compiled></code> if it
* was evaluated from a string.
*
* For example, using irb:
*
* iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
* #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
* iseq.label
* #=> "<compiled>"
*
* Using ::compile_file:
*
* # /tmp/method.rb
* def hello
* puts "hello, world"
* end
*
* # in irb
* > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
* > iseq.label #=> <main>
*/
VALUE
rb_iseq_label(VALUE self)
{
rb_iseq_t *iseq;
GetISeqPtr(self, iseq);
return iseq->location.label;
}
/* Returns the base label of this instruction sequence.
*
* For example, using irb:
*
* iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
* #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
* iseq.base_label
* #=> "<compiled>"
*
* Using ::compile_file:
*
* # /tmp/method.rb
* def hello
* puts "hello, world"
* end
*
* # in irb
* > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb')
* > iseq.base_label #=> <main>
*/
VALUE
rb_iseq_base_label(VALUE self)
{
rb_iseq_t *iseq;
GetISeqPtr(self, iseq);
return iseq->location.base_label;
}
/* Returns the number of the first source line where the instruction sequence
* was loaded from.
*
* For example, using irb:
*
* iseq = RubyVM::InstructionSequence.compile('num = 1 + 2')
* #=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
* iseq.first_lineno
* #=> 1
*/
VALUE
rb_iseq_first_lineno(VALUE self)
{
rb_iseq_t *iseq;
GetISeqPtr(self, iseq);
return iseq->location.first_lineno;
}
VALUE
rb_iseq_klass(VALUE self)
{
rb_iseq_t *iseq;
GetISeqPtr(self, iseq);
return iseq->local_iseq->klass;
}
VALUE
rb_iseq_method_name(VALUE self)
{
rb_iseq_t *iseq, *local_iseq;
GetISeqPtr(self, iseq);
local_iseq = iseq->local_iseq;
if (local_iseq->type == ISEQ_TYPE_METHOD) {
return local_iseq->location.base_label;
}
else {
return Qnil;
}
}
static
VALUE iseq_data_to_ary(rb_iseq_t *iseq);
/*
* call-seq:
* iseq.to_a -> ary
*
* Returns an Array with 14 elements representing the instruction sequence
* with the following data:
*
* [magic]
* A string identifying the data format. <b>Always
* +YARVInstructionSequence/SimpleDataFormat+.</b>
*
* [major_version]
* The major version of the instruction sequence.
*
* [minor_version]
* The minor version of the instruction sequence.
*
* [format_type]
* A number identifying the data format. <b>Always 1</b>.
*
* [misc]
* A hash containing:
*
* [+:arg_size+]
* the total number of arguments taken by the method or the block (0 if
* _iseq_ doesn't represent a method or block)
* [+:local_size+]
* the number of local variables + 1
* [+:stack_max+]
* used in calculating the stack depth at which a SystemStackError is
* thrown.
*
* [#label]
* The name of the context (block, method, class, module, etc.) that this
* instruction sequence belongs to.
*
* <code><main></code> if it's at the top level, <code><compiled></code> if
* it was evaluated from a string.
*
* [#path]
* The relative path to the Ruby file where the instruction sequence was
* loaded from.
*
* <code><compiled></code> if the iseq was evaluated from a string.
*
* [#absolute_path]
* The absolute path to the Ruby file where the instruction sequence was
* loaded from.
*
* +nil+ if the iseq was evaluated from a string.
*
* [#first_lineno]
* The number of the first source line where the instruction sequence was
* loaded from.
*
* [type]
* The type of the instruction sequence.
*
* Valid values are +:top+, +:method+, +:block+, +:class+, +:rescue+,
* +:ensure+, +:eval+, +:main+, and +:defined_guard+.
*
* [locals]
* An array containing the names of all arguments and local variables as
* symbols.
*
* [args]
* The arity if the method or block only has required arguments.
*
* Otherwise an array of:
*
* [required_argc, [optional_arg_labels, ...],
* splat_index, post_splat_argc, post_splat_index,
* block_index, simple]
*
* More info about these values can be found in +vm_core.h+.
*
* [catch_table]
* A list of exceptions and control flow operators (rescue, next, redo,
* break, etc.).
*
* [bytecode]
* An array of arrays containing the instruction names and operands that
* make up the body of the instruction sequence.
*
*/
static VALUE
iseq_to_a(VALUE self)
{
rb_iseq_t *iseq = iseq_check(self);
rb_secure(1);
return iseq_data_to_ary(iseq);
}
/* TODO: search algorithm is brute force.
this should be binary search or so. */
static struct iseq_line_info_entry *
get_line_info(const rb_iseq_t *iseq, size_t pos)
{
size_t i = 0, size = iseq->line_info_size;
struct iseq_line_info_entry *table = iseq->line_info_table;
const int debug = 0;
if (debug) {
printf("size: %"PRIdSIZE"\n", size);
printf("table[%"PRIdSIZE"]: position: %d, line: %d, pos: %"PRIdSIZE"\n",
i, table[i].position, table[i].line_no, pos);
}
if (size == 0) {
return 0;
}
else if (size == 1) {
return &table[0];
}
else {
for (i=1; i<size; i++) {
if (debug) printf("table[%"PRIdSIZE"]: position: %d, line: %d, pos: %"PRIdSIZE"\n",
i, table[i].position, table[i].line_no, pos);
if (table[i].position == pos) {
return &table[i];
}
if (table[i].position > pos) {
return &table[i-1];
}
}
}
return &table[i-1];
}
static unsigned int
find_line_no(const rb_iseq_t *iseq, size_t pos)
{
struct iseq_line_info_entry *entry = get_line_info(iseq, pos);
if (entry) {
return entry->line_no;
}
else {
return 0;
}
}
unsigned int
rb_iseq_line_no(const rb_iseq_t *iseq, size_t pos)
{
if (pos == 0) {
return find_line_no(iseq, pos);
}
else {
return find_line_no(iseq, pos - 1);
}
}
static VALUE
id_to_name(ID id, VALUE default_value)
{
VALUE str = rb_id2str(id);
if (!str) {
str = default_value;
}
else if (!rb_str_symname_p(str)) {
str = rb_str_inspect(str);
}
return str;
}
VALUE
rb_insn_operand_intern(rb_iseq_t *iseq,
VALUE insn, int op_no, VALUE op,
int len, size_t pos, VALUE *pnop, VALUE child)
{
const char *types = insn_op_types(insn);
char type = types[op_no];
VALUE ret;
switch (type) {
case TS_OFFSET: /* LONG */
ret = rb_sprintf("%"PRIdVALUE, (VALUE)(pos + len + op));
break;
case TS_NUM: /* ULONG */
ret = rb_sprintf("%"PRIuVALUE, op);
break;
case TS_LINDEX:{
if (insn == BIN(getlocal) || insn == BIN(setlocal)) {
if (pnop) {
rb_iseq_t *diseq = iseq;
VALUE level = *pnop, i;
for (i = 0; i < level; i++) {
diseq = diseq->parent_iseq;
}
ret = id_to_name(diseq->local_table[diseq->local_size - op], INT2FIX('*'));
}
else {
ret = rb_sprintf("%"PRIuVALUE, op);
}
}
else {
ret = rb_inspect(INT2FIX(op));
}
break;
}
case TS_ID: /* ID (symbol) */
op = ID2SYM(op);
case TS_VALUE: /* VALUE */
op = obj_resurrect(op);
ret = rb_inspect(op);
if (CLASS_OF(op) == rb_cISeq) {
if (child) {
rb_ary_push(child, op);
}
}
break;
case TS_ISEQ: /* iseq */
{
rb_iseq_t *iseq = (rb_iseq_t *)op;
if (iseq) {
ret = iseq->location.label;
if (child) {
rb_ary_push(child, iseq->self);
}
}
else {
ret = rb_str_new2("nil");
}
break;
}
case TS_GENTRY:
{
struct rb_global_entry *entry = (struct rb_global_entry *)op;
ret = rb_str_dup(rb_id2str(entry->id));
}
break;
case TS_IC:
ret = rb_sprintf("<is:%"PRIdPTRDIFF">", (union iseq_inline_storage_entry *)op - iseq->is_entries);
break;
case TS_CALLINFO:
{
rb_call_info_t *ci = (rb_call_info_t *)op;
VALUE ary = rb_ary_new();
if (ci->mid) {
rb_ary_push(ary, rb_sprintf("mid:%s", rb_id2name(ci->mid)));
}
rb_ary_push(ary, rb_sprintf("argc:%d", ci->orig_argc));
if (ci->blockiseq) {
if (child) {
rb_ary_push(child, ci->blockiseq->self);
}
rb_ary_push(ary, rb_sprintf("block:%"PRIsVALUE, ci->blockiseq->location.label));
}
if (ci->flag) {
VALUE flags = rb_ary_new();
if (ci->flag & VM_CALL_ARGS_SPLAT) rb_ary_push(flags, rb_str_new2("ARGS_SPLAT"));
if (ci->flag & VM_CALL_ARGS_BLOCKARG) rb_ary_push(flags, rb_str_new2("ARGS_BLOCKARG"));
if (ci->flag & VM_CALL_FCALL) rb_ary_push(flags, rb_str_new2("FCALL"));
if (ci->flag & VM_CALL_VCALL) rb_ary_push(flags, rb_str_new2("VCALL"));
if (ci->flag & VM_CALL_TAILCALL) rb_ary_push(flags, rb_str_new2("TAILCALL"));
if (ci->flag & VM_CALL_SUPER) rb_ary_push(flags, rb_str_new2("SUPER"));
if (ci->flag & VM_CALL_OPT_SEND) rb_ary_push(flags, rb_str_new2("SNED")); /* maybe not reachable */
if (ci->flag & VM_CALL_ARGS_SKIP_SETUP) rb_ary_push(flags, rb_str_new2("ARGS_SKIP")); /* maybe not reachable */
rb_ary_push(ary, rb_ary_join(flags, rb_str_new2("|")));
}
ret = rb_sprintf("<callinfo!%"PRIsVALUE">", rb_ary_join(ary, rb_str_new2(", ")));
}
break;
case TS_CDHASH:
ret = rb_str_new2("<cdhash>");
break;
case TS_FUNCPTR:
ret = rb_str_new2("<funcptr>");
break;
default:
rb_bug("insn_operand_intern: unknown operand type: %c", type);
}
return ret;
}
/**
* Disassemble a instruction
* Iseq -> Iseq inspect object
*/
int
rb_iseq_disasm_insn(VALUE ret, VALUE *iseq, size_t pos,
rb_iseq_t *iseqdat, VALUE child)
{
VALUE insn = iseq[pos];
int len = insn_len(insn);
int j;
const char *types = insn_op_types(insn);
VALUE str = rb_str_new(0, 0);
const char *insn_name_buff;
insn_name_buff = insn_name(insn);
if (1) {
rb_str_catf(str, "%04"PRIdSIZE" %-16s ", pos, insn_name_buff);
}
else {
rb_str_catf(str, "%04"PRIdSIZE" %-16.*s ", pos,
(int)strcspn(insn_name_buff, "_"), insn_name_buff);
}
for (j = 0; types[j]; j++) {
const char *types = insn_op_types(insn);
VALUE opstr = rb_insn_operand_intern(iseqdat, insn, j, iseq[pos + j + 1],
len, pos, &iseq[pos + j + 2],
child);
rb_str_concat(str, opstr);
if (types[j + 1]) {
rb_str_cat2(str, ", ");
}
}
{
unsigned int line_no = find_line_no(iseqdat, pos);
unsigned int prev = pos == 0 ? 0 : find_line_no(iseqdat, pos - 1);
if (line_no && line_no != prev) {
long slen = RSTRING_LEN(str);
slen = (slen > 70) ? 0 : (70 - slen);
str = rb_str_catf(str, "%*s(%4d)", (int)slen, "", line_no);
}
}
if (ret) {
rb_str_cat2(str, "\n");
rb_str_concat(ret, str);
}
else {
printf("%s\n", RSTRING_PTR(str));
}
return len;
}
static const char *
catch_type(int type)
{
switch (type) {
case CATCH_TYPE_RESCUE:
return "rescue";
case CATCH_TYPE_ENSURE:
return "ensure";
case CATCH_TYPE_RETRY:
return "retry";
case CATCH_TYPE_BREAK:
return "break";
case CATCH_TYPE_REDO:
return "redo";
case CATCH_TYPE_NEXT:
return "next";
default:
rb_bug("unknown catch type (%d)", type);
return 0;
}
}
/*
* call-seq:
* iseq.disasm -> str
* iseq.disassemble -> str
*
* Returns the instruction sequence as a +String+ in human readable form.
*
* puts RubyVM::InstructionSequence.compile('1 + 2').disasm
*
* Produces:
*
* == disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
* 0000 trace 1 ( 1)
* 0002 putobject 1
* 0004 putobject 2
* 0006 opt_plus <ic:1>
* 0008 leave
*/
VALUE
rb_iseq_disasm(VALUE self)
{
rb_iseq_t *iseqdat = iseq_check(self);
VALUE *iseq;
VALUE str = rb_str_new(0, 0);
VALUE child = rb_ary_new();
unsigned long size;
int i;
long l;
ID *tbl;
size_t n;
enum {header_minlen = 72};
rb_secure(1);
iseq = iseqdat->iseq;
size = iseqdat->iseq_size;
rb_str_cat2(str, "== disasm: ");
rb_str_concat(str, iseq_inspect(iseqdat->self));
if ((l = RSTRING_LEN(str)) < header_minlen) {
rb_str_resize(str, header_minlen);
memset(RSTRING_PTR(str) + l, '=', header_minlen - l);
}
rb_str_cat2(str, "\n");
/* show catch table information */
if (iseqdat->catch_table_size != 0) {
rb_str_cat2(str, "== catch table\n");
}
for (i = 0; i < iseqdat->catch_table_size; i++) {
struct iseq_catch_table_entry *entry = &iseqdat->catch_table[i];
rb_str_catf(str,
"| catch type: %-6s st: %04d ed: %04d sp: %04d cont: %04d\n",
catch_type((int)entry->type), (int)entry->start,
(int)entry->end, (int)entry->sp, (int)entry->cont);
if (entry->iseq) {
rb_str_concat(str, rb_iseq_disasm(entry->iseq));
}
}
if (iseqdat->catch_table_size != 0) {
rb_str_cat2(str, "|-------------------------------------"
"-----------------------------------\n");
}
/* show local table information */
tbl = iseqdat->local_table;
if (tbl) {
rb_str_catf(str,
"local table (size: %d, argc: %d "
"[opts: %d, rest: %d, post: %d, block: %d, keyword: %d@%d] s%d)\n",
iseqdat->local_size, iseqdat->argc,
iseqdat->arg_opts, iseqdat->arg_rest,
iseqdat->arg_post_len, iseqdat->arg_block,
iseqdat->arg_keywords, iseqdat->local_size-iseqdat->arg_keyword,
iseqdat->arg_simple);
for (i = 0; i < iseqdat->local_table_size; i++) {
long width;
VALUE name = id_to_name(tbl[i], 0);
char argi[0x100] = "";
char opti[0x100] = "";
if (iseqdat->arg_opts) {
int argc = iseqdat->argc;
int opts = iseqdat->arg_opts;
if (i >= argc && i < argc + opts - 1) {
snprintf(opti, sizeof(opti), "Opt=%"PRIdVALUE,
iseqdat->arg_opt_table[i - argc]);
}
}
snprintf(argi, sizeof(argi), "%s%s%s%s%s", /* arg, opts, rest, post block */
iseqdat->argc > i ? "Arg" : "",
opti,
iseqdat->arg_rest == i ? "Rest" : "",
(iseqdat->arg_post_start <= i &&
i < iseqdat->arg_post_start + iseqdat->arg_post_len) ? "Post" : "",
iseqdat->arg_block == i ? "Block" : "");
rb_str_catf(str, "[%2d] ", iseqdat->local_size - i);
width = RSTRING_LEN(str) + 11;
if (name)
rb_str_append(str, name);
else
rb_str_cat2(str, "?");
if (*argi) rb_str_catf(str, "<%s>", argi);
if ((width -= RSTRING_LEN(str)) > 0) rb_str_catf(str, "%*s", (int)width, "");
}
rb_str_cat2(str, "\n");
}
/* show each line */
for (n = 0; n < size;) {
n += rb_iseq_disasm_insn(str, iseq, n, iseqdat, child);
}
for (i = 0; i < RARRAY_LEN(child); i++) {
VALUE isv = rb_ary_entry(child, i);
rb_str_concat(str, rb_iseq_disasm(isv));
}
return str;
}
/*
* Returns the instruction sequence containing the given proc or method.
*
* For example, using irb:
*
* # a proc
* > p = proc { num = 1 + 2 }
* > RubyVM::InstructionSequence.of(p)
* > #=> <RubyVM::InstructionSequence:block in irb_binding@(irb)>
*
* # for a method
* > def foo(bar); puts bar; end
* > RubyVM::InstructionSequence.of(method(:foo))
* > #=> <RubyVM::InstructionSequence:foo@(irb)>
*
* Using ::compile_file:
*
* # /tmp/iseq_of.rb
* def hello
* puts "hello, world"
* end
*
* $a_global_proc = proc { str = 'a' + 'b' }
*
* # in irb
* > require '/tmp/iseq_of.rb'
*
* # first the method hello
* > RubyVM::InstructionSequence.of(method(:hello))
* > #=> #<RubyVM::InstructionSequence:0x007fb73d7cb1d0>
*
* # then the global proc
* > RubyVM::InstructionSequence.of($a_global_proc)
* > #=> #<RubyVM::InstructionSequence:0x007fb73d7caf78>
*/
static VALUE
iseq_s_of(VALUE klass, VALUE body)
{
VALUE ret = Qnil;
rb_iseq_t *iseq;
rb_secure(1);
if (rb_obj_is_proc(body)) {
rb_proc_t *proc;
GetProcPtr(body, proc);
iseq = proc->block.iseq;
if (RUBY_VM_NORMAL_ISEQ_P(iseq)) {
ret = iseq->self;
}
}
else if ((iseq = rb_method_get_iseq(body)) != 0) {
ret = iseq->self;
}
return ret;
}
/*
* call-seq:
* InstructionSequence.disasm(body) -> str
* InstructionSequence.disassemble(body) -> str
*
* Takes +body+, a Method or Proc object, and returns a String with the
* human readable instructions for +body+.
*
* For a Method object:
*
* # /tmp/method.rb
* def hello
* puts "hello, world"
* end
*
* puts RubyVM::InstructionSequence.disasm(method(:hello))
*
* Produces:
*
* == disasm: <RubyVM::InstructionSequence:hello@/tmp/method.rb>============
* 0000 trace 8 ( 1)
* 0002 trace 1 ( 2)
* 0004 putself
* 0005 putstring "hello, world"
* 0007 send :puts, 1, nil, 8, <ic:0>
* 0013 trace 16 ( 3)
* 0015 leave ( 2)
*
* For a Proc:
*
* # /tmp/proc.rb
* p = proc { num = 1 + 2 }
* puts RubyVM::InstructionSequence.disasm(p)
*
* Produces:
*
* == disasm: <RubyVM::InstructionSequence:block in <main>@/tmp/proc.rb>===
* == catch table
* | catch type: redo st: 0000 ed: 0012 sp: 0000 cont: 0000
* | catch type: next st: 0000 ed: 0012 sp: 0000 cont: 0012
* |------------------------------------------------------------------------
* local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
* [ 2] num
* 0000 trace 1 ( 1)
* 0002 putobject 1
* 0004 putobject 2
* 0006 opt_plus <ic:1>
* 0008 dup
* 0009 setlocal num, 0
* 0012 leave
*
*/
static VALUE
iseq_s_disasm(VALUE klass, VALUE body)
{
VALUE iseqval = iseq_s_of(klass, body);
return NIL_P(iseqval) ? Qnil : rb_iseq_disasm(iseqval);
}
const char *
ruby_node_name(int node)
{
switch (node) {
#include "node_name.inc"
default:
rb_bug("unknown node (%d)", node);
return 0;
}
}
#define DECL_SYMBOL(name) \
static VALUE sym_##name
#define INIT_SYMBOL(name) \
sym_##name = ID2SYM(rb_intern(#name))
static VALUE
register_label(struct st_table *table, unsigned long idx)
{
VALUE sym;
char buff[8 + (sizeof(idx) * CHAR_BIT * 32 / 100)];
snprintf(buff, sizeof(buff), "label_%lu", idx);
sym = ID2SYM(rb_intern(buff));
st_insert(table, idx, sym);
return sym;
}
static VALUE
exception_type2symbol(VALUE type)
{
ID id;
switch (type) {
case CATCH_TYPE_RESCUE: CONST_ID(id, "rescue"); break;
case CATCH_TYPE_ENSURE: CONST_ID(id, "ensure"); break;
case CATCH_TYPE_RETRY: CONST_ID(id, "retry"); break;
case CATCH_TYPE_BREAK: CONST_ID(id, "break"); break;
case CATCH_TYPE_REDO: CONST_ID(id, "redo"); break;
case CATCH_TYPE_NEXT: CONST_ID(id, "next"); break;
default:
rb_bug("...");
}
return ID2SYM(id);
}
static int
cdhash_each(VALUE key, VALUE value, VALUE ary)
{
rb_ary_push(ary, obj_resurrect(key));
rb_ary_push(ary, value);
return ST_CONTINUE;
}
static VALUE
iseq_data_to_ary(rb_iseq_t *iseq)
{
long i;
size_t ti;
unsigned int pos;
unsigned int line = 0;
VALUE *seq;
VALUE val = rb_ary_new();
VALUE type; /* Symbol */
VALUE locals = rb_ary_new();
VALUE args = rb_ary_new();
VALUE body = rb_ary_new(); /* [[:insn1, ...], ...] */
VALUE nbody;
VALUE exception = rb_ary_new(); /* [[....]] */
VALUE misc = rb_hash_new();
static VALUE insn_syms[VM_INSTRUCTION_SIZE];
struct st_table *labels_table = st_init_numtable();
DECL_SYMBOL(top);
DECL_SYMBOL(method);
DECL_SYMBOL(block);
DECL_SYMBOL(class);
DECL_SYMBOL(rescue);
DECL_SYMBOL(ensure);
DECL_SYMBOL(eval);
DECL_SYMBOL(main);
DECL_SYMBOL(defined_guard);
if (sym_top == 0) {
int i;
for (i=0; i<VM_INSTRUCTION_SIZE; i++) {
insn_syms[i] = ID2SYM(rb_intern(insn_name(i)));
}
INIT_SYMBOL(top);
INIT_SYMBOL(method);
INIT_SYMBOL(block);
INIT_SYMBOL(class);
INIT_SYMBOL(rescue);
INIT_SYMBOL(ensure);
INIT_SYMBOL(eval);
INIT_SYMBOL(main);
INIT_SYMBOL(defined_guard);
}
/* type */
switch (iseq->type) {
case ISEQ_TYPE_TOP: type = sym_top; break;
case ISEQ_TYPE_METHOD: type = sym_method; break;
case ISEQ_TYPE_BLOCK: type = sym_block; break;
case ISEQ_TYPE_CLASS: type = sym_class; break;
case ISEQ_TYPE_RESCUE: type = sym_rescue; break;
case ISEQ_TYPE_ENSURE: type = sym_ensure; break;
case ISEQ_TYPE_EVAL: type = sym_eval; break;
case ISEQ_TYPE_MAIN: type = sym_main; break;
case ISEQ_TYPE_DEFINED_GUARD: type = sym_defined_guard; break;
default: rb_bug("unsupported iseq type");
};
/* locals */
for (i=0; i<iseq->local_table_size; i++) {
ID lid = iseq->local_table[i];
if (lid) {
if (rb_id2str(lid)) rb_ary_push(locals, ID2SYM(lid));
}
else {
rb_ary_push(locals, ID2SYM(rb_intern("#arg_rest")));
}
}
/* args */
{
/*
* [argc, # argc
* [label1, label2, ...] # opts
* rest index,
* post_len
* post_start
* block index,
* simple,
* ]
*/
VALUE arg_opt_labels = rb_ary_new();
int j;
for (j=0; j<iseq->arg_opts; j++) {
rb_ary_push(arg_opt_labels,
register_label(labels_table, iseq->arg_opt_table[j]));
}
/* commit */
if (iseq->arg_simple == 1) {
args = INT2FIX(iseq->argc);
}
else {
rb_ary_push(args, INT2FIX(iseq->argc));
rb_ary_push(args, arg_opt_labels);
rb_ary_push(args, INT2FIX(iseq->arg_post_len));
rb_ary_push(args, INT2FIX(iseq->arg_post_start));
rb_ary_push(args, INT2FIX(iseq->arg_rest));
rb_ary_push(args, INT2FIX(iseq->arg_block));
rb_ary_push(args, INT2FIX(iseq->arg_simple));
}
}
/* body */
for (seq = iseq->iseq; seq < iseq->iseq + iseq->iseq_size; ) {
VALUE insn = *seq++;
int j, len = insn_len(insn);
VALUE *nseq = seq + len - 1;
VALUE ary = rb_ary_new2(len);
rb_ary_push(ary, insn_syms[insn]);
for (j=0; j<len-1; j++, seq++) {
switch (insn_op_type(insn, j)) {
case TS_OFFSET: {
unsigned long idx = nseq - iseq->iseq + *seq;
rb_ary_push(ary, register_label(labels_table, idx));
break;
}
case TS_LINDEX:
case TS_NUM:
rb_ary_push(ary, INT2FIX(*seq));
break;
case TS_VALUE:
rb_ary_push(ary, obj_resurrect(*seq));
break;
case TS_ISEQ:
{
rb_iseq_t *iseq = (rb_iseq_t *)*seq;
if (iseq) {
VALUE val = iseq_data_to_ary(iseq);
rb_ary_push(ary, val);
}
else {
rb_ary_push(ary, Qnil);
}
}
break;
case TS_GENTRY:
{
struct rb_global_entry *entry = (struct rb_global_entry *)*seq;
rb_ary_push(ary, ID2SYM(entry->id));
}
break;
case TS_IC:
{
union iseq_inline_storage_entry *is = (union iseq_inline_storage_entry *)*seq;
rb_ary_push(ary, INT2FIX(is - iseq->is_entries));
}
break;
case TS_CALLINFO:
{
rb_call_info_t *ci = (rb_call_info_t *)*seq;
VALUE e = rb_hash_new();
rb_hash_aset(e, ID2SYM(rb_intern("mid")), ci->mid ? ID2SYM(ci->mid) : Qnil);
rb_hash_aset(e, ID2SYM(rb_intern("flag")), ULONG2NUM(ci->flag));
rb_hash_aset(e, ID2SYM(rb_intern("orig_argc")), INT2FIX(ci->orig_argc));
rb_hash_aset(e, ID2SYM(rb_intern("blockptr")), ci->blockiseq ? iseq_data_to_ary(ci->blockiseq) : Qnil);
rb_ary_push(ary, e);
}
break;
case TS_ID:
rb_ary_push(ary, ID2SYM(*seq));
break;
case TS_CDHASH:
{
VALUE hash = *seq;
VALUE val = rb_ary_new();
int i;
rb_hash_foreach(hash, cdhash_each, val);
for (i=0; i<RARRAY_LEN(val); i+=2) {
VALUE pos = FIX2INT(rb_ary_entry(val, i+1));
unsigned long idx = nseq - iseq->iseq + pos;
rb_ary_store(val, i+1,
register_label(labels_table, idx));
}
rb_ary_push(ary, val);
}
break;
default:
rb_bug("unknown operand: %c", insn_op_type(insn, j));
}
}
rb_ary_push(body, ary);
}
nbody = body;
/* exception */
for (i=0; i<iseq->catch_table_size; i++) {
VALUE ary = rb_ary_new();
struct iseq_catch_table_entry *entry = &iseq->catch_table[i];
rb_ary_push(ary, exception_type2symbol(entry->type));
if (entry->iseq) {
rb_iseq_t *eiseq;
GetISeqPtr(entry->iseq, eiseq);
rb_ary_push(ary, iseq_data_to_ary(eiseq));
}
else {
rb_ary_push(ary, Qnil);
}
rb_ary_push(ary, register_label(labels_table, entry->start));
rb_ary_push(ary, register_label(labels_table, entry->end));
rb_ary_push(ary, register_label(labels_table, entry->cont));
rb_ary_push(ary, INT2FIX(entry->sp));
rb_ary_push(exception, ary);
}
/* make body with labels and insert line number */
body = rb_ary_new();
ti = 0;
for (i=0, pos=0; i<RARRAY_LEN(nbody); i++) {
VALUE ary = RARRAY_AREF(nbody, i);
st_data_t label;
if (st_lookup(labels_table, pos, &label)) {
rb_ary_push(body, (VALUE)label);
}
if (ti < iseq->line_info_size && iseq->line_info_table[ti].position == pos) {
line = iseq->line_info_table[ti].line_no;
rb_ary_push(body, INT2FIX(line));
ti++;
}
rb_ary_push(body, ary);
pos += RARRAY_LENINT(ary); /* reject too huge data */
}
st_free_table(labels_table);
rb_hash_aset(misc, ID2SYM(rb_intern("arg_size")), INT2FIX(iseq->arg_size));
rb_hash_aset(misc, ID2SYM(rb_intern("local_size")), INT2FIX(iseq->local_size));
rb_hash_aset(misc, ID2SYM(rb_intern("stack_max")), INT2FIX(iseq->stack_max));
/* TODO: compatibility issue */
/*
* [:magic, :major_version, :minor_version, :format_type, :misc,
* :name, :path, :absolute_path, :start_lineno, :type, :locals, :args,
* :catch_table, :bytecode]
*/
rb_ary_push(val, rb_str_new2("YARVInstructionSequence/SimpleDataFormat"));
rb_ary_push(val, INT2FIX(ISEQ_MAJOR_VERSION)); /* major */
rb_ary_push(val, INT2FIX(ISEQ_MINOR_VERSION)); /* minor */
rb_ary_push(val, INT2FIX(1));
rb_ary_push(val, misc);
rb_ary_push(val, iseq->location.label);
rb_ary_push(val, iseq->location.path);
rb_ary_push(val, iseq->location.absolute_path);
rb_ary_push(val, iseq->location.first_lineno);
rb_ary_push(val, type);
rb_ary_push(val, locals);
rb_ary_push(val, args);
rb_ary_push(val, exception);
rb_ary_push(val, body);
return val;
}
VALUE
rb_iseq_clone(VALUE iseqval, VALUE newcbase)
{
VALUE newiseq = iseq_alloc(rb_cISeq);
rb_iseq_t *iseq0, *iseq1;
GetISeqPtr(iseqval, iseq0);
GetISeqPtr(newiseq, iseq1);
MEMCPY(iseq1, iseq0, rb_iseq_t, 1); /* TODO: write barrier? */
iseq1->self = newiseq;
if (!iseq1->orig) {
RB_OBJ_WRITE(iseq1->self, &iseq1->orig, iseqval);
}
if (iseq0->local_iseq == iseq0) {
iseq1->local_iseq = iseq1;
}
if (newcbase) {
ISEQ_SET_CREF(iseq1, NEW_CREF(newcbase));
RB_OBJ_WRITE(iseq1->cref_stack, &iseq1->cref_stack->nd_refinements, iseq0->cref_stack->nd_refinements);
iseq1->cref_stack->nd_visi = iseq0->cref_stack->nd_visi;
if (iseq0->cref_stack->nd_next) {
RB_OBJ_WRITE(iseq1->cref_stack, &iseq1->cref_stack->nd_next, iseq0->cref_stack->nd_next);
}
RB_OBJ_WRITE(iseq1->self, &iseq1->klass, newcbase);
}
return newiseq;
}
VALUE
rb_iseq_parameters(const rb_iseq_t *iseq, int is_proc)
{
int i, r;
VALUE a, args = rb_ary_new2(iseq->arg_size);
ID req, opt, rest, block, key, keyrest;
#define PARAM_TYPE(type) rb_ary_push(a = rb_ary_new2(2), ID2SYM(type))
#define PARAM_ID(i) iseq->local_table[(i)]
#define PARAM(i, type) ( \
PARAM_TYPE(type), \
rb_id2str(PARAM_ID(i)) ? \
rb_ary_push(a, ID2SYM(PARAM_ID(i))) : \
a)
CONST_ID(req, "req");
CONST_ID(opt, "opt");
if (is_proc) {
for (i = 0; i < iseq->argc; i++) {
PARAM_TYPE(opt);
rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil);
rb_ary_push(args, a);
}
}
else {
for (i = 0; i < iseq->argc; i++) {
rb_ary_push(args, PARAM(i, req));
}
}
r = iseq->argc + iseq->arg_opts - 1;
for (; i < r; i++) {
PARAM_TYPE(opt);
if (rb_id2str(PARAM_ID(i))) {
rb_ary_push(a, ID2SYM(PARAM_ID(i)));
}
rb_ary_push(args, a);
}
if (iseq->arg_rest != -1) {
CONST_ID(rest, "rest");
rb_ary_push(args, PARAM(iseq->arg_rest, rest));
}
r = iseq->arg_post_start + iseq->arg_post_len;
if (is_proc) {
for (i = iseq->arg_post_start; i < r; i++) {
PARAM_TYPE(opt);
rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil);
rb_ary_push(args, a);
}
}
else {
for (i = iseq->arg_post_start; i < r; i++) {
rb_ary_push(args, PARAM(i, req));
}
}
if (iseq->arg_keyword != -1) {
i = 0;
if (iseq->arg_keyword_required) {
ID keyreq;
CONST_ID(keyreq, "keyreq");
for (; i < iseq->arg_keyword_required; i++) {
PARAM_TYPE(keyreq);
if (rb_id2str(iseq->arg_keyword_table[i])) {
rb_ary_push(a, ID2SYM(iseq->arg_keyword_table[i]));
}
rb_ary_push(args, a);
}
}
CONST_ID(key, "key");
for (; i < iseq->arg_keywords; i++) {
PARAM_TYPE(key);
if (rb_id2str(iseq->arg_keyword_table[i])) {
rb_ary_push(a, ID2SYM(iseq->arg_keyword_table[i]));
}
rb_ary_push(args, a);
}
if (!iseq->arg_keyword_check) {
CONST_ID(keyrest, "keyrest");
rb_ary_push(args, PARAM(iseq->arg_keyword, keyrest));
}
}
if (iseq->arg_block != -1) {
CONST_ID(block, "block");
rb_ary_push(args, PARAM(iseq->arg_block, block));
}
return args;
}
VALUE
rb_iseq_defined_string(enum defined_type type)
{
static const char expr_names[][18] = {
"nil",
"instance-variable",
"local-variable",
"global-variable",
"class variable",
"constant",
"method",
"yield",
"super",
"self",
"true",
"false",
"assignment",
"expression",
};
const char *estr;
VALUE *defs, str;
if ((unsigned)(type - 1) >= (unsigned)numberof(expr_names)) return 0;
estr = expr_names[type - 1];
if (!estr[0]) return 0;
defs = GET_VM()->defined_strings;
if (!defs) {
defs = ruby_xcalloc(numberof(expr_names), sizeof(VALUE));
GET_VM()->defined_strings = defs;
}
str = defs[type-1];
if (!str) {
str = rb_str_new_cstr(estr);;
OBJ_FREEZE(str);
defs[type-1] = str;
}
return str;
}
/* ruby2cext */
VALUE
rb_iseq_build_for_ruby2cext(
const rb_iseq_t *iseq_template,
const rb_insn_func_t *func,
const struct iseq_line_info_entry *line_info_table,
const char **local_table,
const VALUE *arg_opt_table,
const struct iseq_catch_table_entry *catch_table,
const char *name,
const char *path,
const unsigned short first_lineno)
{
unsigned long i;
VALUE iseqval = iseq_alloc(rb_cISeq);
rb_iseq_t *iseq;
GetISeqPtr(iseqval, iseq);
/* copy iseq */
MEMCPY(iseq, iseq_template, rb_iseq_t, 1); /* TODO: write barrier, *iseq = *iseq_template; */
RB_OBJ_WRITE(iseq->self, &iseq->location.label, rb_str_new2(name));
RB_OBJ_WRITE(iseq->self, &iseq->location.path, rb_str_new2(path));
iseq->location.first_lineno = first_lineno;
RB_OBJ_WRITE(iseq->self, &iseq->mark_ary, 0);
iseq->self = iseqval;
iseq->iseq = ALLOC_N(VALUE, iseq->iseq_size);
for (i=0; i<iseq->iseq_size; i+=2) {
iseq->iseq[i] = BIN(opt_call_c_function);
iseq->iseq[i+1] = (VALUE)func;
}
rb_iseq_translate_threaded_code(iseq);
#define ALLOC_AND_COPY(dst, src, type, size) do { \
if (size) { \
(dst) = ALLOC_N(type, (size)); \
MEMCPY((dst), (src), type, (size)); \
} \
} while (0)
ALLOC_AND_COPY(iseq->line_info_table, line_info_table,
struct iseq_line_info_entry, iseq->line_info_size);
ALLOC_AND_COPY(iseq->catch_table, catch_table,
struct iseq_catch_table_entry, iseq->catch_table_size);
ALLOC_AND_COPY(iseq->arg_opt_table, arg_opt_table,
VALUE, iseq->arg_opts);
set_relation(iseq, 0);
return iseqval;
}
/* Experimental tracing support: trace(line) -> trace(specified_line)
* MRI Specific.
*/
int
rb_iseq_line_trace_each(VALUE iseqval, int (*func)(int line, rb_event_flag_t *events_ptr, void *d), void *data)
{
int trace_num = 0;
size_t pos, insn;
rb_iseq_t *iseq;
int cont = 1;
GetISeqPtr(iseqval, iseq);
for (pos = 0; cont && pos < iseq->iseq_size; pos += insn_len(insn)) {
insn = iseq->iseq[pos];
if (insn == BIN(trace)) {
rb_event_flag_t current_events = (VALUE)iseq->iseq[pos+1];
if (current_events & RUBY_EVENT_LINE) {
rb_event_flag_t events = current_events & RUBY_EVENT_SPECIFIED_LINE;
trace_num++;
if (func) {
int line = find_line_no(iseq, pos);
/* printf("line: %d\n", line); */
cont = (*func)(line, &events, data);
if (current_events != events) {
iseq->iseq[pos+1] = iseq->iseq_encoded[pos+1] =
(VALUE)(current_events | (events & RUBY_EVENT_SPECIFIED_LINE));
}
}
}
}
}
return trace_num;
}
static int
collect_trace(int line, rb_event_flag_t *events_ptr, void *ptr)
{
VALUE result = (VALUE)ptr;
rb_ary_push(result, INT2NUM(line));
return 1;
}
/*
* <b>Experimental MRI specific feature, only available as C level api.</b>
*
* Returns all +specified_line+ events.
*/
VALUE
rb_iseq_line_trace_all(VALUE iseqval)
{
VALUE result = rb_ary_new();
rb_iseq_line_trace_each(iseqval, collect_trace, (void *)result);
return result;
}
struct set_specifc_data {
int pos;
int set;
int prev; /* 1: set, 2: unset, 0: not found */
};
static int
line_trace_specify(int line, rb_event_flag_t *events_ptr, void *ptr)
{
struct set_specifc_data *data = (struct set_specifc_data *)ptr;
if (data->pos == 0) {
data->prev = *events_ptr & RUBY_EVENT_SPECIFIED_LINE ? 1 : 2;
if (data->set) {
*events_ptr = *events_ptr | RUBY_EVENT_SPECIFIED_LINE;
}
else {
*events_ptr = *events_ptr & ~RUBY_EVENT_SPECIFIED_LINE;
}
return 0; /* found */
}
else {
data->pos--;
return 1;
}
}
/*
* <b>Experimental MRI specific feature, only available as C level api.</b>
*
* Set a +specified_line+ event at the given line position, if the +set+
* parameter is +true+.
*
* This method is useful for building a debugger breakpoint at a specific line.
*
* A TypeError is raised if +set+ is not boolean.
*
* If +pos+ is a negative integer a TypeError exception is raised.
*/
VALUE
rb_iseq_line_trace_specify(VALUE iseqval, VALUE pos, VALUE set)
{
struct set_specifc_data data;
data.prev = 0;
data.pos = NUM2INT(pos);
if (data.pos < 0) rb_raise(rb_eTypeError, "`pos' is negative");
switch (set) {
case Qtrue: data.set = 1; break;
case Qfalse: data.set = 0; break;
default:
rb_raise(rb_eTypeError, "`set' should be true/false");
}
rb_iseq_line_trace_each(iseqval, line_trace_specify, (void *)&data);
if (data.prev == 0) {
rb_raise(rb_eTypeError, "`pos' is out of range.");
}
return data.prev == 1 ? Qtrue : Qfalse;
}
/*
* Document-class: RubyVM::InstructionSequence
*
* The InstructionSequence class represents a compiled sequence of
* instructions for the Ruby Virtual Machine.
*
* With it, you can get a handle to the instructions that make up a method or
* a proc, compile strings of Ruby code down to VM instructions, and
* disassemble instruction sequences to strings for easy inspection. It is
* mostly useful if you want to learn how the Ruby VM works, but it also lets
* you control various settings for the Ruby iseq compiler.
*
* You can find the source for the VM instructions in +insns.def+ in the Ruby
* source.
*
* The instruction sequence results will almost certainly change as Ruby
* changes, so example output in this documentation may be different from what
* you see.
*/
void
Init_ISeq(void)
{
/* declare ::RubyVM::InstructionSequence */
rb_cISeq = rb_define_class_under(rb_cRubyVM, "InstructionSequence", rb_cObject);
rb_define_alloc_func(rb_cISeq, iseq_alloc);
rb_define_method(rb_cISeq, "inspect", iseq_inspect, 0);
rb_define_method(rb_cISeq, "disasm", rb_iseq_disasm, 0);
rb_define_method(rb_cISeq, "disassemble", rb_iseq_disasm, 0);
rb_define_method(rb_cISeq, "to_a", iseq_to_a, 0);
rb_define_method(rb_cISeq, "eval", iseq_eval, 0);
/* location APIs */
rb_define_method(rb_cISeq, "path", rb_iseq_path, 0);
rb_define_method(rb_cISeq, "absolute_path", rb_iseq_absolute_path, 0);
rb_define_method(rb_cISeq, "label", rb_iseq_label, 0);
rb_define_method(rb_cISeq, "base_label", rb_iseq_base_label, 0);
rb_define_method(rb_cISeq, "first_lineno", rb_iseq_first_lineno, 0);
#if 0
/* Now, it is experimental. No discussions, no tests. */
/* They can be used from C level. Please give us feedback. */
rb_define_method(rb_cISeq, "line_trace_all", rb_iseq_line_trace_all, 0);
rb_define_method(rb_cISeq, "line_trace_specify", rb_iseq_line_trace_specify, 2);
#else
(void)rb_iseq_line_trace_all;
(void)rb_iseq_line_trace_specify;
#endif
#if 0 /* TBD */
rb_define_private_method(rb_cISeq, "marshal_dump", iseq_marshal_dump, 0);
rb_define_private_method(rb_cISeq, "marshal_load", iseq_marshal_load, 1);
#endif
/* disable this feature because there is no verifier. */
/* rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1); */
(void)iseq_s_load;
rb_define_singleton_method(rb_cISeq, "compile", iseq_s_compile, -1);
rb_define_singleton_method(rb_cISeq, "new", iseq_s_compile, -1);
rb_define_singleton_method(rb_cISeq, "compile_file", iseq_s_compile_file, -1);
rb_define_singleton_method(rb_cISeq, "compile_option", iseq_s_compile_option_get, 0);
rb_define_singleton_method(rb_cISeq, "compile_option=", iseq_s_compile_option_set, 1);
rb_define_singleton_method(rb_cISeq, "disasm", iseq_s_disasm, 1);
rb_define_singleton_method(rb_cISeq, "disassemble", iseq_s_disasm, 1);
rb_define_singleton_method(rb_cISeq, "of", iseq_s_of, 1);
}
| 27.543263 | 118 | 0.650251 | [
"object"
] |
b708e70b90c374c326ecb219364bbaaa12fb5257 | 10,040 | h | C | services/bluetooth_standard/service/src/util/xml_parse.h | openharmony-sig-ci/communication_bluetooth | c9d9614e881224abfb423505e25e72163dd25df3 | [
"Apache-2.0"
] | null | null | null | services/bluetooth_standard/service/src/util/xml_parse.h | openharmony-sig-ci/communication_bluetooth | c9d9614e881224abfb423505e25e72163dd25df3 | [
"Apache-2.0"
] | null | null | null | services/bluetooth_standard/service/src/util/xml_parse.h | openharmony-sig-ci/communication_bluetooth | c9d9614e881224abfb423505e25e72163dd25df3 | [
"Apache-2.0"
] | 1 | 2021-09-13T11:16:33.000Z | 2021-09-13T11:16:33.000Z | /*
* Copyright (C) 2021 Huawei Device Co., 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 XML_PARSE_H
#define XML_PARSE_H
#include <map>
#include <string>
#include <vector>
#include "base_def.h"
namespace utility {
#define SIZEOF_0X 2
#define BASE_16 16
class XmlParse {
public:
/**
* @brief Construct a new Xml Parse object
*
* @since 6
*/
XmlParse();
/**
* @brief Destroy the Xml Parse object
*
* @since 6
*/
~XmlParse();
/**
* @brief Load XML document form file.
*
* @param path File path.
* @return Success load xml document return true, else return false.
* @since 6
*/
bool Load(const std::string &path);
/**
* @brief Parse XML document.
*
* @return Success parse XML document return true, else return false.
* @since 6
*/
bool Parse();
/**
* @brief Store back to XML document.
*
* @return Success store back to XML document return true, else return false.
* @since 6
*/
bool Save();
/**
* @brief Get specified property value.
* Value type is int.
*
* @param section Xml section.
* @param subSection Xml subSection.
* @param property Xml property.
* @param value Value type is int.
* @return Success get specified property's value return true, else return false.
* @since 6
*/
bool GetValue(const std::string §ion, const std::string &subSection, const std::string &property, int &value);
/**
* @brief Get specified property value.
* Value type is string.
*
* @param section Xml section.
* @param subSection Xml subSection.
* @param property Xml property.
* @param value Value type is string.
* @return Success get specified property's value return true, else return false.
* @since 6
*/
bool GetValue(
const std::string §ion, const std::string &subSection, const std::string &property, std::string &value);
/**
* @brief Get specified property value.
* Value type is bool.
*
* @param section Xml section.
* @param subSection Xml subSection.
* @param property Xml property.
* @param value Value type is bool.
* @return Success get specified property's value return true, else return false.
* @since 6
*/
bool GetValue(const std::string §ion, const std::string &subSection, const std::string &property, bool &value);
/**
* @brief Set specified property value.
* Value type is int.
*
* @param section Xml section.
* @param subSection Xml subSection.
* @param property Xml property.
* @param value Value type is const int.
* @return Success set specified property's value return true, else return false.
* @since 6
*/
bool SetValue(
const std::string §ion, const std::string &subSection, const std::string &property, const int &value);
/**
* @brief Set specified property value. Value type is string.
*
* @param section Xml section.
* @param subSection Xml subSection.
* @param property Xml property.
* @param value Value type is const string.
* @return Success set specified property's value return true, else return false.
* @since 6
*/
bool SetValue(const std::string §ion, const std::string &subSection, const std::string &property,
const std::string &value);
/**
* @brief Set specified property value. Value type is bool.
*
* @param section Xml section.
* @param subSection Xml subSection.
* @param property Xml property.
* @param value Value type is const bool.
* @return Success set specified property's value return true, else return false.
* @since 6
*/
bool SetValue(
const std::string §ion, const std::string &subSection, const std::string &property, const bool &value);
/**
* @brief Whether XML document has specified section.
*
* @param section Xml section.
* @param subSection Xml subSection.
* @return XML document has specified section return true, else return false.
* @since 6
*/
bool HasSection(const std::string §ion, const std::string &subSection);
/**
* @brief Get Address
* @param section Xml section.
* @param subSections
* @return Specified section has one or Mutiple subSections return true, else return false.
* @since 6
*/
bool GetSubSections(const std::string §ion, std::vector<std::string> &subSections);
/**
* @brief Whether XML document has specified property.
*
* @param section Xml section.
* @param subSection
* @param property
* @return XML document has specified property return true, else return false.
* @since 6
*/
bool HasProperty(const std::string §ion, const std::string &subSection, const std::string &property);
/**
* @brief Remove XML document specified section.
*
* @param section Xml section.
* @param subSection Xml subSection.
* @return Success remove XML document specified section return true, else return false.
* @since 6
*/
bool RemoveSection(const std::string §ion, const std::string &subSection);
/**
* @brief Remove XML document specified property.
*
* @param section Xml section.
* @param subSection Xml subSection.
* @param property Xml property.
* @return Success remove XML document specified property return true, else return false.
* @since 6
*/
bool RemoveProperty(const std::string §ion, const std::string &subSection, const std::string &property);
/**
* @brief Get specified property value.
* Value type is int.
*
* @param section Xml section.
* @param property Xml property.
* @param value Value type is int.
* @return Success get specified property's value return true, else return false.
* @since 6
*/
bool GetValue(const std::string §ion, const std::string &property, int &value);
/**
* @brief Get specified property value.
* Value type is string.
* @param section Xml section.
* @param property Xml property.
* @param value Value type is string.
* @return Success get specified property's value return true, else return false.
* @since 6
*/
bool GetValue(const std::string §ion, const std::string &property, std::string &value);
/**
* @brief Get specified property value.
* Value type is bool.
* @param section Xml section.
* @param property Xml property.
* @param value Value type is bool.
* @return Success get specified property's value return true, else return false.
* @since 6
*/
bool GetValue(const std::string §ion, const std::string &property, bool &value);
/**
* @brief Set specified property value.
* Value type is int.
*
* @param section Xml section.
* @param property Xml property.
* @param value Value type is const int.
* @return Success set specified property's value return true, else return false.
* @since 6
*/
bool SetValue(const std::string §ion, const std::string &property, const int &value);
/**
* @brief Set specified property value.
* Value type is string.
*
* @param section Xml section.
* @param property Xml property.
* @param value Value type is const string.
* @return Success set specified property's value return true, else return false.
* @since 6
*/
bool SetValue(const std::string §ion, const std::string &property, const std::string &value);
/**
* @brief Set specified property value.
* Value type is bool.
* @param section Xml section.
* @param property Xml property.
* @param value Value type is const bool.
* @return Success set specified property's value return true, else return false.
* @since 6
*/
bool SetValue(const std::string §ion, const std::string &property, const bool &value);
/**
* @brief Whether XML document has specified section.
*
* @param section Xml section.
* @return XML document has specified section return true, else return false.
* @since 6
*/
bool HasSection(const std::string §ion);
/**
* @brief Whether XML document has specified property.
*
* @param section Xml section.
* @param property
* @return XML document has specified property return true, else return false
* @since 6
*/
bool HasProperty(const std::string §ion, const std::string &property);
/**
* @brief Remove XML document specified section.
* @param section Xml section.
* @return Success remove XML document specified section return true, else return false.
* @since 6
*/
bool RemoveSection(const std::string §ion);
/**
* @brief Remove XML document specified property.
* @param section Xml section.
* @param property Xml property.
* @return Success remove XML document specified property return true, else return false.
* @since 6
*/
bool RemoveProperty(const std::string §ion, const std::string &property);
private:
std::string filePath_ {""};
DECLARE_IMPL();
};
}; // namespace utility
#endif // XML_PARSE_H | 32.282958 | 119 | 0.638147 | [
"object",
"vector"
] |
b7113f71276cf2737e16da66aa992cb8ad362d61 | 8,141 | h | C | cpp/Declaration.h | acw1251/bsvtokami | 41008ae979039d906969331d058f275125548826 | [
"MIT"
] | null | null | null | cpp/Declaration.h | acw1251/bsvtokami | 41008ae979039d906969331d058f275125548826 | [
"MIT"
] | null | null | null | cpp/Declaration.h | acw1251/bsvtokami | 41008ae979039d906969331d058f275125548826 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <map>
#include <memory>
#include "BSVType.h"
#include "SourcePos.h"
using namespace std;
class Declaration;
class EnumDeclaration;
class EnumElementDeclaration;
class FunctionDefinition;
class InterfaceDeclaration;
class MethodDeclaration;
class MethodDefinition;
class ModuleDefinition;
class StructDeclaration;
class UnionDeclaration;
class TypeSynonymDeclaration;
enum BindingType {
GlobalBindingType,
ModuleParamBindingType,
MethodParamBindingType,
LocalBindingType
};
class DeclarationVisitor {
public:
// called for all declarations
virtual void visitDeclaration(const shared_ptr<Declaration> &declaration) {}
virtual void visitEnumDeclaration(const shared_ptr<EnumDeclaration> &decl) {}
virtual void visitFunctionDefinition(const shared_ptr<FunctionDefinition> &decl) {}
virtual void visitInterfaceDeclaration(const shared_ptr<InterfaceDeclaration> &decl) {}
virtual void visitMethodDefinition(const shared_ptr<MethodDefinition> &decl) {}
virtual void visitMethodDeclaration(const shared_ptr<MethodDeclaration> &decl) {}
virtual void visitModuleDefinition(const shared_ptr<ModuleDefinition> &decl) {}
virtual void visitStructDeclaration(const shared_ptr<StructDeclaration> &decl) {}
virtual void visitTypeSynonymDeclaration(const shared_ptr<TypeSynonymDeclaration> &decl) {}
virtual void visitUnionDeclaration(const shared_ptr<UnionDeclaration> &decl) {}
};
class Declaration : public enable_shared_from_this<Declaration> {
public:
const std::string package;
const std::string name;
const std::string uniqueName;
const std::shared_ptr<BSVType> bsvtype;
const BindingType bindingType;
shared_ptr<Declaration> parent;
const SourcePos sourcePos;
Declaration(const std::string &name, std::shared_ptr<BSVType> bsvtype)
: package(), name(name), uniqueName(genUniqueName(string(), name, LocalBindingType)), bsvtype(bsvtype), bindingType(LocalBindingType) {
if (bsvtype) {
for (int i = 0; i < bsvtype->params.size(); i++) {
numericTypeParamVector.push_back(bsvtype->params[i]->isNumeric());
}
}
};
Declaration(const std::string &package, const std::string &name, std::shared_ptr<BSVType> bsvtype, const BindingType bt = LocalBindingType, SourcePos sourcePos = SourcePos())
: package(package), name(name), uniqueName(genUniqueName(package, name, bt)), bsvtype(bsvtype), bindingType(bt), sourcePos(sourcePos) {
if (bsvtype) {
for (int i = 0; i < bsvtype->params.size(); i++) {
numericTypeParamVector.push_back(bsvtype->params[i]->isNumeric());
}
}
};
virtual shared_ptr<EnumDeclaration> enumDeclaration() { return shared_ptr<EnumDeclaration>(); }
virtual shared_ptr<FunctionDefinition> functionDefinition() { return shared_ptr<FunctionDefinition>(); }
virtual shared_ptr<InterfaceDeclaration> interfaceDeclaration() { return shared_ptr<InterfaceDeclaration>(); }
virtual shared_ptr<ModuleDefinition> moduleDefinition() { return shared_ptr<ModuleDefinition>(); }
virtual shared_ptr<MethodDefinition> methodDefinition() { return shared_ptr<MethodDefinition>(); }
virtual shared_ptr<MethodDeclaration> methodDeclaration() { return shared_ptr<MethodDeclaration>(); }
virtual shared_ptr<StructDeclaration> structDeclaration() { return shared_ptr<StructDeclaration>(); }
virtual shared_ptr<TypeSynonymDeclaration> typeSynonymDeclaration() { return shared_ptr<TypeSynonymDeclaration>(); }
virtual shared_ptr<UnionDeclaration> unionDeclaration() { return shared_ptr<UnionDeclaration>(); }
const vector<bool> numericTypeParams() {
return numericTypeParamVector;
}
virtual ~Declaration() {}
private:
vector<bool> numericTypeParamVector;
static string genUniqueName(const string &package, const string &name, BindingType bt);
};
class EnumDeclaration : public Declaration {
public:
std::vector<std::shared_ptr<Declaration> > members;
EnumDeclaration(const std::string &package, const std::string &name, std::shared_ptr<BSVType> bsvtype, SourcePos sourcePos)
: Declaration(package, name, bsvtype, GlobalBindingType, sourcePos) {};
shared_ptr<EnumDeclaration> enumDeclaration() override { return static_pointer_cast<EnumDeclaration, Declaration>(shared_from_this()); }
};
class FunctionDefinition : public Declaration {
public:
FunctionDefinition(const std::string &package, const std::string &name, std::shared_ptr<BSVType> bsvtype, const BindingType bt, SourcePos sourcePos)
: Declaration(package, name, bsvtype, bt, sourcePos) {};
shared_ptr<FunctionDefinition> functionDefinition() override { return static_pointer_cast<FunctionDefinition, Declaration>(shared_from_this()); }
};
class InterfaceDeclaration : public Declaration {
public:
std::vector<std::shared_ptr<Declaration> > members;
InterfaceDeclaration(const std::string &package, const std::string &name, std::shared_ptr<BSVType> bsvtype, SourcePos sourcePos)
: Declaration(package, name, bsvtype, GlobalBindingType, sourcePos) {};
shared_ptr<InterfaceDeclaration> interfaceDeclaration() override { return static_pointer_cast<InterfaceDeclaration, Declaration>(shared_from_this()); }
shared_ptr<Declaration> lookupMember(const string &memberName);
};
class MethodDeclaration : public Declaration {
public:
MethodDeclaration(const std::string &package, const std::string &name, std::shared_ptr<BSVType> bsvtype, SourcePos sourcePos)
: Declaration(package, name, bsvtype, LocalBindingType, sourcePos) {};
shared_ptr<MethodDeclaration>
methodDeclaration() override { return static_pointer_cast<MethodDeclaration, Declaration>(shared_from_this()); }
};
class MethodDefinition : public Declaration {
public:
MethodDefinition(const std::string &name, std::shared_ptr<BSVType> bsvtype, SourcePos sourcePos)
: Declaration(string(), name, bsvtype, LocalBindingType, sourcePos) {};
shared_ptr<MethodDefinition> methodDefinition() override { return static_pointer_cast<MethodDefinition, Declaration>(shared_from_this()); }
};
class ModuleDefinition : public Declaration {
public:
ModuleDefinition(const std::string &package, const std::string &name, std::shared_ptr<BSVType> bsvtype, SourcePos sourcePos)
: Declaration(package, name, bsvtype, GlobalBindingType, sourcePos) {};
shared_ptr<ModuleDefinition> moduleDefinition() override { return static_pointer_cast<ModuleDefinition, Declaration>(shared_from_this()); }
};
class StructDeclaration : public Declaration {
public:
std::vector<std::shared_ptr<Declaration> > members;
StructDeclaration(const std::string &package, const std::string &name, std::shared_ptr<BSVType> bsvtype, SourcePos sourcePos)
: Declaration(package, name, bsvtype, GlobalBindingType, sourcePos) {};
shared_ptr<StructDeclaration> structDeclaration() override { return static_pointer_cast<StructDeclaration, Declaration>(shared_from_this()); }
};
class TypeSynonymDeclaration : public Declaration {
public:
const shared_ptr<BSVType> lhstype;
public:
TypeSynonymDeclaration(const std::string &package, const std::string &name, std::shared_ptr<BSVType> lhstype, std::shared_ptr<BSVType> bsvtype, SourcePos sourcePos)
: Declaration(package, name, bsvtype, GlobalBindingType, sourcePos), lhstype(lhstype) {};
shared_ptr<TypeSynonymDeclaration> typeSynonymDeclaration() override { return static_pointer_cast<TypeSynonymDeclaration, Declaration>(shared_from_this()); }
};
class UnionDeclaration : public Declaration {
public:
std::vector<std::shared_ptr<Declaration> > members;
UnionDeclaration(std::string name, std::shared_ptr<BSVType> bsvtype, SourcePos sourcePos)
: Declaration(package, name, bsvtype, GlobalBindingType, sourcePos) {};
shared_ptr<UnionDeclaration> unionDeclaration() override { return static_pointer_cast<UnionDeclaration, Declaration>(shared_from_this()); }
shared_ptr<Declaration> lookupMember(const string &memberName);
}; | 44.005405 | 178 | 0.757278 | [
"vector"
] |
b717df76840a0196cb1893e94c79a0e539fdd6ad | 8,488 | h | C | EnvironmentModule/EnvironmentModule.h | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | null | null | null | EnvironmentModule/EnvironmentModule.h | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | null | null | null | EnvironmentModule/EnvironmentModule.h | zemo/naali | a02ee7a0547c5233579eda85dedb934b61c546ab | [
"Apache-2.0"
] | 1 | 2021-09-04T12:37:34.000Z | 2021-09-04T12:37:34.000Z | /**
* For conditions of distribution and use, see copyright notice in license.txt
* @file EnvironmentModule.h
* @brief Environment module. Environment module is be responsible for visual environment features like terrain, sky & water.
*/
#ifndef incl_EnvironmentModule_EnvironmentModule_h
#define incl_EnvironmentModule_EnvironmentModule_h
#include "EnvironmentModuleApi.h"
#include "IModule.h"
#include "ModuleLoggingFunctions.h"
#include "WorldStream.h"
#ifdef CAELUM
namespace Caelum
{
class CaelumSystem;
}
#endif
namespace Environment
{
class Terrain;
class Water;
class Environment;
class Sky;
class EnvironmentEditor;
class PostProcessWidget;
class TerrainWeightEditor;
typedef boost::shared_ptr<Terrain> TerrainPtr;
typedef boost::shared_ptr<Water> WaterPtr;
typedef boost::shared_ptr<Sky> SkyPtr;
typedef boost::shared_ptr<Environment> EnvironmentPtr;
//! Environment Module.
/*! \defgroup EnvironmentModuleClient EnvironmentModule Client interface.
Inteface for environment module. Environment module implements terrain, sky and water generation.
Also module will handle all environment editing via EnvironmentEditor. Module receives network
messages and send them forward to other components that will need them.
*/
class ENVIRONMENT_MODULE_API EnvironmentModule : public IModule
{
public:
//! Constructor.
EnvironmentModule();
//! Destructor
virtual ~EnvironmentModule();
void Load();
void Initialize();
void PostInitialize();
void Uninitialize();
void Update(f64 frametime);
bool HandleEvent(event_category_id_t category_id, event_id_t event_id, IEventData* data);
//! Handles resouce event category.
//! @param event_id event id
//! @param data event data pointer
//! @return Should return true if the event was handled and is not to be propagated further
bool HandleResouceEvent(event_id_t event_id, IEventData* data);
//! Handles framework event category.
//! @param event_id event id
//! @param data event data pointer
//! @return Should return true if the event was handled and is not to be propagated further
bool HandleFrameworkEvent(event_id_t event_id, IEventData* data);
//! Handles resouce event category.
//! @param event_id event id
//! @param data event data pointer
//! @return Should return true if the event was handled and is not to be propagated further
bool HandleNetworkEvent(event_id_t event_id, IEventData* data);
//! Handles input event category.
//! @param event_id event id
//! @param data event data pointer
//! @return Should return true if the event was handled and is not to be propagated further
bool HandleInputEvent(event_id_t event_id, IEventData* data);
//! Get terrain texture ids, terrain height and water height values.
//! @param network data pointer.
//! @return Should return true if the event was handled and is not to be propagated further
bool HandleOSNE_RegionHandshake(ProtocolUtilities::NetworkEventInboundData* data);
//! @return The terrain handler object that manages reX terrain logic.
TerrainPtr GetTerrainHandler() const;
//! @return The environment handler.
EnvironmentPtr GetEnvironmentHandler() const;
//! @return The sky handler.
SkyPtr GetSkyHandler() const;
//! @return The water handler.
WaterPtr GetWaterHandler() const;
//! Sends new terrain texture into the server.
//! @param new_texture_id texture asset id that we want to use.
//! @param texture_index switch texture we want to change range [0 - 3].
void SendTextureDetailMessage(const RexTypes::RexAssetID &new_texture_id, uint texture_index);
//! Change new terrain height value,
//! @Param start_height what height texture starts at (meters).
//! @Param height_range how many meters texture will go up from the texture_start_height
//! @Param corner what texture height we want to change.
//! @todo Seems like older OpenSim server (tested 0.6.5) won't inform all the users that terrain heights has been updated,
//! if needed add custom code that will Request a new ReqionInfo message from the server.
//! That message contain all the infomation releated to environment like terrain and water.
void SendTextureHeightMessage(float start_height, float height_range, uint corner);
/*! Sends modify land message into the server.
* @param x coordinate of terrain texture.
* @param y coordinate of terrain texture.
* @param brush brush size OpenSim supports following brush sizes (small = 0, medium = 1 and large = 2)
* @param action what terrain modification operation is used. OpenSim supports following actions:
* Flatten = 0, Raise = 1, Lower = 2, Smooth = 3, Roughen = 4 and Revert = 5)
* @param seconds how long has the modify land operation been executed.
* @param previous height value for spesific texture coordinate
*/
void SendModifyLandMessage(f32 x, f32 y, u8 brush, u8 action, float seconds, float height);
/**
* Creates a local enviroment entity. This is called if there does not exist outside enviroment entity (entity, which has EC_NAME component which attribute name is entity_name + Enviroment example WaterEnviroment).
* IF there exist a that kind entity it will be used to syncronize water, fog etc. things to other clients/server.
* @param entity_name is entity which exist in world.
* @param component_name is name of component which is added into local enviroment entity.
*/
Scene::EntityPtr CreateEnvironmentEntity(const QString& entity_name, const QString& component_name);
/**
* Removes local dump enviroment entity.
*/
void RemoveLocalEnvironment();
MODULE_LOGGING_FUNCTIONS
//! @return Returns name of this module. Needed for logging.
static const std::string &NameStatic() { return type_name_static_; }
#ifdef CAELUM
Caelum::CaelumSystem* GetCaelum();
#endif
private:
EnvironmentModule(const EnvironmentModule &);
void operator=(const EnvironmentModule &);
//! @return Returns type of this module. Needed for logging.
static std::string type_name_static_;
//! Create the terrain.
void CreateTerrain();
//! Create the water.
void CreateWater();
//! Create the environment.
void CreateEnvironment();
//! Create the sky
void CreateSky();
void ReleaseTerrain();
void ReleaseWater();
void ReleaseEnvironment();
void ReleaseSky();
//! Editor for terrain texture weights
TerrainWeightEditor* w_editor_;
//! Event manager pointer.
EventManagerPtr event_manager_;
//! Id for Framework event category
event_category_id_t framework_event_category_;
//! Id for Resource event category
event_category_id_t resource_event_category_;
//! Id for Scene event category
event_category_id_t scene_event_category_;
//! Id for NetworkIn event category
event_category_id_t network_in_event_category_;
//! Id for NetworkState event category
event_category_id_t network_state_event_category_;
//! Id for Input event category
event_category_id_t input_event_category_;
//! Terrain geometry ptr.
TerrainPtr terrain_;
//! Water ptr.
WaterPtr water_;
//! Environment ptr.
EnvironmentPtr environment_;
//! Sky ptr.
SkyPtr sky_;
//! Terrain editor pointer.
EnvironmentEditor *environment_editor_;
//! PostProcess dialog pointer
PostProcessWidget *postprocess_dialog_;
//! WorldStream will handle those network messages that we are wishing to send.
ProtocolUtilities::WorldStreamPtr currentWorldStream_;
//! Wait for new terrain heightmap information.
bool waiting_for_regioninfomessage_;
bool firstTime_;
};
}
#endif
| 37.39207 | 222 | 0.675895 | [
"geometry",
"object"
] |
b71b184073217b38497a9e8a8d123753bc44ebbb | 9,513 | c | C | sources/drivers/misc/mediatek/gpu/gpu_mali/mali_utgard/mali/mali/common/mali_gp_job.c | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | 2 | 2018-03-09T23:59:27.000Z | 2018-04-01T07:58:39.000Z | sources/drivers/misc/mediatek/gpu/gpu_mali/mali_utgard/mali/mali/common/mali_gp_job.c | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | null | null | null | sources/drivers/misc/mediatek/gpu/gpu_mali/mali_utgard/mali/mali/common/mali_gp_job.c | fuldaros/paperplane_kernel_wileyfox-spark | bea244880d2de50f4ad14bb6fa5777652232c033 | [
"Apache-2.0"
] | null | null | null | /*
* This confidential and proprietary software may be used only as
* authorised by a licensing agreement from ARM Limited
* (C) COPYRIGHT 2011-2016 ARM Limited
* ALL RIGHTS RESERVED
* The entire notice above must be reproduced on all authorised
* copies and copies may only be made to the extent permitted
* by a licensing agreement from ARM Limited.
*/
#include "mali_gp_job.h"
#include "mali_osk.h"
#include "mali_osk_list.h"
#include "mali_uk_types.h"
#include "mali_memory_virtual.h"
#include "mali_memory_defer_bind.h"
static u32 gp_counter_src0 = MALI_HW_CORE_NO_COUNTER; /**< Performance counter 0, MALI_HW_CORE_NO_COUNTER for disabled */
static u32 gp_counter_src1 = MALI_HW_CORE_NO_COUNTER; /**< Performance counter 1, MALI_HW_CORE_NO_COUNTER for disabled */
static void _mali_gp_del_varying_allocations(struct mali_gp_job *job);
static int _mali_gp_add_varying_allocations(struct mali_session_data *session,
struct mali_gp_job *job,
u32 *alloc,
u32 num)
{
int i = 0;
struct mali_gp_allocation_node *alloc_node;
mali_mem_allocation *mali_alloc = NULL;
struct mali_vma_node *mali_vma_node = NULL;
for (i = 0 ; i < num ; i++) {
MALI_DEBUG_ASSERT(alloc[i]);
alloc_node = _mali_osk_calloc(1, sizeof(struct mali_gp_allocation_node));
if (alloc_node) {
INIT_LIST_HEAD(&alloc_node->node);
/* find mali allocation structure by vaddress*/
mali_vma_node = mali_vma_offset_search(&session->allocation_mgr, alloc[i], 0);
if (likely(mali_vma_node)) {
mali_alloc = container_of(mali_vma_node, struct mali_mem_allocation, mali_vma_node);
MALI_DEBUG_ASSERT(alloc[i] == mali_vma_node->vm_node.start);
} else {
MALI_DEBUG_PRINT(1, ("ERROE!_mali_gp_add_varying_allocations,can't find allocation %d by address =0x%x, num=%d\n", i, alloc[i], num));
_mali_osk_free(alloc_node);
goto fail;
}
alloc_node->alloc = mali_alloc;
/* add to gp job varying alloc list*/
list_move(&alloc_node->node, &job->varying_alloc);
} else
goto fail;
}
return 0;
fail:
MALI_DEBUG_PRINT(1, ("ERROE!_mali_gp_add_varying_allocations,failed to alloc memory!\n"));
_mali_gp_del_varying_allocations(job);
return -1;
}
static void _mali_gp_del_varying_allocations(struct mali_gp_job *job)
{
struct mali_gp_allocation_node *alloc_node, *tmp_node;
list_for_each_entry_safe(alloc_node, tmp_node, &job->varying_alloc, node) {
list_del(&alloc_node->node);
kfree(alloc_node);
}
INIT_LIST_HEAD(&job->varying_alloc);
}
struct mali_gp_job *mali_gp_job_create(struct mali_session_data *session, _mali_uk_gp_start_job_s *uargs, u32 id, struct mali_timeline_tracker *pp_tracker)
{
struct mali_gp_job *job;
u32 perf_counter_flag;
u32 __user *memory_list = NULL;
struct mali_gp_allocation_node *alloc_node, *tmp_node;
job = _mali_osk_calloc(1, sizeof(struct mali_gp_job));
if (NULL != job) {
job->finished_notification = _mali_osk_notification_create(_MALI_NOTIFICATION_GP_FINISHED, sizeof(_mali_uk_gp_job_finished_s));
if (NULL == job->finished_notification) {
goto fail3;
}
job->oom_notification = _mali_osk_notification_create(_MALI_NOTIFICATION_GP_STALLED, sizeof(_mali_uk_gp_job_suspended_s));
if (NULL == job->oom_notification) {
goto fail2;
}
if (0 != _mali_osk_copy_from_user(&job->uargs, uargs, sizeof(_mali_uk_gp_start_job_s))) {
goto fail1;
}
perf_counter_flag = mali_gp_job_get_perf_counter_flag(job);
/* case when no counters came from user space
* so pass the debugfs / DS-5 provided global ones to the job object */
if (!((perf_counter_flag & _MALI_PERFORMANCE_COUNTER_FLAG_SRC0_ENABLE) ||
(perf_counter_flag & _MALI_PERFORMANCE_COUNTER_FLAG_SRC1_ENABLE))) {
mali_gp_job_set_perf_counter_src0(job, mali_gp_job_get_gp_counter_src0());
mali_gp_job_set_perf_counter_src1(job, mali_gp_job_get_gp_counter_src1());
}
_mali_osk_list_init(&job->list);
job->session = session;
job->id = id;
job->heap_current_addr = job->uargs.frame_registers[4];
job->perf_counter_value0 = 0;
job->perf_counter_value1 = 0;
job->pid = _mali_osk_get_pid();
job->tid = _mali_osk_get_tid();
INIT_LIST_HEAD(&job->varying_alloc);
INIT_LIST_HEAD(&job->vary_todo);
job->dmem = NULL;
if (job->uargs.deferred_mem_num > session->allocation_mgr.mali_allocation_num) {
MALI_PRINT_ERROR(("Mali GP job: The number of varying buffer to defer bind is invalid !\n"));
goto fail1;
}
/* add varying allocation list*/
if (job->uargs.deferred_mem_num > 0) {
/* copy varying list from user space*/
job->varying_list = _mali_osk_calloc(1, sizeof(u32) * job->uargs.deferred_mem_num);
if (!job->varying_list) {
MALI_PRINT_ERROR(("Mali GP job: allocate varying_list failed varying_alloc_num = %d !\n", job->uargs.deferred_mem_num));
goto fail1;
}
memory_list = (u32 __user *)(uintptr_t)job->uargs.deferred_mem_list;
if (0 != _mali_osk_copy_from_user(job->varying_list, memory_list, sizeof(u32) * job->uargs.deferred_mem_num)) {
MALI_PRINT_ERROR(("Mali GP job: Failed to copy varying list from user space!\n"));
goto fail;
}
if (unlikely(_mali_gp_add_varying_allocations(session, job, job->varying_list,
job->uargs.deferred_mem_num))) {
MALI_PRINT_ERROR(("Mali GP job: _mali_gp_add_varying_allocations failed!\n"));
goto fail;
}
/* do preparetion for each allocation */
list_for_each_entry_safe(alloc_node, tmp_node, &job->varying_alloc, node) {
if (unlikely(_MALI_OSK_ERR_OK != mali_mem_defer_bind_allocation_prepare(alloc_node->alloc, &job->vary_todo, &job->required_varying_memsize))) {
MALI_PRINT_ERROR(("Mali GP job: mali_mem_defer_bind_allocation_prepare failed!\n"));
goto fail;
}
}
_mali_gp_del_varying_allocations(job);
/* bind varying here, to avoid memory latency issue. */
{
struct mali_defer_mem_block dmem_block;
INIT_LIST_HEAD(&dmem_block.free_pages);
atomic_set(&dmem_block.num_free_pages, 0);
if (mali_mem_prepare_mem_for_job(job, &dmem_block)) {
MALI_PRINT_ERROR(("Mali GP job: mali_mem_prepare_mem_for_job failed!\n"));
goto fail;
}
if (_MALI_OSK_ERR_OK != mali_mem_defer_bind(job, &dmem_block)) {
MALI_PRINT_ERROR(("gp job create, mali_mem_defer_bind failed! GP %x fail!", job));
goto fail;
}
}
if (job->uargs.varying_memsize > MALI_UK_BIG_VARYING_SIZE)
job->big_job = 1;
}
job->pp_tracker = pp_tracker;
if (NULL != job->pp_tracker) {
/* Take a reference on PP job's tracker that will be released when the GP
job is done. */
mali_timeline_system_tracker_get(session->timeline_system, pp_tracker);
}
mali_timeline_tracker_init(&job->tracker, MALI_TIMELINE_TRACKER_GP, NULL, job);
mali_timeline_fence_copy_uk_fence(&(job->tracker.fence), &(job->uargs.fence));
return job;
} else {
MALI_PRINT_ERROR(("Mali GP job: _mali_osk_calloc failed!\n"));
return NULL;
}
fail:
_mali_osk_free(job->varying_list);
/* Handle allocate fail here, free all varying node */
{
struct mali_backend_bind_list *bkn, *bkn_tmp;
list_for_each_entry_safe(bkn, bkn_tmp , &job->vary_todo, node) {
list_del(&bkn->node);
_mali_osk_free(bkn);
}
}
fail1:
_mali_osk_notification_delete(job->oom_notification);
fail2:
_mali_osk_notification_delete(job->finished_notification);
fail3:
_mali_osk_free(job);
return NULL;
}
void mali_gp_job_delete(struct mali_gp_job *job)
{
struct mali_backend_bind_list *bkn, *bkn_tmp;
MALI_DEBUG_ASSERT_POINTER(job);
MALI_DEBUG_ASSERT(NULL == job->pp_tracker);
MALI_DEBUG_ASSERT(_mali_osk_list_empty(&job->list));
_mali_osk_free(job->varying_list);
/* Handle allocate fail here, free all varying node */
list_for_each_entry_safe(bkn, bkn_tmp , &job->vary_todo, node) {
list_del(&bkn->node);
_mali_osk_free(bkn);
}
mali_mem_defer_dmem_free(job);
/* de-allocate the pre-allocated oom notifications */
if (NULL != job->oom_notification) {
_mali_osk_notification_delete(job->oom_notification);
job->oom_notification = NULL;
}
if (NULL != job->finished_notification) {
_mali_osk_notification_delete(job->finished_notification);
job->finished_notification = NULL;
}
_mali_osk_free(job);
}
void mali_gp_job_list_add(struct mali_gp_job *job, _mali_osk_list_t *list)
{
struct mali_gp_job *iter;
struct mali_gp_job *tmp;
MALI_DEBUG_ASSERT_POINTER(job);
MALI_DEBUG_ASSERT_SCHEDULER_LOCK_HELD();
/* Find position in list/queue where job should be added. */
_MALI_OSK_LIST_FOREACHENTRY_REVERSE(iter, tmp, list,
struct mali_gp_job, list) {
/* A span is used to handle job ID wrapping. */
bool job_is_after = (mali_gp_job_get_id(job) -
mali_gp_job_get_id(iter)) <
MALI_SCHEDULER_JOB_ID_SPAN;
if (job_is_after) {
break;
}
}
_mali_osk_list_add(&job->list, &iter->list);
}
u32 mali_gp_job_get_gp_counter_src0(void)
{
return gp_counter_src0;
}
void mali_gp_job_set_gp_counter_src0(u32 counter)
{
gp_counter_src0 = counter;
}
u32 mali_gp_job_get_gp_counter_src1(void)
{
return gp_counter_src1;
}
void mali_gp_job_set_gp_counter_src1(u32 counter)
{
gp_counter_src1 = counter;
}
mali_scheduler_mask mali_gp_job_signal_pp_tracker(struct mali_gp_job *job, mali_bool success)
{
mali_scheduler_mask schedule_mask = MALI_SCHEDULER_MASK_EMPTY;
MALI_DEBUG_ASSERT_POINTER(job);
if (NULL != job->pp_tracker) {
schedule_mask |= mali_timeline_system_tracker_put(job->session->timeline_system, job->pp_tracker, MALI_FALSE == success);
job->pp_tracker = NULL;
}
return schedule_mask;
}
| 31.5 | 155 | 0.745611 | [
"object"
] |
b71c2b64afb046b7c1d2db6b04807225602ed929 | 2,784 | h | C | FMEFace.h | GameTechDev/FaceTracking | 56223359cb00a66b6dcd882dadd6e6f6a47da9ea | [
"Apache-2.0"
] | 39 | 2017-04-11T10:01:59.000Z | 2022-01-12T15:13:45.000Z | FMEFace.h | shengguo78/FaceMe | 7f87583312545f16557624d3c99b2521e95d9670 | [
"Apache-2.0"
] | 2 | 2017-03-21T22:13:20.000Z | 2021-04-19T16:38:03.000Z | FMEFace.h | shengguo78/FaceMe | 7f87583312545f16557624d3c99b2521e95d9670 | [
"Apache-2.0"
] | 16 | 2017-03-16T12:20:50.000Z | 2020-03-21T04:13:55.000Z | /////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or imlied.
// See the License for the specific language governing permissions and
// limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "FMECommon.h"
#include "FMEFaceTracker.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <deque>
#include <iostream>
#include <map>
namespace FME{
class FMEExprParser;
typedef float AUWeight;
typedef float AUState;
typedef std::map<ActionUnit,AUState> AUStates;
typedef Eigen::Vector3f Point3D;
typedef Eigen::Vector2f Point2D;
typedef std::vector<Point2D> Point2Ds;
typedef std::vector<Point3D> Point3Ds;
typedef Eigen::Vector3f FaceAngles;
typedef Eigen::Array<float,6,1> FAPUs;
typedef enum FapuName
{
IRISD_L,
IRISD_R,
ES,
ENS,
MNS,
MW,
} FapuName;
class FMEFace
{
public:
FMEFace(RawFaceData *rawFaceData, FMEExprParser *exprParser);
~FMEFace();
void MeasureAUStates();
void MeasureActionUnitWeightMap();
void MeasureFaceAngle();
AUStates* GetAUStates(){return &m_auStates;};
ActionUnitWeightMap* GetActionUnitWeightMap(){return &m_ActionUnitWeightMap;};
FaceAngles* GetRawFaceAngles(){return &m_rawFaceAngles;};
float GetAUWeight(ActionUnit fa){return m_ActionUnitWeightMap[fa];}
protected:
inline Point3D Landmark(int index);
inline float LandmarkDistance(int i, int j);
inline Point2D LandmarkImage(int index);
inline float LandmarkImageDistance(int i, int j);
void EyebrowStates();
void EyelidStates();
void EyeballStates();
void MouthStates();
void EyebrowWeights();
void EyelidWeights();
void EyeballWeights();
void MouthWeights();
protected:
RawFaceData* m_rawFaceData;
AUStates m_auStates;
ActionUnitWeightMap m_ActionUnitWeightMap;
FMEExprParser* m_exprParser;
FaceAngles m_rawFaceAngles;
FAPUs* m_neutralFAPUs;
AUStates* m_neutralAUStates;
};
class FMENeutralFace: public FMEFace
{
public:
FMENeutralFace(RawFaceData *rawFaceData,FMEExprParser *exprParser);
~FMENeutralFace();
void MeasureFAPUs();
FAPUs* GetFAPUs(){ return &m_rawFAPUs;};
protected:
FAPUs m_rawFAPUs;
};
} //namespace | 26.769231 | 94 | 0.684986 | [
"geometry",
"vector"
] |
b723e807a424b14b28dadc22b704055a9ab90dd9 | 1,626 | h | C | Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/NodePaletteTreeView.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/NodePaletteTreeView.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/GraphCanvas/Code/StaticLib/GraphCanvas/Widgets/NodePalette/NodePaletteTreeView.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#if !defined(Q_MOC_RUN)
#include <QTreeView>
#include <AzCore/Memory/SystemAllocator.h>
#include <AzToolsFramework/UI/UICore/QTreeViewStateSaver.hxx>
#endif
namespace GraphCanvas
{
class NodePaletteTreeItem;
class NodePaletteTreeView
: public AzToolsFramework::QTreeViewWithStateSaving
{
Q_OBJECT
public:
AZ_CLASS_ALLOCATOR(NodePaletteTreeView, AZ::SystemAllocator, 0);
explicit NodePaletteTreeView(QWidget* parent = nullptr);
void resizeEvent(QResizeEvent* event) override;
void selectionChanged(const QItemSelection& selected, const QItemSelection &deselected) override;
public slots:
signals:
void OnTreeItemDoubleClicked(GraphCanvas::NodePaletteTreeItem* treeItem);
protected:
void mousePressEvent(QMouseEvent* ev) override;
void mouseMoveEvent(QMouseEvent* ev) override;
void mouseReleaseEvent(QMouseEvent* ev) override;
void leaveEvent(QEvent* ev) override;
void OnClicked(const QModelIndex& modelIndex);
void OnDoubleClicked(const QModelIndex& modelIndex);
void rowsAboutToBeRemoved(const QModelIndex& parentIndex, int first, int last) override;
private:
void UpdatePointer(const QModelIndex &modelIndex, bool isMousePressed);
QModelIndex m_lastIndex;
NodePaletteTreeItem* m_lastItem;
};
}
| 28.034483 | 105 | 0.720787 | [
"3d"
] |
b724dca26a5fdc08413c033a68585ea151b0bda2 | 5,430 | h | C | MZFormSheetPresentationController/MZFormSheetPresentationViewController.h | hlhelong/MZFormSheetPresentationController | 4bf4d6d7a26e99557a5964a00bf82cd5212e71be | [
"MIT"
] | null | null | null | MZFormSheetPresentationController/MZFormSheetPresentationViewController.h | hlhelong/MZFormSheetPresentationController | 4bf4d6d7a26e99557a5964a00bf82cd5212e71be | [
"MIT"
] | null | null | null | MZFormSheetPresentationController/MZFormSheetPresentationViewController.h | hlhelong/MZFormSheetPresentationController | 4bf4d6d7a26e99557a5964a00bf82cd5212e71be | [
"MIT"
] | null | null | null | //
// MZFormSheetPresentationViewController.h
// MZFormSheetPresentationViewController
//
// Created by Michał Zaborowski on 24.02.2015.
// Copyright (c) 2015 Michał Zaborowski. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import <UIKit/UIKit.h>
#import "MZTransition.h"
#import "MZFormSheetPresentationController.h"
#import <MZAppearance/MZAppearance.h>
#import "MZFormSheetPresentationViewControllerAnimatedTransitioning.h"
#import "MZFormSheetPresentationViewControllerInteractiveTransitioning.h"
#import "MZFormSheetPresentationContentSizing.h"
extern CGFloat const MZFormSheetPresentationViewControllerDefaultAnimationDuration;
typedef void(^MZFormSheetPresentationViewControllerCompletionHandler)(UIViewController * __nonnull contentViewController);
@interface MZFormSheetPresentationViewController : UIViewController <MZAppearance, MZFormSheetPresentationContentSizing, UIViewControllerTransitioningDelegate>
/**
* The view controller responsible for the content portion of the popup.
*/
@property (nonatomic, readonly, strong, nullable) UIViewController *contentViewController;
@property (nonatomic, readonly, nullable) MZFormSheetPresentationController *presentationController;
/**
Corner radius of content view
By default, this is 5.0
*/
@property (nonatomic, assign) CGFloat contentViewCornerRadius MZ_APPEARANCE_SELECTOR;
/**
The blur radius (in points) used to render the layer’s shadow.
By default, this is 6.0
*/
@property (nonatomic, assign) CGFloat shadowRadius MZ_APPEARANCE_SELECTOR;
/**
* Allow dismiss the modals by swiping up/down/left/right on the navigation bar.
* By default, this is None.
*/
@property (nonatomic, assign) MZFormSheetPanGestureDismissDirection interactivePanGestureDismissalDirection;
/**
* Allow dismiss the modals by swiping up/down/left/right on the presented view.
* By default, this is NO.
*/
@property (nonatomic, assign) BOOL allowDismissByPanningPresentedView;
/**
The transition style to use when presenting the receiver.
By default, this is MZFormSheetPresentationTransitionStyleSlideFromTop.
*/
@property (nonatomic, assign) MZFormSheetPresentationTransitionStyle contentViewControllerTransitionStyle MZ_APPEARANCE_SELECTOR;
@property (nonatomic, strong, null_resettable) id <MZFormSheetPresentationViewControllerAnimatedTransitioning> animatorForPresentationController;
@property (nonatomic, strong, null_resettable) UIPercentDrivenInteractiveTransition <MZFormSheetPresentationViewControllerInteractiveTransitioning> *interactionAnimatorForPresentationController;
/**
The handler to call when presented form sheet is before entry transition and its view will show on window.
*/
@property (nonatomic, copy, nullable) MZFormSheetPresentationViewControllerCompletionHandler willPresentContentViewControllerHandler;
/**
The handler to call when presented form sheet is after entry transition animation.
*/
@property (nonatomic, copy, nullable) MZFormSheetPresentationViewControllerCompletionHandler didPresentContentViewControllerHandler;
/**
The handler to call when presented form sheet will be dismiss, this is called before out transition animation.
*/
@property (nonatomic, copy, nullable) MZFormSheetPresentationViewControllerCompletionHandler willDismissContentViewControllerHandler;
/**
The handler to call when presented form sheet is after dismiss.
*/
@property (nonatomic, copy, nullable) MZFormSheetPresentationViewControllerCompletionHandler didDismissContentViewControllerHandler;
/**
Returns an initialized popup controller object with just a view.
@param contentView This parameter must not be nil.
*/
- (nonnull instancetype)initWithContentView:(UIView * __nonnull)contentView;
/**
Returns an initialized popup controller object.
@param viewController This parameter must not be nil.
*/
- (nonnull instancetype)initWithContentViewController:(UIViewController * __nonnull)viewController;
@property (nonatomic, strong) UIPanGestureRecognizer *presentedViewDismissalPanGestureRecognizer;
/** 拖拽结束 */
@property (nonatomic, copy) dispatch_block_t dragEndBlock;
@end
@interface UIViewController (MZFormSheetPresentationViewController)
- (nullable MZFormSheetPresentationViewController *)mz_formSheetPresentingPresentationController;
- (nullable MZFormSheetPresentationViewController *)mz_formSheetPresentedPresentationController;
@end
| 42.755906 | 194 | 0.816943 | [
"render",
"object"
] |
b72dc87b584ba6fb8c075ecd7c61353c83faf974 | 3,840 | h | C | RecoLocalMuon/DTSegment/src/DTSegmentUpdator.h | malbouis/cmssw | 16173a30d3f0c9ecc5419c474bb4d272c58b65c8 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoLocalMuon/DTSegment/src/DTSegmentUpdator.h | malbouis/cmssw | 16173a30d3f0c9ecc5419c474bb4d272c58b65c8 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoLocalMuon/DTSegment/src/DTSegmentUpdator.h | malbouis/cmssw | 16173a30d3f0c9ecc5419c474bb4d272c58b65c8 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #ifndef DTSegment_DTSegmentUpdator_h
#define DTSegment_DTSegmentUpdator_h
/** \class DTSegmentUpdator
*
* Perform linear fit and hits update for DT segments.
* Update a segment by improving the hits thanks to the refined knowledge of
* impact angle and position (also along the wire) and perform linear fit on
* improved hits.
*
* \author Stefano Lacaprara - INFN Legnaro <stefano.lacaprara@pd.infn.it>
* \author Riccardo Bellan - INFN TO <riccardo.bellan@cern.ch>
* \author M.Meneghelli - INFN BO <marco.meneghelli@cern.ch>
*
*/
/* C++ Headers */
#include <vector>
#include "DataFormats/CLHEP/interface/AlgebraicObjects.h"
#include "DataFormats/GeometryVector/interface/GlobalPoint.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/ConsumesCollector.h"
#include "Geometry/DTGeometry/interface/DTGeometry.h"
/* ====================================================================== */
/* Collaborating Class Declarations */
class DTSegmentCand;
class DTRecSegment2D;
class DTRecSegment4D;
class DTLinearFit;
class DTRecHitBaseAlgo;
class DTChamberRecSegment2D;
class DTGeometry;
class MuonGeometryRecord;
namespace edm {
class EventSetup;
class ParameterSet;
} // namespace edm
/* Class DTSegmentUpdator Interface */
class DTSegmentUpdator {
public:
/// Constructor
DTSegmentUpdator(const edm::ParameterSet& config, edm::ConsumesCollector);
/// Destructor
~DTSegmentUpdator();
/* Operations */
/** do the linear fit on the hits of the segment candidate and update it.
* Returns false if the segment candidate is not good() */
bool fit(DTSegmentCand* seg, bool allow3par, const bool fitdebug) const;
/** ditto for true segment: since the fit is applied on a true segment, by
* definition the segment is "good", while it's not the case for just
* candidates */
void fit(DTRecSegment2D* seg, bool allow3par, bool block3par) const;
/** ditto for true segment 4D, the fit is done on either projection and then
* the 4D direction and position is built. Since the fit is applied on a
* true segment, by definition the segment is "good", while it's not the
* case for just candidates */
void fit(DTRecSegment4D* seg, bool allow3par) const;
/// recompute hits position and refit the segment4D
void update(DTRecSegment4D* seg, const bool calcT0, bool allow3par) const;
/// recompute hits position and refit the segment2D
void update(DTRecSegment2D* seg, bool allow3par) const;
void calculateT0corr(DTRecSegment2D* seg) const;
void calculateT0corr(DTRecSegment4D* seg) const;
/// set the setup
void setES(const edm::EventSetup& setup);
protected:
private:
std::unique_ptr<DTLinearFit> theFitter; // the linear fitter
std::unique_ptr<DTRecHitBaseAlgo> theAlgo; // the algo for hit reconstruction
edm::ESHandle<DTGeometry> theGeom; // the geometry
const edm::ESGetToken<DTGeometry, MuonGeometryRecord> theGeomToken;
void updateHits(DTRecSegment2D* seg, GlobalPoint& gpos, GlobalVector& gdir, const int step = 2) const;
//rejects bad hits (due to deltas) for phi segment
void rejectBadHits(DTChamberRecSegment2D*) const;
/// interface to LinearFit
void fit(const std::vector<float>& x,
const std::vector<float>& y,
const std::vector<int>& lfit,
const std::vector<double>& dist,
const std::vector<float>& sigy,
LocalPoint& pos,
LocalVector& dir,
float& cminf,
float& vminf,
AlgebraicSymMatrix& covMat,
double& chi2,
const bool allow3par = false,
const bool block3par = false) const;
double intime_cut;
bool vdrift_4parfit;
double T0_hit_resolution;
bool perform_delta_rejecting;
bool debug;
};
#endif // DTSegment_DTSegmentUpdator_h
| 32.542373 | 104 | 0.708594 | [
"geometry",
"vector"
] |
b73a0d5c14bb0e2ec873949879887a006b2520db | 12,648 | h | C | ePub3/utilities/iri.h | khemlabs/readium-sdk | 5989b5d7932082064ccbe63bd43e6e8fa9d45b5c | [
"BSD-3-Clause"
] | 289 | 2015-01-01T12:46:16.000Z | 2022-03-25T14:49:55.000Z | ePub3/utilities/iri.h | khemlabs/readium-sdk | 5989b5d7932082064ccbe63bd43e6e8fa9d45b5c | [
"BSD-3-Clause"
] | 193 | 2015-01-07T17:30:58.000Z | 2022-01-15T14:17:29.000Z | ePub3/utilities/iri.h | khemlabs/readium-sdk | 5989b5d7932082064ccbe63bd43e6e8fa9d45b5c | [
"BSD-3-Clause"
] | 122 | 2015-01-23T15:03:03.000Z | 2022-02-15T08:13:32.000Z | //
// iri.h
// ePub3
//
// Created by Jim Dovey on 2013-01-15.
// Copyright (c) 2014 Readium Foundation and/or its licensees. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
// 3. Neither the name of the organization nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef __ePub3__iri__
#define __ePub3__iri__
#include <ePub3/utilities/utfstring.h>
#include <ePub3/utilities/make_unique.h>
#include <google-url/gurl.h>
#include <vector>
EPUB3_BEGIN_NAMESPACE
class CFI;
/**
The IRI class encapsulates all URL and URN storage in Readium.
The EPUB 3 specification calls for IRIs rather than URIs (i.e. Unicode characters
are allowed and should not be implicitly encoded) in matching properties and other
identifiers. This class provides URN support internally, URL support through
Google's GURL library, and Unicode IRI support is wrapped around GURL.
@ingroup utilities
*/
class IRI
{
// would like this to contain const strings, but that proves awkward for now
typedef std::vector<string> ComponentList;
typedef ComponentList::size_type size_type;
static string gPathSeparator;
static string gURNScheme;
static string gReservedCharacters;
public:
///
/// A type encapsulating an account and shared-secret pair, such as username and password.
typedef const std::pair<string, string> IRICredentials;
///
/// The IRI scheme used to refer to EPUB 3 documents.
EPUB3_EXPORT
static string gEPUBScheme;
EPUB3_EXPORT
static void AddStandardScheme(const string& scheme);
public:
///
/// Initializes an empty (and thus invalid) IRI.
IRI() : _urnComponents(), _url(make_unique<GURL>()), _pureIRI() {}
/**
Create a new IRI.
@param iriStr A valid URL or IRI string.
*/
EPUB3_EXPORT
IRI(const string& iriStr);
/**
Create a URN.
Follows the form 'urn:`nameID`:`namespacedString`'.
@param nameID The identifier/namespace for the resource name.
@param namespacedString The resource name.
*/
EPUB3_EXPORT
IRI(const string& nameID, const string& namespacedString);
/**
Create a simple URL.
The URL will be in the format:
[scheme]://[host][path]?[query]#[fragment]
If the path is empty or does not begin with a path separator character (`/`),
one will be inserted automatically.
@param scheme The URL scheme.
@param host The host part of the URL.
@param path The URL's path.
@param query Any query components of the URL, properly URL-encoded.
@param fragment A fragmuent used to identify a particular location within a
resource.
*/
EPUB3_EXPORT
IRI(const string& scheme, const string& host, const string& path, const string& query=string(), const string& fragment=string());
///
/// Create a copy of an existing IRI.
IRI(const IRI& o) : _urnComponents(o._urnComponents), _url(new GURL(*o._url)), _pureIRI(o._pureIRI) {}
///
/// C++11 move-constructor.
IRI(IRI&& o) : _urnComponents(std::move(o._urnComponents)), _url(std::move(o._url)), _pureIRI(std::move(o._pureIRI)) { o._url = nullptr; }
virtual ~IRI();
/// @{
/// @name Assignment
///
/// Assigns the value of another IRI (copy assignment).
EPUB3_EXPORT
IRI& operator=(const IRI& o);
///
/// Assigns ownership of the value of another IRI (move assignment).
EPUB3_EXPORT
IRI& operator=(IRI&& o);
/**
Assigns the IRI the value represented by the given string.
@param str The IRI string to parse and assign.
@throw std::invalid_argument if the input string does not represent a valid IRI.
*/
EPUB3_EXPORT
IRI& operator=(const string& str);
/// @}
/// @{
/// @name Comparators
/**
Compares two IRIs for equality.
@param o An IRI to compare.
@result Returns `true` if the IRIs are equal, `false` otherwise.
*/
EPUB3_EXPORT
bool operator==(const IRI& o) const;
/**
Compares two IRIs for inequality.
@param o An IRI to compare.
@result Returns `true` if the IRIs are *not* equal, `false` otherwise.
*/
EPUB3_EXPORT
bool operator!=(const IRI& o) const;
/**
Less-than comparator.
This is here to add std::sort() support to IRIs.
@param o An IRI against which to compare.
@result Returns `true` if `*this` is less than `o`, `false` otherwise.
*/
EPUB3_EXPORT
bool operator<(const IRI& o) const;
/// @}
///
/// Returns `true` if the IRI is a URN.
bool IsURN() const { return _urnComponents.size() > 1; }
///
/// Returns `true` if the IRI is a URL referencing a relative location.
bool IsRelative() const { return !_url->has_host(); }
///
/// Returns `true` if the IRI is empty.
bool IsEmpty() const { return _url->is_empty(); }
/// @{
/// @name Component Introspection
///
/// Obtains the IRI's scheme component.
const string Scheme() const { return (IsURN() ? _urnComponents[0] : _url->scheme()); } // simple, because it must ALWAYS be present (even if empty, as for pure fragment IRIs)
///
/// Obtains the name-id component of a URN IRI.
const string& NameID() const { if (!IsURN()) { throw std::invalid_argument("Not a URN"); } return _urnComponents[1]; }
///
/// Retrieves the nost component of a URL IRI.
const string Host() const { return _url->host(); }
///
/// Retrieves any credentials attached to an IRI.
EPUB3_EXPORT
IRICredentials Credentials() const;
///
/// Returns the namespace-qualified part of a URN IRI.
const string NamespacedString() const { if (!IsURN()) { throw std::invalid_argument("Not a URN"); } return _urnComponents[2]; }
///
/// Obtains the port number associated with a URL IRI.
int Port() const { return _url->EffectiveIntPort(); }
/**
Obtains the path component of a URL IRI.
@param URLEncoded If `true`, returns the path in URL-encoded format. Otherwise,
the path will be decoded first, yielding a standard POSIX file-system path.
*/
EPUB3_EXPORT
const string Path(bool URLEncoded=true) const;
///
/// Retrieves the query portion of a URL IRI, if any.
const string Query() const { return _url->query(); }
///
/// Retrieves any fragment part of a URL IRI.
const string Fragment() const { return _url->ref(); }
///
/// Obtains the last path component of a URL IRI.
const string LastPathComponent() const { return _url->ExtractFileName(); }
/**
Returns any CFI present in a URL IRI.
If the fragment part of a URL is a valid Content Fragment Identifier (i.e. if
the URL's fragment begins with `epubcfi(`) then this will parse the fragment
into a CFI representation.
@result A valid CFI if one is present in the URL's fragment, or an empty CFI if
no content fragment identifier is present.
*/
EPUB3_EXPORT
const CFI ContentFragmentIdentifier() const;
/**
Assigns a scheme to this IRI.
@param scheme The new scheme.
*/
EPUB3_EXPORT
void SetScheme(const string& scheme);
/**
Assigns a host to this IRI.
@note The host **must not** contain a port number. Any instance of the
characters '`[`', '`]`', or '`:`' will cause the host to be rejected, as these
characters are only valid in IPv6-address hostnames such as `[ff:8::1]`.
@param host The new host component.
*/
EPUB3_EXPORT
void SetHost(const string& host);
/**
Assigns a port number to this IRI.
@param port The new port number.
*/
EPUB3_EXPORT
void SetPort(uint16_t port);
/**
Sets credentials for this IRI.
@param user The username for the credential.
@param pass The shared-secret part of the credential.
*/
EPUB3_EXPORT
void SetCredentials(const string& user, const string& pass);
/**
Appends a new component to a URL IRI's path.
@param component The new path component.
*/
EPUB3_EXPORT
void AddPathComponent(const string& component);
/**
Adds or replaces the query component of a URL IRI.
@param query The new query string.
*/
EPUB3_EXPORT
void SetQuery(const string& query);
/**
Adds or replaces the fragment component of a URL IRI.
@param fragment The new fragment string.
*/
EPUB3_EXPORT
void SetFragment(const string& query);
/**
Sets a URL IRI's fragment using a Content Fragment Identifier.
*/
EPUB3_EXPORT
void SetContentFragmentIdentifier(const CFI& cfi);
/// @}
/// @{
/// @name Helper Methods
///
/// URL-encodes a path, query, or fragment component.
EPUB3_EXPORT
static string URLEncodeComponent(const string& str);
///
/// Percent-encodes the UTF-8 representation of any non-ASCII characters in a string.
EPUB3_EXPORT
static string PercentEncodeUCS(const string& str);
///
/// Converts an IDN (hostname in non-ASCII Unicode format) into its ASCII representation.
EPUB3_EXPORT
static string IDNEncodeHostname(const string& host);
/// @}
/**
Obtains a Unicode string representation of this IRI.
Only percent-encodes URL-reserved characters within components, and uses IDN
algorithm to obtain a Unicode hostname.
Note that any components which are already URL-encoded will not be explicitly
decoded by this function.
@result A Unicode IRI string.
*/
EPUB3_EXPORT
string IRIString() const;
/**
Obtains a valid ASCII URL representation of this IRI.
Percent-encodes all URL-reserved characters and all non-ASCII characters outside
the hostname using those characters' UTF-8 representations. Uses IDN algorithm to
obtain an ASCII representation of any Unicode hostname.
@result An ASCII URL string; even though the result is a Unicode string type, the
characters are guaranteed to be valid ASCII suitable for use with non-Unicode
libraries.
*/
EPUB3_EXPORT
string URIString() const;
protected:
ComponentList _urnComponents; ///< The components of a URN.
std::unique_ptr<GURL> _url; ///< The underlying URL object.
string _pureIRI; ///< A cache of the Unicode IRI string. May be empty.
};
template <class _CharT, class _Traits>
inline std::basic_ostream<_CharT, _Traits>&
operator<<(std::basic_ostream<_CharT, _Traits>& __os, const IRI& iri) {
return __os << iri.URIString();
}
EPUB3_END_NAMESPACE
#endif /* defined(__ePub3__iri__) */
| 33.728 | 184 | 0.640892 | [
"object",
"vector"
] |
bb812e3a4c550e317218cca759632a52ad59c66e | 9,842 | h | C | test/test_deconvolutional_layer.h | kvmanohar22/tiny-dnn | 465aa899a870143ab66cf14207f1fcbaac7804ed | [
"BSD-3-Clause"
] | 3 | 2016-12-04T20:44:51.000Z | 2020-12-07T22:28:48.000Z | test/test_deconvolutional_layer.h | kvmanohar22/tiny-dnn | 465aa899a870143ab66cf14207f1fcbaac7804ed | [
"BSD-3-Clause"
] | 9 | 2016-07-28T20:51:13.000Z | 2017-06-21T10:13:06.000Z | test/test_deconvolutional_layer.h | kvmanohar22/tiny-dnn | 465aa899a870143ab66cf14207f1fcbaac7804ed | [
"BSD-3-Clause"
] | 5 | 2016-07-28T03:35:56.000Z | 2020-02-14T20:56:54.000Z | /*
Copyright (c) 2013, Taiga Nomi and the respective contributors
All rights reserved.
Use of this source code is governed by a BSD-style license that can be found
in the LICENSE file.
*/
#pragma once
#include <gtest/gtest.h>
#include <vector>
#include "test/testhelper.h"
#include "tiny_dnn/tiny_dnn.h"
namespace tiny_dnn {
TEST(deconvolutional, setup_tiny) {
deconvolutional_layer l(2, 2, 3, 1, 2, padding::valid, true, 1, 1,
core::backend_t::internal);
EXPECT_EQ(l.parallelize(), true); // if layer can be parallelized
EXPECT_EQ(l.in_channels(), 3u); // num of input tensors
EXPECT_EQ(l.out_channels(), 1u); // num of output tensors
EXPECT_EQ(l.in_data_size(), 4u); // size of input tensors
EXPECT_EQ(l.out_data_size(), 32u); // size of output tensors
EXPECT_EQ(l.in_data_shape().size(), 1u); // number of inputs shapes
EXPECT_EQ(l.out_data_shape().size(), 1u); // num of output shapes
EXPECT_EQ(l.weights().size(), 2u); // the wieghts vector size
EXPECT_EQ(l.weights_grads().size(), 2u); // the wieghts vector size
EXPECT_EQ(l.inputs().size(), 3u); // num of input edges
EXPECT_EQ(l.outputs().size(), 1u); // num of outpus edges
EXPECT_EQ(l.in_types().size(), 3u); // num of input data types
EXPECT_EQ(l.out_types().size(), 1u); // num of output data types
EXPECT_EQ(l.fan_in_size(), 9u); // num of incoming connections
EXPECT_EQ(l.fan_out_size(), 18u); // num of outgoing connections
EXPECT_STREQ(l.layer_type().c_str(), "deconv"); // string with layer type
}
#ifdef CNN_USE_NNPACK
TEST(deconvolutional, setup_nnp) {
deconvolutional_layer l(2, 2, 3, 1, 2, padding::valid, true, 1, 1,
backend_t::nnpack);
EXPECT_EQ(l.parallelize(), true); // if layer can be parallelized
EXPECT_EQ(l.in_channels(), 3); // num of input tensors
EXPECT_EQ(l.out_channels(), 1); // num of output tensors
EXPECT_EQ(l.in_data_size(), 4); // size of input tensors
EXPECT_EQ(l.out_data_size(), 32); // size of output tensors
EXPECT_EQ(l.in_data_shape().size(), 1); // number of inputs shapes
EXPECT_EQ(l.out_data_shape().size(), 1); // num of output shapes
EXPECT_EQ(l.weights().size(), 2); // the wieghts vector size
EXPECT_EQ(l.weights_grads().size(), 2); // the wieghts vector size
EXPECT_EQ(l.inputs().size(), 3); // num of input edges
EXPECT_EQ(l.outputs().size(), 1); // num of outpus edges
EXPECT_EQ(l.in_types().size(), 3); // num of input data types
EXPECT_EQ(l.out_types().size(), 1); // num of output data types
EXPECT_EQ(l.fan_in_size(), 9); // num of incoming connections
EXPECT_EQ(l.fan_out_size(), 18); // num of outgoing connections
EXPECT_STREQ(l.layer_type().c_str(), "deconv"); // string with layer type
}
#endif
TEST(deconvolutional, fprop) {
network<sequential> nn;
deconvolutional_layer l(2, 2, 3, 1, 2);
// layer::forward_propagation expects tensors, even if we feed only one
// input at a time
auto create_simple_tensor = [](size_t vector_size) {
return tensor_t(1, vec_t(vector_size));
};
// create simple tensors that wrap the payload vectors of the correct size
tensor_t in_tensor = create_simple_tensor(4),
out_tensor = create_simple_tensor(32),
a_tensor = create_simple_tensor(32),
weight_tensor = create_simple_tensor(18),
bias_tensor = create_simple_tensor(2);
// short-hand references to the payload vectors
vec_t &in = in_tensor[0], &out = out_tensor[0], &weight = weight_tensor[0];
ASSERT_EQ(l.in_shape()[1].size(), 18u); // weight
uniform_rand(in.begin(), in.end(), -1.0, 1.0);
std::vector<tensor_t *> in_data, out_data;
in_data.push_back(&in_tensor);
in_data.push_back(&weight_tensor);
in_data.push_back(&bias_tensor);
out_data.push_back(&out_tensor);
out_data.push_back(&a_tensor);
l.setup(false);
{
l.forward_propagation(in_data, out_data);
for (auto o : out) EXPECT_DOUBLE_EQ(o, float_t(0));
}
// clang-format off
weight[0] = 0.3; weight[1] = 0.1; weight[2] = 0.2;
weight[3] = 0.0; weight[4] = -0.1; weight[5] = -0.1;
weight[6] = 0.05; weight[7] = -0.2; weight[8] = 0.05;
weight[9] = 0.0; weight[10] = -0.1; weight[11] = 0.1;
weight[12] = 0.1; weight[13] = -0.2; weight[14] = 0.3;
weight[15] = 0.2; weight[16] = -0.3; weight[17] = 0.2;
in[0] = 3; in[1] = 2; in[2] = 3; in[3] = 0;
// clang-format on
{
l.forward_propagation(in_data, out_data);
EXPECT_NEAR(0.900, out[0], 1E-5);
EXPECT_NEAR(0.900, out[1], 1E-5);
EXPECT_NEAR(0.800, out[2], 1E-5);
EXPECT_NEAR(0.400, out[3], 1E-5);
EXPECT_NEAR(0.900, out[4], 1E-5);
EXPECT_NEAR(0.000, out[5], 1E-5);
EXPECT_NEAR(0.100, out[6], 1E-5);
EXPECT_NEAR(-0.20, out[7], 1E-5);
EXPECT_NEAR(0.150, out[8], 1E-5);
EXPECT_NEAR(-0.80, out[9], 1E-5);
EXPECT_NEAR(-0.55, out[10], 1E-5);
EXPECT_NEAR(0.100, out[11], 1E-5);
EXPECT_NEAR(0.150, out[12], 1E-5);
EXPECT_NEAR(-0.60, out[13], 1E-5);
EXPECT_NEAR(0.150, out[14], 1E-5);
EXPECT_NEAR(0.000, out[15], 1E-5);
}
}
TEST(deconvolutional, fprop2) {
network<sequential> nn;
deconvolutional_layer l(2, 2, 3, 1, 2, padding::same);
auto create_simple_tensor = [](size_t vector_size) {
return tensor_t(1, vec_t(vector_size));
};
tensor_t in_tensor = create_simple_tensor(4),
out_tensor = create_simple_tensor(32),
weight_tensor = create_simple_tensor(18),
bias_tensor = create_simple_tensor(2);
// short-hand references to the payload vectors
vec_t &in = in_tensor[0], &out = out_tensor[0], &weight = weight_tensor[0];
ASSERT_EQ(l.in_shape()[1].size(), 18u); // weight
uniform_rand(in.begin(), in.end(), -1.0, 1.0);
std::vector<tensor_t *> in_data, out_data;
in_data.push_back(&in_tensor);
in_data.push_back(&weight_tensor);
in_data.push_back(&bias_tensor);
out_data.push_back(&out_tensor);
l.setup(false);
{
l.forward_propagation(in_data, out_data);
for (auto o : out) EXPECT_DOUBLE_EQ(o, float_t(0));
}
// clang-format off
weight[0] = 0.3; weight[1] = 0.1; weight[2] = 0.2;
weight[3] = 0.0; weight[4] = -0.1; weight[5] = -0.1;
weight[6] = 0.05; weight[7] = -0.2; weight[8] = 0.05;
weight[9] = 0.0; weight[10] = -0.1; weight[11] = 0.1;
weight[12] = 0.1; weight[13] = -0.2; weight[14] = 0.3;
weight[15] = 0.2; weight[16] = -0.3; weight[17] = 0.2;
in[0] = 3; in[1] = 2; in[2] = 3; in[3] = 0;
// clang-format on
// resize tensor because its dimension changed in above used test case
out_tensor[0].resize(32);
{
l.forward_propagation(in_data, out_data);
EXPECT_NEAR(0.000, out[0], 1E-5);
EXPECT_NEAR(0.100, out[1], 1E-5);
EXPECT_NEAR(-0.80, out[2], 1E-5);
EXPECT_NEAR(-0.55, out[3], 1E-5);
EXPECT_NEAR(-0.70, out[4], 1E-5);
EXPECT_NEAR(0.800, out[5], 1E-5);
EXPECT_NEAR(-1.10, out[6], 1E-5);
EXPECT_NEAR(0.900, out[7], 1E-5);
}
}
/*
TEST(deconvolutional, gradient_check) { // tanh - mse
network<sequential> nn;
nn << deconvolutional_layer(2, 2, 3, 1, 1) << tanh();
const auto test_data = generate_gradient_check_data(nn.in_data_size());
nn.init_weight();
EXPECT_TRUE(nn.gradient_check<mse>(test_data.first, test_data.second,
epsilon<float_t>(), GRAD_CHECK_ALL));
}
TEST(deconvolutional, gradient_check2) { // sigmoid - mse
network<sequential> nn;
nn << deconvolutional_layer(2, 2, 3, 1, 1) << sigmoid();
const auto test_data = generate_gradient_check_data(nn.in_data_size());
nn.init_weight();
EXPECT_TRUE(nn.gradient_check<mse>(test_data.first, test_data.second,
epsilon<float_t>(), GRAD_CHECK_ALL));
}
TEST(deconvolutional, gradient_check3) { // rectified - mse
network<sequential> nn;
nn << deconvolutional_layer(2, 2, 3, 1, 1) << relu();
const auto test_data = generate_gradient_check_data(nn.in_data_size());
nn.init_weight();
EXPECT_TRUE(nn.gradient_check<mse>(test_data.first, test_data.second,
epsilon<float_t>(), GRAD_CHECK_ALL));
}
TEST(deconvolutional, gradient_check4) { // identity - mse
network<sequential> nn;
nn << deconvolutional_layer(2, 2, 3, 1, 1);
const auto test_data = generate_gradient_check_data(nn.in_data_size());
nn.init_weight();
EXPECT_TRUE(nn.gradient_check<mse>(test_data.first, test_data.second,
epsilon<float_t>(), GRAD_CHECK_ALL));
}
TEST(deconvolutional, gradient_check5) { // sigmoid - cross-entropy
network<sequential> nn;
nn << deconvolutional_layer(2, 2, 3, 1, 1) << sigmoid();
const auto test_data = generate_gradient_check_data(nn.in_data_size());
nn.init_weight();
EXPECT_TRUE(nn.gradient_check<cross_entropy>(
test_data.first, test_data.second, epsilon<float_t>(), GRAD_CHECK_ALL));
}
TEST(deconvolutional, read_write)
{
deconvolutional_layer l1(2, 2, 3, 1, 1);
deconvolutional_layer l2(2, 2, 3, 1, 1);
l1.init_weight();
l2.init_weight();
serialization_test(l1, l2);
}
TEST(deconvolutional, read_write2) {
#define O true
#define X false
static const bool connection[] = {
O, X, X, X, O, O,
O, O, X, X, X, O,
O, O, O, X, X, X
};
#undef O
#undef X
deconvolutional_layer layer1(14, 14, 5, 3, 6,
connection_table(connection, 3, 6));
deconvolutional_layer layer2(14, 14, 5, 3, 6,
connection_table(connection, 3, 6));
layer1.init_weight();
layer2.init_weight();
serialization_test(layer1, layer2);
}
*/
} // namespace tiny_dnn
| 34.533333 | 80 | 0.631884 | [
"vector"
] |
bb90b3637cacb68b3649c644bb17aef94304a465 | 9,882 | c | C | src/mesa/drivers/dri/i965/genX_blorp_exec.c | VincentWei/mg-mesa3d | e8046ad08e90494c900aab65d9360b01e3536c73 | [
"MIT"
] | 1 | 2022-03-26T08:39:34.000Z | 2022-03-26T08:39:34.000Z | src/mesa/drivers/dri/i965/genX_blorp_exec.c | VincentWei/mg-mesa3d | e8046ad08e90494c900aab65d9360b01e3536c73 | [
"MIT"
] | null | null | null | src/mesa/drivers/dri/i965/genX_blorp_exec.c | VincentWei/mg-mesa3d | e8046ad08e90494c900aab65d9360b01e3536c73 | [
"MIT"
] | 2 | 2018-09-19T09:53:12.000Z | 2022-01-27T09:25:20.000Z | /*
* Copyright © 2011 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) 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 <assert.h>
#include "intel_batchbuffer.h"
#include "intel_mipmap_tree.h"
#include "intel_fbo.h"
#include "brw_context.h"
#include "brw_state.h"
#include "blorp/blorp_genX_exec.h"
#if GEN_GEN <= 5
#include "gen4_blorp_exec.h"
#endif
#include "brw_blorp.h"
static void *
blorp_emit_dwords(struct blorp_batch *batch, unsigned n)
{
assert(batch->blorp->driver_ctx == batch->driver_batch);
struct brw_context *brw = batch->driver_batch;
intel_batchbuffer_begin(brw, n, RENDER_RING);
uint32_t *map = brw->batch.map_next;
brw->batch.map_next += n;
intel_batchbuffer_advance(brw);
return map;
}
static uint64_t
blorp_emit_reloc(struct blorp_batch *batch,
void *location, struct blorp_address address, uint32_t delta)
{
assert(batch->blorp->driver_ctx == batch->driver_batch);
struct brw_context *brw = batch->driver_batch;
uint32_t offset;
if (GEN_GEN < 6 && brw_ptr_in_state_buffer(&brw->batch, location)) {
offset = (char *)location - (char *)brw->batch.state.map;
return brw_state_reloc(&brw->batch, offset,
address.buffer, address.offset + delta,
address.reloc_flags);
}
assert(!brw_ptr_in_state_buffer(&brw->batch, location));
offset = (char *)location - (char *)brw->batch.batch.map;
return brw_batch_reloc(&brw->batch, offset,
address.buffer, address.offset + delta,
address.reloc_flags);
}
static void
blorp_surface_reloc(struct blorp_batch *batch, uint32_t ss_offset,
struct blorp_address address, uint32_t delta)
{
assert(batch->blorp->driver_ctx == batch->driver_batch);
struct brw_context *brw = batch->driver_batch;
struct brw_bo *bo = address.buffer;
uint64_t reloc_val =
brw_state_reloc(&brw->batch, ss_offset, bo, address.offset + delta,
address.reloc_flags);
void *reloc_ptr = (void *)brw->batch.state.map + ss_offset;
#if GEN_GEN >= 8
*(uint64_t *)reloc_ptr = reloc_val;
#else
*(uint32_t *)reloc_ptr = reloc_val;
#endif
}
static void *
blorp_alloc_dynamic_state(struct blorp_batch *batch,
uint32_t size,
uint32_t alignment,
uint32_t *offset)
{
assert(batch->blorp->driver_ctx == batch->driver_batch);
struct brw_context *brw = batch->driver_batch;
return brw_state_batch(brw, size, alignment, offset);
}
static void
blorp_alloc_binding_table(struct blorp_batch *batch, unsigned num_entries,
unsigned state_size, unsigned state_alignment,
uint32_t *bt_offset, uint32_t *surface_offsets,
void **surface_maps)
{
assert(batch->blorp->driver_ctx == batch->driver_batch);
struct brw_context *brw = batch->driver_batch;
uint32_t *bt_map = brw_state_batch(brw,
num_entries * sizeof(uint32_t), 32,
bt_offset);
for (unsigned i = 0; i < num_entries; i++) {
surface_maps[i] = brw_state_batch(brw,
state_size, state_alignment,
&(surface_offsets)[i]);
bt_map[i] = surface_offsets[i];
}
}
static void *
blorp_alloc_vertex_buffer(struct blorp_batch *batch, uint32_t size,
struct blorp_address *addr)
{
assert(batch->blorp->driver_ctx == batch->driver_batch);
struct brw_context *brw = batch->driver_batch;
/* From the Skylake PRM, 3DSTATE_VERTEX_BUFFERS:
*
* "The VF cache needs to be invalidated before binding and then using
* Vertex Buffers that overlap with any previously bound Vertex Buffer
* (at a 64B granularity) since the last invalidation. A VF cache
* invalidate is performed by setting the "VF Cache Invalidation Enable"
* bit in PIPE_CONTROL."
*
* This restriction first appears in the Skylake PRM but the internal docs
* also list it as being an issue on Broadwell. In order to avoid this
* problem, we align all vertex buffer allocations to 64 bytes.
*/
uint32_t offset;
void *data = brw_state_batch(brw, size, 64, &offset);
*addr = (struct blorp_address) {
.buffer = brw->batch.state.bo,
.offset = offset,
#if GEN_GEN == 10
.mocs = CNL_MOCS_WB,
#elif GEN_GEN == 9
.mocs = SKL_MOCS_WB,
#elif GEN_GEN == 8
.mocs = BDW_MOCS_WB,
#elif GEN_GEN == 7
.mocs = GEN7_MOCS_L3,
#endif
};
return data;
}
#if GEN_GEN >= 8
static struct blorp_address
blorp_get_workaround_page(struct blorp_batch *batch)
{
assert(batch->blorp->driver_ctx == batch->driver_batch);
struct brw_context *brw = batch->driver_batch;
return (struct blorp_address) {
.buffer = brw->workaround_bo,
};
}
#endif
static void
blorp_flush_range(struct blorp_batch *batch, void *start, size_t size)
{
/* All allocated states come from the batch which we will flush before we
* submit it. There's nothing for us to do here.
*/
}
static void
blorp_emit_urb_config(struct blorp_batch *batch,
unsigned vs_entry_size, unsigned sf_entry_size)
{
assert(batch->blorp->driver_ctx == batch->driver_batch);
struct brw_context *brw = batch->driver_batch;
#if GEN_GEN >= 7
if (brw->urb.vsize >= vs_entry_size)
return;
gen7_upload_urb(brw, vs_entry_size, false, false);
#elif GEN_GEN == 6
gen6_upload_urb(brw, vs_entry_size, false, 0);
#else
/* We calculate it now and emit later. */
brw_calculate_urb_fence(brw, 0, vs_entry_size, sf_entry_size);
#endif
}
void
genX(blorp_exec)(struct blorp_batch *batch,
const struct blorp_params *params)
{
assert(batch->blorp->driver_ctx == batch->driver_batch);
struct brw_context *brw = batch->driver_batch;
struct gl_context *ctx = &brw->ctx;
bool check_aperture_failed_once = false;
/* Flush the sampler and render caches. We definitely need to flush the
* sampler cache so that we get updated contents from the render cache for
* the glBlitFramebuffer() source. Also, we are sometimes warned in the
* docs to flush the cache between reinterpretations of the same surface
* data with different formats, which blorp does for stencil and depth
* data.
*/
if (params->src.enabled)
brw_render_cache_set_check_flush(brw, params->src.addr.buffer);
brw_render_cache_set_check_flush(brw, params->dst.addr.buffer);
brw_select_pipeline(brw, BRW_RENDER_PIPELINE);
retry:
intel_batchbuffer_require_space(brw, 1400, RENDER_RING);
brw_require_statebuffer_space(brw, 600);
intel_batchbuffer_save_state(brw);
brw->batch.no_wrap = true;
#if GEN_GEN == 6
/* Emit workaround flushes when we switch from drawing to blorping. */
brw_emit_post_sync_nonzero_flush(brw);
#endif
brw_upload_state_base_address(brw);
#if GEN_GEN >= 8
gen7_l3_state.emit(brw);
#endif
#if GEN_GEN >= 6
brw_emit_depth_stall_flushes(brw);
#endif
#if GEN_GEN == 8
gen8_write_pma_stall_bits(brw, 0);
#endif
blorp_emit(batch, GENX(3DSTATE_DRAWING_RECTANGLE), rect) {
rect.ClippedDrawingRectangleXMax = MAX2(params->x1, params->x0) - 1;
rect.ClippedDrawingRectangleYMax = MAX2(params->y1, params->y0) - 1;
}
blorp_exec(batch, params);
brw->batch.no_wrap = false;
/* Check if the blorp op we just did would make our batch likely to fail to
* map all the BOs into the GPU at batch exec time later. If so, flush the
* batch and try again with nothing else in the batch.
*/
if (!brw_batch_has_aperture_space(brw, 0)) {
if (!check_aperture_failed_once) {
check_aperture_failed_once = true;
intel_batchbuffer_reset_to_saved(brw);
intel_batchbuffer_flush(brw);
goto retry;
} else {
int ret = intel_batchbuffer_flush(brw);
WARN_ONCE(ret == -ENOSPC,
"i965: blorp emit exceeded available aperture space\n");
}
}
if (unlikely(brw->always_flush_batch))
intel_batchbuffer_flush(brw);
/* We've smashed all state compared to what the normal 3D pipeline
* rendering tracks for GL.
*/
brw->ctx.NewDriverState |= BRW_NEW_BLORP;
brw->no_depth_or_stencil = !params->depth.enabled &&
!params->stencil.enabled;
brw->ib.index_size = -1;
if (params->dst.enabled)
brw_render_cache_set_add_bo(brw, params->dst.addr.buffer);
if (params->depth.enabled)
brw_render_cache_set_add_bo(brw, params->depth.addr.buffer);
if (params->stencil.enabled)
brw_render_cache_set_add_bo(brw, params->stencil.addr.buffer);
}
| 32.721854 | 79 | 0.676381 | [
"render",
"3d"
] |
bb949b6576c89562cbf56246190d0fd34d51d38d | 12,989 | c | C | lib/misc/dlo/dlo-font-mcufont.c | yogpstop/libwebsockets | ef19cb6635abc81fe92e1f8f7307dfaab346f127 | [
"Apache-2.0"
] | null | null | null | lib/misc/dlo/dlo-font-mcufont.c | yogpstop/libwebsockets | ef19cb6635abc81fe92e1f8f7307dfaab346f127 | [
"Apache-2.0"
] | null | null | null | lib/misc/dlo/dlo-font-mcufont.c | yogpstop/libwebsockets | ef19cb6635abc81fe92e1f8f7307dfaab346f127 | [
"Apache-2.0"
] | null | null | null | /*
* lws abstract display
*
* Copyright (C) 2013 Petteri Aimonen
* Copyright (C) 2019 - 2022 Andy Green <andy@warmcat.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* Display List Object: mcufont font
*
* The mcu decoding is rewritten from the mcufont implementation at
* https://github.com/mcufont/mcufont, which is licensed under MIT already,
* to use a stateful decoder.
*
* The decoder only brings in new compression codes when needed to produce more
* pixels on the line of the glyphs being decoded.
*/
#include <private-lib-core.h>
#include "private-lib-drivers-display-dlo.h"
#define DICT_START 24
#define REF_FILLZEROS 16
#define RLE_CODEMASK 0xC0
#define RLE_VALMASK 0x3F
#define RLE_ZEROS 0x00
#define RLE_64ZEROS 0x40
#define RLE_ONES 0x80
#define RLE_SHADE 0xC0
#define DICT_START7BIT 4
#define DICT_START6BIT 132
#define DICT_START5BIT 196
#define DICT_START4BIT 228
#define DICT_START3BIT 244
#define DICT_START2BIT 252
enum {
RS_IDLE,
RS_SKIP_PX,
RS_WRITE_PX,
RS_ALLZERO,
COMP = 0,
DICT1,
DICT1_CONT,
DICT2,
DICT3
};
typedef struct mcu_stack {
const uint8_t *dict;
int16_t dictlen;
int16_t runlen; /* for accumilation on DICT1 */
uint8_t byte;
uint8_t bitcount;
uint8_t state;
} mcu_stack_t;
typedef struct mcu_glyph {
lws_font_glyph_t fg;
const uint8_t *comp;
mcu_stack_t st[3];
int32_t runlen;
int8_t sp;
uint8_t runstate;
uint8_t alpha;
uint8_t code;
} mcu_glyph_t;
/* Get bit count for the "fill entries" */
static uint8_t
fillentry_bitcount(uint8_t index)
{
if (index >= DICT_START2BIT)
return 2;
else if (index >= DICT_START3BIT)
return 3;
else if (index >= DICT_START4BIT)
return 4;
else if (index >= DICT_START5BIT)
return 5;
else if (index >= DICT_START6BIT)
return 6;
else
return 7;
}
void
draw_px(lws_dlo_text_t *t, mcu_glyph_t *g)
{
lws_display_colour_t c = (lws_display_colour_t)((lws_display_colour_t)(g->alpha << 24) |
(lws_display_colour_t)((lws_display_colour_t)t->dlo.dc & 0xffffffu));
lws_colour_error_t *ce;
lws_fx_t t1, x;
int ex;
t1.whole = g->fg.x;
if (!g->alpha)
return;
t1.frac = 0;
lws_fx_add(&x, &g->fg.xpx, &t1);
#if 0
{ char b1[22], b2[22], b3[22];
lwsl_err("fadj %s = %s + %s\n",
lws_fx_string(&x, b1, sizeof(b1)),
lws_fx_string(&g->fg.xpx, b2, sizeof(b2)),
lws_fx_string(&g->fg.xorg, b3, sizeof(b3))); }
#endif
ex = x.whole;// - t->dlo.box.x.whole;
if (ex < 0 || ex >= t->dlo.box.w.whole) {
//lwsl_err("%s: ex %d (lim %d)\n", __func__, ex, t->dlo.box.w.whole);
return;
}
lws_fx_add(&x, &x, &g->fg.xorg);
ce = &t->nle[!(t->curr & 1)][ex];
lws_fx_add(&t1, &t->dlo.box.x, &x);
lws_surface_set_px(t->ic, t->line, t1.whole, &c, ce);
if (t->ic->type == LWSSURF_TRUECOLOR32)
return;
if (ex != t->dlo.box.w.whole - 1) {
dist_err(ce, &t->nle[!(t->curr & 1)][ex + 1], 7);
dist_err(ce, &t->nle[t->curr & 1][ex + 1], 1);
}
if (ex)
dist_err(ce, &t->nle[t->curr & 1][ex - 1], 3);
dist_err(ce, &t->nle[t->curr & 1][ex], 5);
}
static void
write_ref_codeword(mcu_glyph_t *g, const uint8_t *bf, uint8_t c)
{
uint32_t o, o1;
if (!c) {
g->runlen = 1;
g->runstate = RS_SKIP_PX;
return;
}
if (c <= 15) {
g->alpha = (uint8_t)(0x11 * c);
g->runlen = 1;
g->runstate = RS_WRITE_PX;
return;
}
if (c == REF_FILLZEROS) {
/* Fill with zeroes to end */
g->alpha = 0;
g->runlen = 1000000;
g->runstate = RS_WRITE_PX;
return;
}
if (c < DICT_START)
return;
if (c < DICT_START + lws_ser_ru32be(bf + MCUFO_COUNT_RLE_DICT)) {
/* write_rle_dictentry */
o1 = lws_ser_ru32be(bf + MCUFO_FOFS_DICT_OFS);
o = lws_ser_ru16be(bf + o1 + ((c - DICT_START) * 2));
g->st[(int)++g->sp].dictlen = (int16_t)(lws_ser_ru16be(bf + o1 +
((c - DICT_START + 1) * 2)) - o);
g->st[(int)g->sp].dict = bf + lws_ser_ru32be(bf + MCUFO_FOFS_DICT_DATA) + o;
g->st[(int)g->sp].state = DICT2;
return;
}
g->st[(int)++g->sp].bitcount = fillentry_bitcount(c);
g->st[(int)g->sp].byte = (uint8_t)(c - DICT_START7BIT);
g->st[(int)g->sp].state = DICT1;
g->runlen = 0;
}
static void
mcufont_next_code(mcu_glyph_t *g)
{
lws_dlo_text_t *t = lws_container_of(g->fg.list.owner, lws_dlo_text_t,
glyphs);
const uint8_t *bf = (const uint8_t *)t->font->data;
uint8_t c = *g->comp++;
uint32_t o, o1;
if (c < DICT_START + lws_ser_ru32be(&bf[MCUFO_COUNT_RLE_DICT]) ||
c >= DICT_START + lws_ser_ru32be(&bf[MCUFO_COUNT_REF_RLE_DICT])) {
write_ref_codeword(g, bf, c);
return;
}
/* write_ref_dictentry() */
o1 = lws_ser_ru32be(bf + MCUFO_FOFS_DICT_OFS);
o = lws_ser_ru16be(bf + o1 + ((c - DICT_START) * 2));
g->st[(int)++g->sp].dictlen = (int16_t)(lws_ser_ru16be(bf + o1 +
((c - DICT_START + 1) * 2)) - o);
g->st[(int)g->sp].dict = bf + lws_ser_ru32be(bf + MCUFO_FOFS_DICT_DATA) + o;
g->st[(int)g->sp].state = DICT3;
}
/* lookup and append a glyph for specific unicode to the text glyph list */
static uint32_t
font_mcufont_uniglyph_lookup(lws_dlo_text_t *text, uint32_t unicode)
{
const uint8_t *bf = (const uint8_t *)text->font->data,
*r = bf + lws_ser_ru32be(&bf[MCUFO_FOFS_CHAR_RANGE_TABLES]);
unsigned int n, i;
do {
for (n = 0; n < lws_ser_ru32be(
&bf[MCUFO_COUNT_CHAR_RANGE_TABLES]); n++) {
i = unicode - lws_ser_ru32be(r + 0);
if (unicode >= lws_ser_ru32be(r + 0) &&
i < lws_ser_ru32be(r + 4))
return lws_ser_ru32be(r + 0xc) +
lws_ser_ru16be(bf +
lws_ser_ru32be(r + 8) + (i * 2));
r += 16;
}
if (unicode == lws_ser_ru32be(&bf[MCUFO_UNICODE_FALLBACK]))
return 0;
unicode = lws_ser_ru32be(&bf[MCUFO_UNICODE_FALLBACK]);
} while (1);
}
static mcu_glyph_t *
font_mcufont_uniglyph(lws_dlo_text_t *text, uint32_t unicode)
{
const uint8_t *bf = (const uint8_t *)text->font->data;
uint32_t ofs;
mcu_glyph_t *g;
ofs = font_mcufont_uniglyph_lookup(text, unicode);
if (!ofs)
return NULL;
g = lws_zalloc(sizeof(*g), __func__);
if (!g)
return NULL;
g->comp = bf + ofs;
g->fg.cwidth.whole = *g->comp++;
g->fg.cwidth.frac = 0;
lws_dll2_add_tail(&g->fg.list, &text->glyphs);
return g;
}
int
lws_display_font_mcufont_getcwidth(lws_dlo_text_t *text, uint32_t unicode,
lws_fx_t *fx)
{
const uint8_t *bf = (const uint8_t *)text->font->data;
uint32_t ofs = font_mcufont_uniglyph_lookup(text, unicode);
if (!ofs)
return 1;
fx->whole = bf[ofs];
fx->frac = 0;
return 0;
}
lws_font_glyph_t *
lws_display_font_mcufont_image_glyph(lws_dlo_text_t *text, uint32_t unicode,
char attach)
{
const uint8_t *bf = (const uint8_t *)text->font->data;
mcu_glyph_t *g;
/* one text dlo has glyphs from all the same fonts and attributes */
if (!text->font_height) {
text->font_height = (int16_t)lws_ser_ru16be(&bf[MCUFO16_HEIGHT]);
text->font_y_baseline = (int16_t)(text->font_height -
lws_ser_ru16be(&bf[MCUFO16_BASELINE_Y]));
text->font_line_height = (int16_t)lws_ser_ru16be(&bf[MCUFO16_LINE_HEIGHT]);
}
lws_display_font_mcufont_getcwidth(text, unicode, &text->_cwidth);
if (!attach)
return NULL;
g = font_mcufont_uniglyph(text, unicode);
if (!g)
return NULL;
g->fg.height.whole = lws_ser_ru16be(bf + MCUFO16_HEIGHT);
g->fg.height.frac = 0;
return &g->fg;
}
void
lws_display_font_mcufont_render(const lws_surface_info_t *ic,
struct lws_dlo *dlo, const lws_box_t *origin,
lws_display_scalar curr, uint8_t *line,
lws_colour_error_t **nle)
{
lws_dlo_text_t *text = lws_container_of(dlo, lws_dlo_text_t, dlo);
const uint8_t *bf = (const uint8_t *)text->font->data;
lws_fx_t ax, ay, t, t1, t2, t3;
lws_colour_error_t ce;
mcu_glyph_t *g;
int s, e, yo;
uint8_t c, el;
lws_fx_add(&ax, &origin->x, &dlo->box.x);
lws_fx_add(&t, &ax, &dlo->box.w);
lws_fx_add(&ay, &origin->y, &dlo->box.y);
lws_fx_add(&t1, &ay, &dlo->box.h);
lws_fx_add(&t2, &ax, &text->bounding_box.w);
text->curr = curr;
text->ic = ic;
text->line = line;
text->nle = nle;
s = ax.whole;
e = lws_fx_roundup(&t2);
if (e <= 0)
return; /* wholly off to the left */
if (s >= ic->wh_px[0].whole)
return; /* wholly off to the right */
if (e >= ic->wh_px[0].whole)
e = ic->wh_px[0].whole;
/* figure out our y position inside the glyph bounding box */
yo = curr - ay.whole;
if (!yo) {
lws_display_dlo_text_attach_glyphs(text);
t3.whole = lws_ser_ru16be(bf + MCUFO16_BASELINE_X);
t3.frac = 0;
lws_start_foreach_dll(struct lws_dll2 *, d,
lws_dll2_get_head(&text->glyphs)) {
lws_font_glyph_t *fg = lws_container_of(d, lws_font_glyph_t, list);
lws_fx_sub(&fg->xpx, &fg->xpx, &t3);
fg->xorg = origin->x;
} lws_end_foreach_dll(d);
}
memset(&ce, 0, sizeof(ce));
lws_dlo_ensure_err_diff(dlo);
#if 0
{
uint32_t dc = 0xff0000ff;
int s1 = s;
/* from origin.x + dlo->box.x */
for (s1 = ax.whole; s1 < t2.whole; s1++)
lws_surface_set_px(ic, line, s1, &dc, &ce);
memset(&ce, 0, sizeof(ce));
}
#endif
lws_start_foreach_dll(struct lws_dll2 *, d,
lws_dll2_get_head(&text->glyphs)) {
lws_font_glyph_t *fg = lws_container_of(d, lws_font_glyph_t, list);
g = (mcu_glyph_t *)fg;
fg->x = 0;
while (yo < (int)fg->height.whole &&
fg->x < lws_ser_ru16be(bf + MCUFO16_WIDTH)) {
switch (g->runstate) {
case RS_IDLE:
switch (g->st[(int)g->sp].state) {
case COMP:
mcufont_next_code(g);
break;
case DICT1_CONT:
--g->sp; /* back to DICT1 after doing the skip */
g->runstate = RS_SKIP_PX;
g->runlen = 1;
continue;
case DICT1:
/* write_bin_codeword() states */
el = 0;
while (g->st[(int)g->sp].bitcount--) {
c = g->st[(int)g->sp].byte;
g->st[(int)g->sp].byte >>= 1;
if (c & 1)
g->st[(int)g->sp].runlen++;
else {
if (g->st[(int)g->sp].runlen) {
g->alpha = 255;
g->runstate = RS_WRITE_PX;
g->runlen = g->st[(int)g->sp].runlen;
g->st[(int)g->sp].runlen = 0;
g->st[(int)++g->sp].state = DICT1_CONT;
el = 1;
break;
}
g->runstate = RS_SKIP_PX;
g->runlen = 1;
el = 1;
break;
}
}
if (el)
continue;
/* back out of DICT1 */
if (!g->sp)
assert(0);
g->sp--;
if (g->st[(int)g->sp + 1].runlen) {
g->alpha = 255;
g->runstate = RS_WRITE_PX;
g->runlen = g->st[(int)g->sp + 1].runlen;
g->st[(int)g->sp + 1].runlen = 0;
continue;
}
break;
case DICT2: /* write_rle_dictentry */
c = (*g->st[(int)g->sp].dict++);
if (!--g->st[(int)g->sp].dictlen) {
if (!g->sp)
assert(0);
g->sp--;
}
if ((c & RLE_CODEMASK) == RLE_ZEROS) {
g->runstate = RS_SKIP_PX;
g->runlen = c & RLE_VALMASK;
continue;
}
if ((c & RLE_CODEMASK) == RLE_64ZEROS) {
g->runstate = RS_SKIP_PX;
g->runlen = ((c & RLE_VALMASK) + 1) * 64;
continue;
}
if ((c & RLE_CODEMASK) == RLE_ONES) {
g->alpha = 255;
g->runstate = RS_WRITE_PX;
g->runlen = (c & RLE_VALMASK) + 1;
continue;
}
if ((c & RLE_CODEMASK) == RLE_SHADE) {
g->alpha = (uint8_t)(((c & RLE_VALMASK) & 0xf) * 0x11);
g->runstate = RS_WRITE_PX;
g->runlen = ((c & RLE_VALMASK) >> 4) + 1;
continue;
}
break;
case DICT3:
c = *g->st[(int)g->sp].dict++;
if (!--g->st[(int)g->sp].dictlen) {
if (!g->sp)
assert(0);
g->sp--;
}
write_ref_codeword(g, bf, c);
break;
}
break;
case RS_SKIP_PX:
fg->x++;
if (--g->runlen)
break;
g->runstate = RS_IDLE;
break;
case RS_WRITE_PX:
if (g->alpha)
draw_px(text, g);
g->fg.x++;
if (--g->runlen)
break;
g->runstate = RS_IDLE;
break;
case RS_ALLZERO:
fg->x++;
if (--g->runlen)
break;
g->runstate = RS_IDLE;
break;
}
}
} lws_end_foreach_dll(d);
}
| 24.461394 | 89 | 0.62399 | [
"object"
] |
bb98666d0aeaa3d4b575e36e2b418f2aadb1a992 | 4,781 | h | C | MetaheuristicsCPP.Evaluations/Evaluation.h | kommar/metaheuristics-lab | 6fce305b1f347eae44ac615a474d96b497264141 | [
"MIT"
] | null | null | null | MetaheuristicsCPP.Evaluations/Evaluation.h | kommar/metaheuristics-lab | 6fce305b1f347eae44ac615a474d96b497264141 | [
"MIT"
] | null | null | null | MetaheuristicsCPP.Evaluations/Evaluation.h | kommar/metaheuristics-lab | 6fce305b1f347eae44ac615a474d96b497264141 | [
"MIT"
] | null | null | null | #pragma once
#include "Constraint.h"
#include <utility>
#include <vector>
using namespace Constraints;
using namespace std;
namespace Evaluations
{
template <typename TElement>
class IEvaluationProfile
{
public:
IEvaluationProfile() = default;
IEvaluationProfile(const IEvaluationProfile<TElement> &cOther) = delete;
IEvaluationProfile(IEvaluationProfile<TElement> &&cOther) = delete;
virtual ~IEvaluationProfile() = default;
virtual int iGetSize() = 0;
virtual IConstraint<TElement> &cGetConstraint() = 0;
IEvaluationProfile<TElement>& operator=(const IEvaluationProfile<TElement> &cOther) = delete;
IEvaluationProfile<TElement>& operator=(IEvaluationProfile<TElement> &&cOther) = delete;
};//class IEvaluationProfile
template <typename TElement, typename TResult>
class IEvaluation : public IEvaluationProfile<TElement>
{
public:
virtual TResult tEvaluate(vector<TElement> &vSolution) = 0;
virtual TResult &tGetMaxValue() = 0;
virtual vector<TResult*> &vGetOptimalParetoFront() = 0;
virtual long long iGetFFE() = 0;
};//class IEvaluation : public IEvaluationProfile<TElement>
template <typename TElement>
class IMultimodalEvaluation : public virtual IEvaluation<TElement, double>
{
public:
virtual int iGetNumberOfGlobalOptima() = 0;
virtual double dGetNicheRadius() = 0;
};//class IMultimodalEvaluation : public virtual IEvaluation<TElement, double>
template <typename TElement, typename TResult>
class CEvaluation : public virtual IEvaluation<TElement, TResult>
{
public:
CEvaluation(int iSize, TResult tMaxValue) : i_size(iSize), t_max_value(tMaxValue), i_ffe(0) { }
virtual ~CEvaluation()
{
for (size_t i = 0; i < v_optimal_pareto_front.size(); i++)
{
delete v_optimal_pareto_front[i];
}//for (size_t i = 0; i < v_optimal_pareto_front.size(); i++)
}//virtual ~CEvaluation()
virtual TResult tEvaluate(vector<TElement> &vSolution) final
{
TResult t_value = t_evaluate(vSolution);
i_ffe++;
return t_value;
}//virtual double dEvaluate(vector<TElement> &vSolution) final
virtual int iGetSize() { return i_size; }
virtual TResult &tGetMaxValue() { return t_max_value; }
virtual vector<TResult*> &vGetOptimalParetoFront() { return v_optimal_pareto_front; }
virtual long long iGetFFE() { return i_ffe; }
CEvaluation<TElement, TResult>& operator=(const CEvaluation<TElement, TResult> &cOther) = delete;
CEvaluation<TElement, TResult>& operator=(CEvaluation<TElement, TResult> &&cOther) = delete;
protected:
virtual TResult t_evaluate(vector<TElement> &vSolution) = 0;
void v_set_size(int iSize) { i_size = iSize; }
void v_set_max_value(TResult tMaxValue) { t_max_value = tMaxValue; }
vector<TResult*> v_optimal_pareto_front;
private:
int i_size;
TResult t_max_value;
long long i_ffe;
};//class CEvaluation : public virtual IEvaluation<TElement, TResult>
template <typename TElement, typename TResult>
class CProxyEvaluation : public virtual IEvaluation<TElement, TResult>
{
public:
CProxyEvaluation(IEvaluation<TElement, TResult> **ppcEvaluation)
: ppc_evaluation(ppcEvaluation)
{
}//CProxyEvaluation(IEvaluation<TElement, TResult> *ppcEvaluation)
virtual TResult tEvaluate(vector<TElement> &vSolution) { return (*ppc_evaluation)->tEvaluate(vSolution); }
virtual int iGetSize() { return (*ppc_evaluation)->iGetSize(); };
virtual TResult &tGetMaxValue() { return (*ppc_evaluation)->tGetMaxValue(); }
virtual vector<TResult*> &vGetOptimalParetoFront() { return (*ppc_evaluation)->vGetOptimalParetoFront(); }
virtual IConstraint<double> &cGetConstraint() { return (*ppc_evaluation)->cGetConstraint(); }
virtual long long iGetFFE() { return (*ppc_evaluation)->iGetFFE(); }
private:
IEvaluation<TElement, TResult> **ppc_evaluation;
};//class CProxyEvaluation : public virtual IEvaluation<TElement, TResult>
template <typename TElement>
class CVerticalScalingEvaluation : public CEvaluation<TElement, double>
{
public:
CVerticalScalingEvaluation(IEvaluation<TElement, double> &cEvaluation, double dFactor)
: CEvaluation<TElement, double>(cEvaluation.iGetSize(), dFactor * cEvaluation.tGetMaxValue()), c_evaluation(cEvaluation), d_factor(dFactor)
{
}//CVerticalScalingEvaluation(IEvaluation<TElement, double> &cEvaluation, double dFactor)
virtual IConstraint<TElement> &cGetConstraint() { return c_evaluation.cGetConstraint(); }
protected:
virtual double t_evaluate(vector<TElement> &vSolution)
{
return d_factor * c_evaluation.tEvaluate(vSolution);
}//virtual double t_evaluate(vector<TElement> &vSolution)
private:
IEvaluation<TElement, double> &c_evaluation;
double d_factor;
};//class CVerticalScalingEvaluation : public CEvaluation<TElement, double>
}//namespace Evaluations
| 32.52381 | 142 | 0.754236 | [
"vector"
] |
bb9b44bc826d1f7cb5e155214bb889bcfebaa5c4 | 4,150 | h | C | include/pyscience11/numpy/dual.h | yokaze/pyscience11 | b385505eaa470cb6d6c73e20a06751577cbec664 | [
"MIT"
] | 15 | 2018-09-10T07:40:20.000Z | 2021-06-04T07:00:40.000Z | include/pyscience11/numpy/dual.h | yokaze/pyscience11 | b385505eaa470cb6d6c73e20a06751577cbec664 | [
"MIT"
] | 3 | 2018-09-11T12:02:16.000Z | 2018-12-24T08:19:12.000Z | include/pyscience11/numpy/dual.h | yokaze/pyscience11 | b385505eaa470cb6d6c73e20a06751577cbec664 | [
"MIT"
] | 5 | 2018-08-31T06:07:40.000Z | 2021-02-23T12:06:05.000Z | //
// dual.h
// pyscience11
//
// Copyright (C) 2018 Rue Yokaze
// Distributed under the MIT License.
//
// This header is compatible with numpy 1.15.1.
//
#pragma once
#include <pybind11/pybind11.h>
namespace numpy11 {
namespace numpy {
class dual_module : public pybind11::module {
public:
using pybind11::module::module;
template <class... TArgs>
pybind11::object cholesky(TArgs&&... args)
{
return attr("cholesky")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object det(TArgs&&... args)
{
return attr("det")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object eig(TArgs&&... args)
{
return attr("eig")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object eigh(TArgs&&... args)
{
return attr("eigh")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object eigvals(TArgs&&... args)
{
return attr("eigvals")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object eigvalsh(TArgs&&... args)
{
return attr("eigvalsh")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object fft(TArgs&&... args)
{
return attr("fft")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object fft2(TArgs&&... args)
{
return attr("fft2")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object fftn(TArgs&&... args)
{
return attr("fftn")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object i0(TArgs&&... args)
{
return attr("i0")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object ifft(TArgs&&... args)
{
return attr("ifft")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object ifft2(TArgs&&... args)
{
return attr("ifft2")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object ifftn(TArgs&&... args)
{
return attr("ifftn")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object inv(TArgs&&... args)
{
return attr("inv")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object lstsq(TArgs&&... args)
{
return attr("lstsq")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object norm(TArgs&&... args)
{
return attr("norm")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object pinv(TArgs&&... args)
{
return attr("pinv")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object register_func(TArgs&&... args)
{
return attr("register_func")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object restore_all(TArgs&&... args)
{
return attr("restore_all")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object restore_func(TArgs&&... args)
{
return attr("restore_func")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object solve(TArgs&&... args)
{
return attr("solve")(std::forward<TArgs>(args)...);
}
template <class... TArgs>
pybind11::object svd(TArgs&&... args)
{
return attr("svd")(std::forward<TArgs>(args)...);
}
};
dual_module import_dual()
{
return pybind11::module::import("numpy.dual");
}
}
}
| 26.100629 | 71 | 0.499036 | [
"object"
] |
bba36f3ec98f2af0cb2341253d9086ff5d8f7691 | 7,963 | c | C | qemu/target/i386/whpx/whpx-apic.c | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 44 | 2022-03-16T08:32:31.000Z | 2022-03-31T16:02:35.000Z | qemu/target/i386/whpx/whpx-apic.c | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 1 | 2022-03-29T02:30:28.000Z | 2022-03-30T03:40:46.000Z | qemu/target/i386/whpx/whpx-apic.c | hyunjoy/scripts | 01114d3627730d695b5ebe61093c719744432ffa | [
"Apache-2.0"
] | 18 | 2022-03-19T04:41:04.000Z | 2022-03-31T03:32:12.000Z | /*
* WHPX platform APIC support
*
* Copyright (c) 2011 Siemens AG
*
* Authors:
* Jan Kiszka <jan.kiszka@siemens.com>
* John Starks <jostarks@microsoft.com>
*
* This work is licensed under the terms of the GNU GPL version 2.
* See the COPYING file in the top-level directory.
*/
#include "qemu/osdep.h"
#include "qemu-common.h"
#include "cpu.h"
#include "hw/i386/apic_internal.h"
#include "hw/i386/apic-msidef.h"
#include "hw/pci/msi.h"
#include "sysemu/hw_accel.h"
#include "sysemu/whpx.h"
#include "whpx-internal.h"
struct whpx_lapic_state {
struct {
uint32_t data;
uint32_t padding[3];
} fields[256];
};
static void whpx_put_apic_state(APICCommonState *s,
struct whpx_lapic_state *kapic)
{
int i;
memset(kapic, 0, sizeof(*kapic));
kapic->fields[0x2].data = s->id << 24;
kapic->fields[0x3].data = s->version | ((APIC_LVT_NB - 1) << 16);
kapic->fields[0x8].data = s->tpr;
kapic->fields[0xd].data = s->log_dest << 24;
kapic->fields[0xe].data = s->dest_mode << 28 | 0x0fffffff;
kapic->fields[0xf].data = s->spurious_vec;
for (i = 0; i < 8; i++) {
kapic->fields[0x10 + i].data = s->isr[i];
kapic->fields[0x18 + i].data = s->tmr[i];
kapic->fields[0x20 + i].data = s->irr[i];
}
kapic->fields[0x28].data = s->esr;
kapic->fields[0x30].data = s->icr[0];
kapic->fields[0x31].data = s->icr[1];
for (i = 0; i < APIC_LVT_NB; i++) {
kapic->fields[0x32 + i].data = s->lvt[i];
}
kapic->fields[0x38].data = s->initial_count;
kapic->fields[0x3e].data = s->divide_conf;
}
static void whpx_get_apic_state(APICCommonState *s,
struct whpx_lapic_state *kapic)
{
int i, v;
s->id = kapic->fields[0x2].data >> 24;
s->tpr = kapic->fields[0x8].data;
s->arb_id = kapic->fields[0x9].data;
s->log_dest = kapic->fields[0xd].data >> 24;
s->dest_mode = kapic->fields[0xe].data >> 28;
s->spurious_vec = kapic->fields[0xf].data;
for (i = 0; i < 8; i++) {
s->isr[i] = kapic->fields[0x10 + i].data;
s->tmr[i] = kapic->fields[0x18 + i].data;
s->irr[i] = kapic->fields[0x20 + i].data;
}
s->esr = kapic->fields[0x28].data;
s->icr[0] = kapic->fields[0x30].data;
s->icr[1] = kapic->fields[0x31].data;
for (i = 0; i < APIC_LVT_NB; i++) {
s->lvt[i] = kapic->fields[0x32 + i].data;
}
s->initial_count = kapic->fields[0x38].data;
s->divide_conf = kapic->fields[0x3e].data;
v = (s->divide_conf & 3) | ((s->divide_conf >> 1) & 4);
s->count_shift = (v + 1) & 7;
s->initial_count_load_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);
apic_next_timer(s, s->initial_count_load_time);
}
static void whpx_apic_set_base(APICCommonState *s, uint64_t val)
{
s->apicbase = val;
}
static void whpx_put_apic_base(CPUState *cpu, uint64_t val)
{
HRESULT hr;
WHV_REGISTER_VALUE reg_value = {.Reg64 = val};
WHV_REGISTER_NAME reg_name = WHvX64RegisterApicBase;
hr = whp_dispatch.WHvSetVirtualProcessorRegisters(
whpx_global.partition,
cpu->cpu_index,
®_name, 1,
®_value);
if (FAILED(hr)) {
error_report("WHPX: Failed to set MSR APIC base, hr=%08lx", hr);
}
}
static void whpx_apic_set_tpr(APICCommonState *s, uint8_t val)
{
s->tpr = val;
}
static uint8_t whpx_apic_get_tpr(APICCommonState *s)
{
return s->tpr;
}
static void whpx_apic_vapic_base_update(APICCommonState *s)
{
/* not implemented yet */
}
static void whpx_apic_put(CPUState *cs, run_on_cpu_data data)
{
APICCommonState *s = data.host_ptr;
struct whpx_lapic_state kapic;
HRESULT hr;
whpx_put_apic_base(CPU(s->cpu), s->apicbase);
whpx_put_apic_state(s, &kapic);
hr = whp_dispatch.WHvSetVirtualProcessorInterruptControllerState2(
whpx_global.partition,
cs->cpu_index,
&kapic,
sizeof(kapic));
if (FAILED(hr)) {
fprintf(stderr,
"WHvSetVirtualProcessorInterruptControllerState failed: %08lx\n",
hr);
abort();
}
}
void whpx_apic_get(DeviceState *dev)
{
APICCommonState *s = APIC_COMMON(dev);
CPUState *cpu = CPU(s->cpu);
struct whpx_lapic_state kapic;
HRESULT hr = whp_dispatch.WHvGetVirtualProcessorInterruptControllerState2(
whpx_global.partition,
cpu->cpu_index,
&kapic,
sizeof(kapic),
NULL);
if (FAILED(hr)) {
fprintf(stderr,
"WHvSetVirtualProcessorInterruptControllerState failed: %08lx\n",
hr);
abort();
}
whpx_get_apic_state(s, &kapic);
}
static void whpx_apic_post_load(APICCommonState *s)
{
run_on_cpu(CPU(s->cpu), whpx_apic_put, RUN_ON_CPU_HOST_PTR(s));
}
static void whpx_apic_external_nmi(APICCommonState *s)
{
}
static void whpx_send_msi(MSIMessage *msg)
{
uint64_t addr = msg->address;
uint32_t data = msg->data;
uint8_t dest = (addr & MSI_ADDR_DEST_ID_MASK) >> MSI_ADDR_DEST_ID_SHIFT;
uint8_t vector = (data & MSI_DATA_VECTOR_MASK) >> MSI_DATA_VECTOR_SHIFT;
uint8_t dest_mode = (addr >> MSI_ADDR_DEST_MODE_SHIFT) & 0x1;
uint8_t trigger_mode = (data >> MSI_DATA_TRIGGER_SHIFT) & 0x1;
uint8_t delivery = (data >> MSI_DATA_DELIVERY_MODE_SHIFT) & 0x7;
WHV_INTERRUPT_CONTROL interrupt = {
/* Values correspond to delivery modes */
.Type = delivery,
.DestinationMode = dest_mode ?
WHvX64InterruptDestinationModeLogical :
WHvX64InterruptDestinationModePhysical,
.TriggerMode = trigger_mode ?
WHvX64InterruptTriggerModeLevel : WHvX64InterruptTriggerModeEdge,
.Reserved = 0,
.Vector = vector,
.Destination = dest,
};
HRESULT hr = whp_dispatch.WHvRequestInterrupt(whpx_global.partition,
&interrupt, sizeof(interrupt));
if (FAILED(hr)) {
fprintf(stderr, "whpx: injection failed, MSI (%llx, %x) delivery: %d, "
"dest_mode: %d, trigger mode: %d, vector: %d, lost (%08lx)\n",
addr, data, delivery, dest_mode, trigger_mode, vector, hr);
}
}
static uint64_t whpx_apic_mem_read(void *opaque, hwaddr addr,
unsigned size)
{
return ~(uint64_t)0;
}
static void whpx_apic_mem_write(void *opaque, hwaddr addr,
uint64_t data, unsigned size)
{
MSIMessage msg = { .address = addr, .data = data };
whpx_send_msi(&msg);
}
static const MemoryRegionOps whpx_apic_io_ops = {
.read = whpx_apic_mem_read,
.write = whpx_apic_mem_write,
.endianness = DEVICE_NATIVE_ENDIAN,
};
static void whpx_apic_reset(APICCommonState *s)
{
/* Not used by WHPX. */
s->wait_for_sipi = 0;
run_on_cpu(CPU(s->cpu), whpx_apic_put, RUN_ON_CPU_HOST_PTR(s));
}
static void whpx_apic_realize(DeviceState *dev, Error **errp)
{
APICCommonState *s = APIC_COMMON(dev);
memory_region_init_io(&s->io_memory, OBJECT(s), &whpx_apic_io_ops, s,
"whpx-apic-msi", APIC_SPACE_SIZE);
msi_nonbroken = true;
}
static void whpx_apic_class_init(ObjectClass *klass, void *data)
{
APICCommonClass *k = APIC_COMMON_CLASS(klass);
k->realize = whpx_apic_realize;
k->reset = whpx_apic_reset;
k->set_base = whpx_apic_set_base;
k->set_tpr = whpx_apic_set_tpr;
k->get_tpr = whpx_apic_get_tpr;
k->post_load = whpx_apic_post_load;
k->vapic_base_update = whpx_apic_vapic_base_update;
k->external_nmi = whpx_apic_external_nmi;
k->send_msi = whpx_send_msi;
}
static const TypeInfo whpx_apic_info = {
.name = "whpx-apic",
.parent = TYPE_APIC_COMMON,
.instance_size = sizeof(APICCommonState),
.class_init = whpx_apic_class_init,
};
static void whpx_apic_register_types(void)
{
type_register_static(&whpx_apic_info);
}
type_init(whpx_apic_register_types)
| 28.237589 | 79 | 0.63682 | [
"object",
"vector"
] |
bba68d5deaf7672151830bb1beda9d5965858a68 | 9,316 | h | C | include/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.h | lukhnos/objclucene | 29c7189a0b30ab3d3dd4c8ed148235ee296128b7 | [
"MIT"
] | 9 | 2016-01-13T05:38:05.000Z | 2020-06-04T23:05:03.000Z | include/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.h | lukhnos/objclucene | 29c7189a0b30ab3d3dd4c8ed148235ee296128b7 | [
"MIT"
] | 4 | 2016-05-12T10:40:53.000Z | 2016-06-11T19:08:33.000Z | include/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.h | lukhnos/objclucene | 29c7189a0b30ab3d3dd4c8ed148235ee296128b7 | [
"MIT"
] | 5 | 2016-01-13T05:37:39.000Z | 2019-07-27T16:53:10.000Z | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: ./suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.java
//
#include "J2ObjC_header.h"
#pragma push_macro("INCLUDE_ALL_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder")
#ifdef RESTRICT_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder
#define INCLUDE_ALL_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder 0
#else
#define INCLUDE_ALL_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder 1
#endif
#undef RESTRICT_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder
#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif
#if !defined (OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder_) && (INCLUDE_ALL_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder || defined(INCLUDE_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder))
#define OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder_
@class OrgApacheLuceneSearchSuggestFstFSTCompletion;
@class OrgApacheLuceneUtilBytesRef;
@class OrgApacheLuceneUtilFstFST;
@protocol OrgApacheLuceneSearchSuggestFstBytesRefSorter;
/*!
@brief Finite state automata based implementation of "autocomplete" functionality.
<h2>Implementation details</h2>
<p>
The construction step in <code>finalize()</code> works as follows:
<ul>
<li>A set of input terms and their buckets is given.</li>
<li>All terms in the input are prefixed with a synthetic pseudo-character
(code) of the weight bucket the term fell into. For example a term
<code>abc</code> with a discretized weight equal '1' would become
<code>1abc</code>.</li>
<li>The terms are then sorted by their raw value of UTF-8 character values
(including the synthetic bucket code in front).</li>
<li>A finite state automaton (<code>FST</code>) is constructed from the input. The
root node has arcs labeled with all possible weights. We cache all these
arcs, highest-weight first.</li>
</ul>
<p>
At runtime, in <code>FSTCompletion.lookup(CharSequence, int)</code>,
the automaton is utilized as follows:
<ul>
<li>For each possible term weight encoded in the automaton (cached arcs from
the root above), starting with the highest one, we descend along the path of
the input key. If the key is not a prefix of a sequence in the automaton
(path ends prematurely), we exit immediately -- no completions.</li>
<li>Otherwise, we have found an internal automaton node that ends the key.
<b>The entire subautomaton (all paths) starting from this node form the key's
completions.</b> We start the traversal of this subautomaton. Every time we
reach a final state (arc), we add a single suggestion to the list of results
(the weight of this suggestion is constant and equal to the root path we
started from). The tricky part is that because automaton edges are sorted and
we scan depth-first, we can terminate the entire procedure as soon as we
collect enough suggestions the user requested.</li>
<li>In case the number of suggestions collected in the step above is still
insufficient, we proceed to the next (smaller) weight leaving the root node
and repeat the same algorithm again.</li>
</ul>
<h2>Runtime behavior and performance characteristic</h2>
The algorithm described above is optimized for finding suggestions to short
prefixes in a top-weights-first order. This is probably the most common use
case: it allows presenting suggestions early and sorts them by the global
frequency (and then alphabetically).
<p>
If there is an exact match in the automaton, it is returned first on the
results list (even with by-weight sorting).
<p>
Note that the maximum lookup time for <b>any prefix</b> is the time of
descending to the subtree, plus traversal of the subtree up to the number of
requested suggestions (because they are already presorted by weight on the
root level and alphabetically at any node level).
<p>
To order alphabetically only (no ordering by priorities), use identical term
weights for all terms. Alphabetical suggestions are returned even if
non-constant weights are used, but the algorithm for doing this is
suboptimal.
<p>
"alphabetically" in any of the documentation above indicates UTF-8
representation order, nothing else.
<p>
<b>NOTE</b>: the FST file format is experimental and subject to suddenly
change, requiring you to rebuild the FST suggest index.
- seealso: FSTCompletion
*/
@interface OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder : NSObject {
@public
/*!
@brief Finite state automaton encoding all the lookup terms.See class notes for
details.
*/
OrgApacheLuceneUtilFstFST *automaton_;
}
@property (readonly, class) jint DEFAULT_BUCKETS NS_SWIFT_NAME(DEFAULT_BUCKETS);
#pragma mark Public
/*!
@brief Creates an <code>FSTCompletion</code> with default options: 10 buckets, exact match
promoted to first position and <code>InMemorySorter</code> with a comparator obtained from
<code>BytesRef.getUTF8SortedAsUnicodeComparator()</code>.
*/
- (instancetype __nonnull)init;
/*!
@brief Creates an FSTCompletion with the specified options.
@param buckets The number of buckets for weight discretization. Buckets are used
in <code>add(BytesRef, int)</code>
and must be smaller than the number given here.
@param sorter<code>BytesRefSorter</code>
used for re-sorting input for the automaton. For large inputs, use on-disk sorting implementations. The sorter
is closed automatically in
<code>build()</code> if it implements <code>Closeable</code>
.
@param shareMaxTailLength Max shared suffix sharing length.
See the description of this parameter in
<code>Builder</code> 's constructor. In general, for very large inputs you'll want to construct a non-minimal
automaton which will be larger, but the construction will take far less ram.
For minimal automata, set it to
<code>Integer.MAX_VALUE</code> .
*/
- (instancetype __nonnull)initWithInt:(jint)buckets
withOrgApacheLuceneSearchSuggestFstBytesRefSorter:(id<OrgApacheLuceneSearchSuggestFstBytesRefSorter>)sorter
withInt:(jint)shareMaxTailLength;
/*!
@brief Appends a single suggestion and its weight to the internal buffers.
@param utf8 The suggestion (utf8 representation) to be added. The content is
copied and the object can be reused.
@param bucket The bucket to place this suggestion in. Must be non-negative and
smaller than the number of buckets passed in the constructor.
Higher numbers indicate suggestions that should be presented
before suggestions placed in smaller buckets.
*/
- (void)addWithOrgApacheLuceneUtilBytesRef:(OrgApacheLuceneUtilBytesRef *)utf8
withInt:(jint)bucket;
/*!
@brief Builds the final automaton from a list of added entries.This method may
take a longer while as it needs to build the automaton.
*/
- (OrgApacheLuceneSearchSuggestFstFSTCompletion *)build;
@end
J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder)
J2OBJC_FIELD_SETTER(OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder, automaton_, OrgApacheLuceneUtilFstFST *)
/*!
@brief Default number of buckets.
*/
inline jint OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder_get_DEFAULT_BUCKETS(void);
#define OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder_DEFAULT_BUCKETS 10
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder, DEFAULT_BUCKETS, jint)
FOUNDATION_EXPORT void OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder_init(OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder *self);
FOUNDATION_EXPORT OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder *new_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder_init(void) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder *create_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder_init(void);
FOUNDATION_EXPORT void OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder_initWithInt_withOrgApacheLuceneSearchSuggestFstBytesRefSorter_withInt_(OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder *self, jint buckets, id<OrgApacheLuceneSearchSuggestFstBytesRefSorter> sorter, jint shareMaxTailLength);
FOUNDATION_EXPORT OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder *new_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder_initWithInt_withOrgApacheLuceneSearchSuggestFstBytesRefSorter_withInt_(jint buckets, id<OrgApacheLuceneSearchSuggestFstBytesRefSorter> sorter, jint shareMaxTailLength) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder *create_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder_initWithInt_withOrgApacheLuceneSearchSuggestFstBytesRefSorter_withInt_(jint buckets, id<OrgApacheLuceneSearchSuggestFstBytesRefSorter> sorter, jint shareMaxTailLength);
J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder)
#endif
#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneSearchSuggestFstFSTCompletionBuilder")
| 49.291005 | 315 | 0.798411 | [
"object"
] |
bbacda4462ef07e678eac207ae79c7161e770888 | 1,633 | h | C | submissions/M3/lab3_aes_sw/edaduino/vp/include/periphs/uart_device.h | maanjum95/SynthesisDigitalSystems_Lab | afc942decf7595eb1557ff78074693de2eea1780 | [
"MIT"
] | null | null | null | submissions/M3/lab3_aes_sw/edaduino/vp/include/periphs/uart_device.h | maanjum95/SynthesisDigitalSystems_Lab | afc942decf7595eb1557ff78074693de2eea1780 | [
"MIT"
] | null | null | null | submissions/M3/lab3_aes_sw/edaduino/vp/include/periphs/uart_device.h | maanjum95/SynthesisDigitalSystems_Lab | afc942decf7595eb1557ff78074693de2eea1780 | [
"MIT"
] | null | null | null | /**
* @Author: sharif
* @Date: 2019-04-15T12:10:40+02:00
* @Email: uzair.sharif@tum.de
* @Filename: external_uart_device.h
* @Last modified by: sharif
* @Last modified time: 2019-04-15T12:10:51+02:00
* @Copyright: Copyright (c) 2019
Institute for Electronic Design Automation, TU Munich
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef __EXTERNAL_UART_DEVICE_H__
#define __EXTERNAL_UART_DEVICE_H__
#include "systemc"
#include "tlm_utils/simple_initiator_socket.h"
#include "tlm_utils/simple_target_socket.h"
class ExternalUARTDevice final : sc_core::sc_module {
SC_HAS_PROCESS(ExternalUARTDevice);
public:
tlm_utils::simple_target_socket<ExternalUARTDevice> sock_t_{"target_socket"};
tlm_utils::simple_initiator_socket<ExternalUARTDevice> sock_i_{
"initiator_socket"};
ExternalUARTDevice(sc_core::sc_module_name);
void b_transport(tlm::tlm_generic_payload&, sc_core::sc_time&);
private:
void sense_input();
int readFIFO(unsigned char* buf);
int writeFIFO(unsigned char* buf);
std::vector<char> inbuf_;
};
#endif
| 31.403846 | 79 | 0.767299 | [
"vector"
] |
bbaed9980c26c734fd5b5fd97c1e41325e25dda3 | 5,517 | h | C | modules/voxelman/library/voxel_library.h | Relintai/pandemonium_engine | 3de05db75a396b497f145411f71eb363572b38ae | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | modules/voxelman/library/voxel_library.h | Relintai/pandemonium_engine | 3de05db75a396b497f145411f71eb363572b38ae | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | modules/voxelman/library/voxel_library.h | Relintai/pandemonium_engine | 3de05db75a396b497f145411f71eb363572b38ae | [
"MIT",
"Apache-2.0",
"CC-BY-4.0",
"Unlicense"
] | null | null | null | #ifndef VOXEL_LIBRARY_H
#define VOXEL_LIBRARY_H
/*
Copyright (c) 2019-2020 Péter Magyar
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 "core/resource.h"
#include "core/math/rect2.h"
#include "scene/resources/material.h"
#include "../data/voxel_light.h"
#include "voxel_surface.h"
#include "../defines.h"
class VoxelMaterialCache;
class VoxelChunk;
class VoxelSurface;
class VoxelMesher;
class PackedScene;
#ifdef PROPS_PRESENT
class PropData;
#endif
class VoxelLibrary : public Resource {
GDCLASS(VoxelLibrary, Resource)
public:
enum {
MATERIAL_INDEX_VOXELS = 0,
MATERIAL_INDEX_LIQUID = 1,
MATERIAL_INDEX_PROP = 2,
};
public:
bool get_initialized() const;
void set_initialized(const bool value);
bool supports_caching();
virtual bool _supports_caching();
Ref<Material> material_get(const int index);
Ref<Material> material_lod_get(const int index);
void material_cache_get_key(Ref<VoxelChunk> chunk);
virtual void _material_cache_get_key(Ref<VoxelChunk> chunk);
Ref<VoxelMaterialCache> material_cache_get(const int key);
virtual Ref<VoxelMaterialCache> _material_cache_get(const int key);
void material_cache_unref(const int key);
virtual void _material_cache_unref(const int key);
void material_add(const Ref<Material> &value);
void material_set(const int index, const Ref<Material> &value);
void material_remove(const int index);
int material_get_num() const;
void materials_clear();
Vector<Variant> materials_get();
void materials_set(const Vector<Variant> &materials);
Ref<Material> liquid_material_get(const int index);
Ref<Material> liquid_material_lod_get(const int index);
void liquid_material_cache_get_key(Ref<VoxelChunk> chunk);
virtual void _liquid_material_cache_get_key(Ref<VoxelChunk> chunk);
Ref<VoxelMaterialCache> liquid_material_cache_get(const int key);
virtual Ref<VoxelMaterialCache> _liquid_material_cache_get(const int key);
void liquid_material_cache_unref(const int key);
virtual void _liquid_material_cache_unref(const int key);
void liquid_material_add(const Ref<Material> &value);
void liquid_material_set(const int index, const Ref<Material> &value);
void liquid_material_remove(const int index);
int liquid_material_get_num() const;
void liquid_materials_clear();
Vector<Variant> liquid_materials_get();
void liquid_materials_set(const Vector<Variant> &materials);
Ref<Material> prop_material_get(const int index);
Ref<Material> prop_material_lod_get(const int index);
void prop_material_cache_get_key(Ref<VoxelChunk> chunk);
virtual void _prop_material_cache_get_key(Ref<VoxelChunk> chunk);
Ref<VoxelMaterialCache> prop_material_cache_get(const int key);
virtual Ref<VoxelMaterialCache> _prop_material_cache_get(const int key);
void prop_material_cache_unref(const int key);
virtual void _prop_material_cache_unref(const int key);
void prop_material_add(const Ref<Material> &value);
void prop_material_set(const int index, const Ref<Material> &value);
void prop_material_remove(const int index);
int prop_material_get_num() const;
void prop_materials_clear();
Vector<Variant> prop_materials_get();
void prop_materials_set(const Vector<Variant> &materials);
virtual Ref<VoxelSurface> voxel_surface_get(const int index);
virtual void voxel_surface_add(Ref<VoxelSurface> value);
virtual void voxel_surface_set(const int index, Ref<VoxelSurface> value);
virtual void voxel_surface_remove(const int index);
virtual int voxel_surface_get_num() const;
virtual void voxel_surfaces_clear();
virtual Ref<PackedScene> scene_get(const int id);
virtual void scene_add(Ref<PackedScene> value);
virtual void scene_set(const int id, Ref<PackedScene> value);
virtual void scene_remove(const int id);
virtual int scene_get_num() const;
virtual void scenes_clear();
#ifdef PROPS_PRESENT
virtual Ref<PropData> prop_get(const int id);
virtual void prop_add(Ref<PropData> value);
virtual bool prop_has(const Ref<PropData> &value) const;
virtual void prop_set(const int id, Ref<PropData> value);
virtual void prop_remove(const int id);
virtual int prop_get_num() const;
virtual void props_clear();
virtual Rect2 get_prop_uv_rect(const Ref<Texture> &texture);
#endif
virtual void refresh_rects();
void setup_material_albedo(int material_index, Ref<Texture> texture);
VoxelLibrary();
~VoxelLibrary();
protected:
static void _bind_methods();
bool _initialized;
Vector<Ref<Material>> _materials;
Vector<Ref<Material>> _liquid_materials;
Vector<Ref<Material>> _prop_materials;
};
#endif // VOXEL_LIBRARY_H
| 34.267081 | 78 | 0.799347 | [
"vector"
] |
bbb97903df4ee46bb7c6ba7827d21aa5c72efbea | 5,615 | h | C | framework/tarscpp/util/include/util/tc_lock.h | hfcrwx/Tars-v2.4.20 | b0782b3fad556582470cddaa4416874126bd105c | [
"BSD-3-Clause"
] | null | null | null | framework/tarscpp/util/include/util/tc_lock.h | hfcrwx/Tars-v2.4.20 | b0782b3fad556582470cddaa4416874126bd105c | [
"BSD-3-Clause"
] | null | null | null | framework/tarscpp/util/include/util/tc_lock.h | hfcrwx/Tars-v2.4.20 | b0782b3fad556582470cddaa4416874126bd105c | [
"BSD-3-Clause"
] | null | null | null | /**
* Tencent is pleased to support the open source community by making Tars
* available.
*
* Copyright (C) 2016THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the
* License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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 _TC_LOCK_H
#define _TC_LOCK_H
#include <cerrno>
#include <stdexcept>
#include <string>
#include "util/tc_ex.h"
using namespace std;
namespace tars {
/////////////////////////////////////////////////
/**
* @file tc_lock.h
* @brief 锁类
* @brief Lock Class
*/
/////////////////////////////////////////////////
/**
* @brief 锁异常
* @brief Lock exception
*/
struct TC_Lock_Exception : public TC_Exception {
TC_Lock_Exception(const string& buffer) : TC_Exception(buffer){};
~TC_Lock_Exception() throw(){};
};
/**
* @brief 锁模板类其他具体锁配合使用,
* 构造时候加锁,析够的时候解锁
* @brief Lock template class with other specific locks,
* lock when construction, unlock when analysis is sufficient
*/
template <typename T>
class TC_LockT {
public:
/**
* @brief 构造函数,构造时枷锁
* @brief Constructor, flail when constructing
*
* @param mutex 锁对象
* @param mutex Lock Object
*/
TC_LockT(const T& mutex) : _mutex(mutex) {
_mutex.lock();
_acquired = true;
}
/**
* @brief 析构,析构时解锁
* @brief Destructor, unlock at destruct
*/
virtual ~TC_LockT() {
if (_acquired) {
_mutex.unlock();
}
}
/**
* @brief 上锁, 如果已经上锁,则抛出异常
* @brief Lock, throw an exception if already locked
*/
void acquire() const {
if (_acquired) {
throw TC_Lock_Exception("thread has locked!");
}
_mutex.lock();
_acquired = true;
}
/**
* @brief 尝试上锁.
* @brief Try to lock.
*
* @return 成功返回true,否则返回false
* @return If it is successful,return true,otherwise return false
*/
bool tryAcquire() const {
_acquired = _mutex.tryLock();
return _acquired;
}
/**
* @brief 释放锁, 如果没有上过锁, 则抛出异常
* @brief Release lock, throw exception if no lock is on
*/
void release() const {
if (!_acquired) {
throw TC_Lock_Exception("thread hasn't been locked!");
}
_mutex.unlock();
_acquired = false;
}
/**
* @brief 是否已经上锁.
* @brief Is locked or not
*
* @return 返回true已经上锁,否则返回false
* @return Returning true indicates that it is locked; otherwise returning
* false
*/
bool acquired() const { return _acquired; }
protected:
/**
* @brief 构造函数
* 用于锁尝试操作,与TC_LockT相似
* @brief Constructor
* For lock attempt operations, with TC_LockT Similarity
*
*/
TC_LockT(const T& mutex, bool) : _mutex(mutex) {
_acquired = _mutex.tryLock();
}
private:
// Not implemented; prevents accidental use.
TC_LockT(const TC_LockT&);
TC_LockT& operator=(const TC_LockT&);
protected:
/**
* 锁对象
* Lock object
*/
const T& _mutex;
/**
* 是否已经上锁
* Is it locked or not
*/
mutable bool _acquired;
};
/**
* @brief 尝试上锁
* @brief Attempt to lock
*/
template <typename T>
class TC_TryLockT : public TC_LockT<T> {
public:
TC_TryLockT(const T& mutex) : TC_LockT<T>(mutex, true) {}
};
/**
* @brief 空锁, 不做任何锁动作
* @brief Empty lock, no lock action
*/
class TC_EmptyMutex {
public:
/**
* @brief 写锁.
* @brief Write lock
*
* @return int, 0 正确
* @return int 0 right
*/
int lock() const { return 0; }
/**
* @brief 解写锁
* @brief Unlock
*/
int unlock() const { return 0; }
/**
* @brief 尝试解锁.
* @brief Try to unlock
*
* @return int, 0 正确
* @return int, 0 right
*/
bool trylock() const { return true; }
};
/**
* @brief 读写锁读锁模板类
* 构造时候加锁,析够的时候解锁
* @brief Read-Write Lock Read Lock Template Class
* Lock when construction, unlock when analysis is sufficient
*/
template <typename T>
class TC_RW_RLockT {
public:
/**
* @brief 构造函数,构造时枷锁
* @brief Constructor, flail when constructing
*
* @param lock 锁对象
* @param lock lock object
*/
TC_RW_RLockT(T& lock) : _rwLock(lock), _acquired(false) {
_rwLock.readLock();
_acquired = true;
}
/**
* @brief 析构时解锁
* @brief Unlock at destruct time
*/
~TC_RW_RLockT() {
if (_acquired) {
_rwLock.unReadLock();
}
}
private:
/**
*锁对象
*lock object
*/
const T& _rwLock;
/**
* 是否已经上锁
* Is it locked or not
*/
mutable bool _acquired;
TC_RW_RLockT(const TC_RW_RLockT&);
TC_RW_RLockT& operator=(const TC_RW_RLockT&);
};
template <typename T>
class TC_RW_WLockT {
public:
/**
* @brief 构造函数,构造时枷锁
* @brief Constructor, Constructive Flail
*
* @param lock 锁对象
* @param lock Lock Object
*/
TC_RW_WLockT(T& lock) : _rwLock(lock), _acquired(false) {
_rwLock.writeLock();
_acquired = true;
}
/**
* @brief 析构时解锁
* @brief Unlock at destruct time
*/
~TC_RW_WLockT() {
if (_acquired) {
_rwLock.unWriteLock();
}
}
private:
/**
*锁对象
*Lock Object
*/
const T& _rwLock;
/**
* 是否已经上锁
* Is it locked or not
*/
mutable bool _acquired;
TC_RW_WLockT(const TC_RW_WLockT&);
TC_RW_WLockT& operator=(const TC_RW_WLockT&);
};
}; // namespace tars
#endif
| 19.496528 | 80 | 0.616028 | [
"object"
] |
bbc05c1fb56d321cd20a208dda79ed22ce046b6d | 11,096 | h | C | aws-cpp-sdk-location/include/aws/location/model/ListDevicePositionsResponseEntry.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-location/include/aws/location/model/ListDevicePositionsResponseEntry.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-location/include/aws/location/model/ListDevicePositionsResponseEntry.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T12:02:58.000Z | 2021-11-09T12:02:58.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/location/LocationService_EXPORTS.h>
#include <aws/location/model/PositionalAccuracy.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSMap.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace LocationService
{
namespace Model
{
/**
* <p>Contains the tracker resource details.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/location-2020-11-19/ListDevicePositionsResponseEntry">AWS
* API Reference</a></p>
*/
class AWS_LOCATIONSERVICE_API ListDevicePositionsResponseEntry
{
public:
ListDevicePositionsResponseEntry();
ListDevicePositionsResponseEntry(Aws::Utils::Json::JsonView jsonValue);
ListDevicePositionsResponseEntry& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The accuracy of the device position.</p>
*/
inline const PositionalAccuracy& GetAccuracy() const{ return m_accuracy; }
/**
* <p>The accuracy of the device position.</p>
*/
inline bool AccuracyHasBeenSet() const { return m_accuracyHasBeenSet; }
/**
* <p>The accuracy of the device position.</p>
*/
inline void SetAccuracy(const PositionalAccuracy& value) { m_accuracyHasBeenSet = true; m_accuracy = value; }
/**
* <p>The accuracy of the device position.</p>
*/
inline void SetAccuracy(PositionalAccuracy&& value) { m_accuracyHasBeenSet = true; m_accuracy = std::move(value); }
/**
* <p>The accuracy of the device position.</p>
*/
inline ListDevicePositionsResponseEntry& WithAccuracy(const PositionalAccuracy& value) { SetAccuracy(value); return *this;}
/**
* <p>The accuracy of the device position.</p>
*/
inline ListDevicePositionsResponseEntry& WithAccuracy(PositionalAccuracy&& value) { SetAccuracy(std::move(value)); return *this;}
/**
* <p>The ID of the device for this position.</p>
*/
inline const Aws::String& GetDeviceId() const{ return m_deviceId; }
/**
* <p>The ID of the device for this position.</p>
*/
inline bool DeviceIdHasBeenSet() const { return m_deviceIdHasBeenSet; }
/**
* <p>The ID of the device for this position.</p>
*/
inline void SetDeviceId(const Aws::String& value) { m_deviceIdHasBeenSet = true; m_deviceId = value; }
/**
* <p>The ID of the device for this position.</p>
*/
inline void SetDeviceId(Aws::String&& value) { m_deviceIdHasBeenSet = true; m_deviceId = std::move(value); }
/**
* <p>The ID of the device for this position.</p>
*/
inline void SetDeviceId(const char* value) { m_deviceIdHasBeenSet = true; m_deviceId.assign(value); }
/**
* <p>The ID of the device for this position.</p>
*/
inline ListDevicePositionsResponseEntry& WithDeviceId(const Aws::String& value) { SetDeviceId(value); return *this;}
/**
* <p>The ID of the device for this position.</p>
*/
inline ListDevicePositionsResponseEntry& WithDeviceId(Aws::String&& value) { SetDeviceId(std::move(value)); return *this;}
/**
* <p>The ID of the device for this position.</p>
*/
inline ListDevicePositionsResponseEntry& WithDeviceId(const char* value) { SetDeviceId(value); return *this;}
/**
* <p>The last known device position. Empty if no positions currently stored.</p>
*/
inline const Aws::Vector<double>& GetPosition() const{ return m_position; }
/**
* <p>The last known device position. Empty if no positions currently stored.</p>
*/
inline bool PositionHasBeenSet() const { return m_positionHasBeenSet; }
/**
* <p>The last known device position. Empty if no positions currently stored.</p>
*/
inline void SetPosition(const Aws::Vector<double>& value) { m_positionHasBeenSet = true; m_position = value; }
/**
* <p>The last known device position. Empty if no positions currently stored.</p>
*/
inline void SetPosition(Aws::Vector<double>&& value) { m_positionHasBeenSet = true; m_position = std::move(value); }
/**
* <p>The last known device position. Empty if no positions currently stored.</p>
*/
inline ListDevicePositionsResponseEntry& WithPosition(const Aws::Vector<double>& value) { SetPosition(value); return *this;}
/**
* <p>The last known device position. Empty if no positions currently stored.</p>
*/
inline ListDevicePositionsResponseEntry& WithPosition(Aws::Vector<double>&& value) { SetPosition(std::move(value)); return *this;}
/**
* <p>The last known device position. Empty if no positions currently stored.</p>
*/
inline ListDevicePositionsResponseEntry& AddPosition(double value) { m_positionHasBeenSet = true; m_position.push_back(value); return *this; }
/**
* <p>The properties associated with the position.</p>
*/
inline const Aws::Map<Aws::String, Aws::String>& GetPositionProperties() const{ return m_positionProperties; }
/**
* <p>The properties associated with the position.</p>
*/
inline bool PositionPropertiesHasBeenSet() const { return m_positionPropertiesHasBeenSet; }
/**
* <p>The properties associated with the position.</p>
*/
inline void SetPositionProperties(const Aws::Map<Aws::String, Aws::String>& value) { m_positionPropertiesHasBeenSet = true; m_positionProperties = value; }
/**
* <p>The properties associated with the position.</p>
*/
inline void SetPositionProperties(Aws::Map<Aws::String, Aws::String>&& value) { m_positionPropertiesHasBeenSet = true; m_positionProperties = std::move(value); }
/**
* <p>The properties associated with the position.</p>
*/
inline ListDevicePositionsResponseEntry& WithPositionProperties(const Aws::Map<Aws::String, Aws::String>& value) { SetPositionProperties(value); return *this;}
/**
* <p>The properties associated with the position.</p>
*/
inline ListDevicePositionsResponseEntry& WithPositionProperties(Aws::Map<Aws::String, Aws::String>&& value) { SetPositionProperties(std::move(value)); return *this;}
/**
* <p>The properties associated with the position.</p>
*/
inline ListDevicePositionsResponseEntry& AddPositionProperties(const Aws::String& key, const Aws::String& value) { m_positionPropertiesHasBeenSet = true; m_positionProperties.emplace(key, value); return *this; }
/**
* <p>The properties associated with the position.</p>
*/
inline ListDevicePositionsResponseEntry& AddPositionProperties(Aws::String&& key, const Aws::String& value) { m_positionPropertiesHasBeenSet = true; m_positionProperties.emplace(std::move(key), value); return *this; }
/**
* <p>The properties associated with the position.</p>
*/
inline ListDevicePositionsResponseEntry& AddPositionProperties(const Aws::String& key, Aws::String&& value) { m_positionPropertiesHasBeenSet = true; m_positionProperties.emplace(key, std::move(value)); return *this; }
/**
* <p>The properties associated with the position.</p>
*/
inline ListDevicePositionsResponseEntry& AddPositionProperties(Aws::String&& key, Aws::String&& value) { m_positionPropertiesHasBeenSet = true; m_positionProperties.emplace(std::move(key), std::move(value)); return *this; }
/**
* <p>The properties associated with the position.</p>
*/
inline ListDevicePositionsResponseEntry& AddPositionProperties(const char* key, Aws::String&& value) { m_positionPropertiesHasBeenSet = true; m_positionProperties.emplace(key, std::move(value)); return *this; }
/**
* <p>The properties associated with the position.</p>
*/
inline ListDevicePositionsResponseEntry& AddPositionProperties(Aws::String&& key, const char* value) { m_positionPropertiesHasBeenSet = true; m_positionProperties.emplace(std::move(key), value); return *this; }
/**
* <p>The properties associated with the position.</p>
*/
inline ListDevicePositionsResponseEntry& AddPositionProperties(const char* key, const char* value) { m_positionPropertiesHasBeenSet = true; m_positionProperties.emplace(key, value); return *this; }
/**
* <p>The timestamp at which the device position was determined. Uses <a
* href="https://www.iso.org/iso-8601-date-and-time-format.html"> ISO 8601</a>
* format: <code>YYYY-MM-DDThh:mm:ss.sssZ</code>.</p>
*/
inline const Aws::Utils::DateTime& GetSampleTime() const{ return m_sampleTime; }
/**
* <p>The timestamp at which the device position was determined. Uses <a
* href="https://www.iso.org/iso-8601-date-and-time-format.html"> ISO 8601</a>
* format: <code>YYYY-MM-DDThh:mm:ss.sssZ</code>.</p>
*/
inline bool SampleTimeHasBeenSet() const { return m_sampleTimeHasBeenSet; }
/**
* <p>The timestamp at which the device position was determined. Uses <a
* href="https://www.iso.org/iso-8601-date-and-time-format.html"> ISO 8601</a>
* format: <code>YYYY-MM-DDThh:mm:ss.sssZ</code>.</p>
*/
inline void SetSampleTime(const Aws::Utils::DateTime& value) { m_sampleTimeHasBeenSet = true; m_sampleTime = value; }
/**
* <p>The timestamp at which the device position was determined. Uses <a
* href="https://www.iso.org/iso-8601-date-and-time-format.html"> ISO 8601</a>
* format: <code>YYYY-MM-DDThh:mm:ss.sssZ</code>.</p>
*/
inline void SetSampleTime(Aws::Utils::DateTime&& value) { m_sampleTimeHasBeenSet = true; m_sampleTime = std::move(value); }
/**
* <p>The timestamp at which the device position was determined. Uses <a
* href="https://www.iso.org/iso-8601-date-and-time-format.html"> ISO 8601</a>
* format: <code>YYYY-MM-DDThh:mm:ss.sssZ</code>.</p>
*/
inline ListDevicePositionsResponseEntry& WithSampleTime(const Aws::Utils::DateTime& value) { SetSampleTime(value); return *this;}
/**
* <p>The timestamp at which the device position was determined. Uses <a
* href="https://www.iso.org/iso-8601-date-and-time-format.html"> ISO 8601</a>
* format: <code>YYYY-MM-DDThh:mm:ss.sssZ</code>.</p>
*/
inline ListDevicePositionsResponseEntry& WithSampleTime(Aws::Utils::DateTime&& value) { SetSampleTime(std::move(value)); return *this;}
private:
PositionalAccuracy m_accuracy;
bool m_accuracyHasBeenSet;
Aws::String m_deviceId;
bool m_deviceIdHasBeenSet;
Aws::Vector<double> m_position;
bool m_positionHasBeenSet;
Aws::Map<Aws::String, Aws::String> m_positionProperties;
bool m_positionPropertiesHasBeenSet;
Aws::Utils::DateTime m_sampleTime;
bool m_sampleTimeHasBeenSet;
};
} // namespace Model
} // namespace LocationService
} // namespace Aws
| 39.487544 | 227 | 0.687455 | [
"vector",
"model"
] |
bbc3999e0cba8b8528efe26920b23d70f1a9f32e | 1,875 | h | C | chrome/browser/ui/views/eye_dropper/eye_dropper_win.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/views/eye_dropper/eye_dropper_win.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/views/eye_dropper/eye_dropper_win.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_EYE_DROPPER_EYE_DROPPER_WIN_H_
#define CHROME_BROWSER_UI_VIEWS_EYE_DROPPER_EYE_DROPPER_WIN_H_
#include <memory>
#include "base/optional.h"
#include "base/timer/timer.h"
#include "content/public/browser/eye_dropper.h"
#include "content/public/browser/eye_dropper_listener.h"
#include "content/public/browser/render_frame_host.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/widget/widget_delegate.h"
class EyeDropperWin : public content::EyeDropper,
public views::WidgetDelegateView {
public:
EyeDropperWin(content::RenderFrameHost* frame,
content::EyeDropperListener* listener);
EyeDropperWin(const EyeDropperWin&) = delete;
EyeDropperWin& operator=(const EyeDropperWin&) = delete;
~EyeDropperWin() override;
protected:
// views::WidgetDelegateView:
void OnPaint(gfx::Canvas* canvas) override;
void WindowClosing() override;
void DeleteDelegate() override;
ui::ModalType GetModalType() const override;
void OnWidgetMove() override;
private:
class PreEventDispatchHandler;
class ViewPositionHandler;
class ScreenCapturer;
// Moves the view to the cursor position.
void UpdatePosition();
// Handles color selection and notifies the listener.
void OnColorSelected();
content::RenderFrameHost* render_frame_host_;
// Receives the color selection.
content::EyeDropperListener* listener_;
std::unique_ptr<PreEventDispatchHandler> pre_dispatch_handler_;
std::unique_ptr<ViewPositionHandler> view_position_handler_;
std::unique_ptr<ScreenCapturer> screen_capturer_;
base::Optional<SkColor> selected_color_;
};
#endif // CHROME_BROWSER_UI_VIEWS_EYE_DROPPER_EYE_DROPPER_WIN_H_
| 32.327586 | 73 | 0.7776 | [
"geometry"
] |
bbd65b956783aeace5f34d1c0d3bc12455502218 | 17,324 | h | C | xls/ir/python/wrapper_types.h | hafixo/xls | 21009ec2165d04d0037d9cf3583b207949ef7a6d | [
"Apache-2.0"
] | null | null | null | xls/ir/python/wrapper_types.h | hafixo/xls | 21009ec2165d04d0037d9cf3583b207949ef7a6d | [
"Apache-2.0"
] | null | null | null | xls/ir/python/wrapper_types.h | hafixo/xls | 21009ec2165d04d0037d9cf3583b207949ef7a6d | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The XLS Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef XLS_IR_PYTHON_WRAPPER_TYPES_H_
#define XLS_IR_PYTHON_WRAPPER_TYPES_H_
#include <memory>
#include <type_traits>
#include "absl/status/statusor.h"
#include "pybind11/cast.h"
#include "xls/ir/function.h"
#include "xls/ir/function_builder.h"
#include "xls/ir/package.h"
#include "xls/ir/type.h"
namespace xls {
// A number of C++ IR types contain unowning Package* pointers. In order to
// ensure memory safety, all Python references to such types values are wrapped
// in objects that contain not just the unowning pointer but but also a
// shared_ptr to its Package.
//
// Unfortunately, this wrapping causes quite a lot of friction in defining the
// pybind11 bindings. This file contains type definitions and helpers for this.
// The main helper function is PyBind, which in most cases makes it possible to
// write pybind11 wrapper declarations mostly as usual even for objects that are
// wrapped, and when parameters and return values are of types that need to be
// wrapped.
// Classes that are a wrapper that contains both an unowning pointer and an
// owning pointer should inherit this class to signal to helper functions that
// it is such a wrapper.
//
// Subclasses of this class should have a T& deref() const method that returns
// the wrapped unowned object.
//
// Subclasses of this class are expected to be copyable.
struct PyHolder {};
// Base class for wrapper objects that have objects that are owned by Package.
// (BValue and FunctionHolder need more than just a shared_ptr to Package so
// they don't use this.)
template <typename T>
class PointerOwnedByPackage : public PyHolder {
public:
PointerOwnedByPackage(T* pointer, const std::shared_ptr<Package>& owner)
: pointer_(pointer), owner_(owner) {}
T& deref() const { return *pointer_; }
const std::shared_ptr<Package>& package() { return owner_; }
private:
T* pointer_;
std::shared_ptr<Package> owner_;
};
// Abstract base class for wrappers of xls::Type objects. pybind11 expects to be
// able to do static_cast up casts for types that are declared to inherit each
// other so it is necessary that the wrapper class hierarchy mirrors the
// hierarchy of the wrapped objects.
class TypeHolder : public PointerOwnedByPackage<Type> {
protected:
using PointerOwnedByPackage::PointerOwnedByPackage;
};
// Wrapper for BitsType* pointers.
struct BitsTypeHolder : public TypeHolder {
BitsTypeHolder(BitsType* pointer, const std::shared_ptr<Package>& owner)
: TypeHolder(pointer, owner) {}
BitsType& deref() const {
return static_cast<BitsType&>(TypeHolder::deref());
}
};
// Wrapper for ArrayType* pointers.
struct ArrayTypeHolder : public TypeHolder {
ArrayTypeHolder(ArrayType* pointer, const std::shared_ptr<Package>& owner)
: TypeHolder(pointer, owner) {}
ArrayType& deref() const {
return static_cast<ArrayType&>(TypeHolder::deref());
}
};
// Wrapper for TupleType* pointers.
struct TupleTypeHolder : public TypeHolder {
TupleTypeHolder(TupleType* pointer, const std::shared_ptr<Package>& owner)
: TypeHolder(pointer, owner) {}
TupleType& deref() const {
return static_cast<TupleType&>(TypeHolder::deref());
}
};
// Wrapper for FunctionType* pointers.
struct FunctionTypeHolder : public PointerOwnedByPackage<FunctionType> {
using PointerOwnedByPackage::PointerOwnedByPackage;
};
// Wrapper for Function* pointers.
struct FunctionHolder : public PointerOwnedByPackage<Function> {
using PointerOwnedByPackage::PointerOwnedByPackage;
};
// Wrapper for Package objects.
//
// A Package can be referred to through unowned pointers by other objects like
// FunctionBuilder and Type. For this reason, it is held in a shared_ptr, so
// that it can be kept alive for as long as any Python object refers to it, even
// if there is no longer a direct reference to the Package.
//
// Using PointerOwnedByPackage makes this object contain a Package* and a
// std::shared_ptr<Package> which is a little bit weird, but it allows reusing
// helper functions that work on PointerOwnedByPackage.
struct PackageHolder : public PointerOwnedByPackage<Package> {
using PointerOwnedByPackage::PointerOwnedByPackage;
};
// Wrapper for BValue objects.
//
// A BValue C++ object has unowned pointers both to its Package and to its
// FunctionBuilder. To keep them alive for as long as the Python reference
// exists, this holder keeps shared_ptrs to the Package and FunctionBuilder.
class BValueHolder : public PyHolder {
public:
BValueHolder(const BValue& value, const std::shared_ptr<Package>& package,
const std::shared_ptr<FunctionBuilder>& builder)
: value_(std::make_shared<BValue>(value)),
package_(package),
builder_(builder) {}
const std::shared_ptr<BValue>& value() const { return value_; }
const std::shared_ptr<Package>& package() const { return package_; }
const std::shared_ptr<FunctionBuilder>& builder() const { return builder_; }
BValue& deref() const { return *value_; }
private:
std::shared_ptr<BValue> value_;
std::shared_ptr<Package> package_;
std::shared_ptr<FunctionBuilder> builder_;
};
// Wrapper for FunctionBuilder objects.
//
// A FunctionBuilder has unowned pointers to the belonging package. To keep the
// Package alive for as long as the Python reference exists, it is held by
// shared_ptr here. Furthermore, since FunctionBuilder can be referred to by
// other BValue objects, it itself is kept in a shared_ptr too.
class FunctionBuilderHolder : public PyHolder {
public:
FunctionBuilderHolder(absl::string_view name, PackageHolder package)
: package_(package.package()),
builder_(std::make_shared<FunctionBuilder>(name, &package.deref())) {}
FunctionBuilderHolder(const std::shared_ptr<Package>& package,
const std::shared_ptr<FunctionBuilder>& builder)
: package_(package), builder_(builder) {}
FunctionBuilder& deref() const { return *builder_; }
const std::shared_ptr<Package>& package() const { return package_; }
const std::shared_ptr<FunctionBuilder>& builder() const { return builder_; }
private:
std::shared_ptr<Package> package_;
std::shared_ptr<FunctionBuilder> builder_;
};
// PyHolderTypeTraits is a template that defines a mapping from a wrapped type
// (for example BitsType) to its holder type (in this case BitsTypeHolder).
template <typename T>
struct PyHolderTypeTraits;
template <>
struct PyHolderTypeTraits<Type> {
using Holder = TypeHolder;
};
template <>
struct PyHolderTypeTraits<BitsType> {
using Holder = BitsTypeHolder;
};
template <>
struct PyHolderTypeTraits<ArrayType> {
using Holder = ArrayTypeHolder;
};
template <>
struct PyHolderTypeTraits<TupleType> {
using Holder = TupleTypeHolder;
};
template <>
struct PyHolderTypeTraits<FunctionType> {
using Holder = FunctionTypeHolder;
};
template <>
struct PyHolderTypeTraits<Function> {
using Holder = FunctionHolder;
};
template <>
struct PyHolderTypeTraits<Package> {
using Holder = PackageHolder;
};
template <>
struct PyHolderTypeTraits<BValue> {
using Holder = BValueHolder;
};
template <>
struct PyHolderTypeTraits<FunctionBuilder> {
using Holder = FunctionBuilderHolder;
};
// PyHolderType<T> finds the wrapper type of a given type. For example,
// PyHolderType<BitsType> is BitsTypeHolder.
template <typename T>
using PyHolderType = typename PyHolderTypeTraits<T>::Holder;
// Takes something that potentially should be wrapped by a holder object (for
// example BValue) and wraps it in a holder object (for example a BValueHolder).
// The second parameter is a PyHolder object that is used to get the owning
// pointers required to construct the holder object.
//
// If T is not a type that needs to be wrapped, this function returns `value`.
//
// This function is used by PyWrap on return values of wrapped methods.
//
// Making PyWrap able to wrap a new return type is done by adding a new overload
// of the WrapInPyHolder function.
template <typename T, typename Holder>
auto WrapInPyHolderIfHolderExists(T&& value, Holder* holder)
-> decltype(WrapInPyHolder(std::forward<T>(value), holder)) {
return WrapInPyHolder(std::forward<T>(value), holder);
}
template <typename T>
auto WrapInPyHolderIfHolderExists(T&& value, ...) {
return std::forward<T>(value);
}
// Tells PyWrap how to wrap BValue return values, see
// WrapInPyHolderIfHolderExists.
static inline BValueHolder WrapInPyHolder(const BValue& value,
FunctionBuilderHolder* holder) {
return BValueHolder(value, holder->package(), holder->builder());
}
// Tells PyWrap how to wrap FunctionBuilder return values from BValue methods,
// see WrapInPyHolderIfHolderExists.
static inline FunctionBuilderHolder WrapInPyHolder(FunctionBuilder* builder,
BValueHolder* holder) {
return FunctionBuilderHolder(holder->package(), holder->builder());
}
// Tells PyWrap how to wrap return values from BValue methods of pointers owned
// by Package, see WrapInPyHolderIfHolderExists.
template <typename T>
PyHolderType<T> WrapInPyHolder(T* value, BValueHolder* holder) {
return PyHolderType<T>(value, holder->package());
}
// Tells PyWrap how to wrap return values of pointers owned by Package, see
// WrapInPyHolderIfHolderExists.
template <typename T, typename U>
PyHolderType<T> WrapInPyHolder(T* value, PointerOwnedByPackage<U>* holder) {
return PyHolderType<T>(value, holder->package());
}
// Tells PyWrap how to wrap absl::StatusOr return values of types that need to
// be wrapped, see WrapInPyHolderIfHolderExists.
template <typename T, typename Holder>
absl::StatusOr<PyHolderType<T>> WrapInPyHolder(const absl::StatusOr<T*>& value,
Holder* holder) {
if (value.ok()) {
return PyHolderType<T>(value.value(), holder->package());
} else {
return value.status();
}
}
// HasPyHolderType<T> is true when T is a type that has a PyHolder type.
template <typename, typename = std::void_t<>>
struct HasPyHolderTypeHelper : std::false_type {};
template <typename T>
struct HasPyHolderTypeHelper<
T, std::void_t<typename PyHolderTypeTraits<T>::Holder>>
: public std::true_type {};
template <typename T>
constexpr bool HasPyHolderType = HasPyHolderTypeHelper<T>::value;
static_assert(!HasPyHolderType<int>);
static_assert(HasPyHolderType<BValue>);
// WrappedFunctionParameterTraits<T> defines how PyWrap handles parameters of
// functions it wraps: For a function void Foo(T t), the wrapped function will
// be of type void (*)(WrappedFunctionParameterTraits<T>::WrappedType t).
//
// PyWrap then uses WrappedFunctionParameterTraits<T>::Unwrap(t) to extract the
// potentially wrapped underlying type to pass it to the wrapped function.
//
// This primary template specifies how PyWrap behaves for types that are not
// wrapped. Partial specializations define the behavior for wrapped types.
template <typename T, typename = std::void_t<>>
struct WrappedFunctionParameterTraits {
using WrappedType = T;
static T Unwrap(T&& t) { return std::move(t); }
};
// WrappedFunctionParameterTraits for absl::Spans of types that have wrapper
// types.
template <typename T>
struct WrappedFunctionParameterTraits<absl::Span<const T>,
std::enable_if_t<HasPyHolderType<T>>> {
using WrappedType = absl::Span<const PyHolderType<T>>;
static std::vector<T> Unwrap(const WrappedType& t) {
std::vector<T> values;
values.reserve(t.size());
for (auto& value : t) {
values.push_back(value.deref());
}
return values;
}
};
// WrappedFunctionParameterTraits for absl::optionals of types that have wrapper
// types.
template <typename T>
struct WrappedFunctionParameterTraits<absl::optional<T>,
std::enable_if_t<HasPyHolderType<T>>> {
using WrappedType = absl::optional<PyHolderType<T>>;
static absl::optional<T> Unwrap(const WrappedType& t) {
if (t) {
return t->deref();
} else {
return {};
}
}
};
// WrappedFunctionParameterTraits for types that have wrapper types.
template <typename T>
struct WrappedFunctionParameterTraits<
T, std::enable_if_t<HasPyHolderType<std::remove_pointer_t<T>>>> {
private:
using NonPointerType = PyHolderType<std::remove_pointer_t<T>>;
public:
using WrappedType =
std::conditional_t<std::is_pointer_v<T>, NonPointerType*, NonPointerType>;
static T Unwrap(const WrappedType& t) {
if constexpr (std::is_pointer_v<T>) {
return &t->deref();
} else {
return t.deref();
}
}
};
// Helper function with shared logic for the two PyWrap overloads that take
// pointers to member methods (the const and the non-const variant).
template <typename MethodPointer, typename ReturnT, typename T,
typename... Args>
auto PyWrapHelper(MethodPointer method_pointer) {
return
[method_pointer](
PyHolderType<T>* t,
typename WrappedFunctionParameterTraits<Args>::WrappedType... args) {
auto unwrapped = ((t->deref()).*method_pointer)(
WrappedFunctionParameterTraits<Args>::Unwrap(
std::forward<
typename WrappedFunctionParameterTraits<Args>::WrappedType>(
args))...);
return WrapInPyHolderIfHolderExists(std::move(unwrapped), t);
};
}
// PyWrap is the main interface for the code in this file. It is designed to be
// used in pybind11 interface definition code when declaring methods of wrapped
// types. It takes a pointer to a method of a wrapped type that potentially has
// parameters of types that are wrapped, and potentially returns something that
// needs to be wrapped.
//
// Its return value is a functor that unwraps the object, calls the given method
// after unwrapping the parameters and then wraps the return value before
// returning.
//
// Example usage (here, FunctionHolder is a PyHolder type that holds a
// Function*):
//
// py::class_<FunctionHolder>(m, "Function")
// .def("dump_ir", PyWrap(&Function::DumpIr));
//
// Note that even though Function* is wrapped in FunctionHolder, the type can be
// declared almost as if the object is not wrapped. For comparison, an unwrapped
// type would have been defined like this:
//
// py::class_<Function>(m, "Function")
// .def("dump_ir", &Function::DumpIr);
template <typename ReturnT, typename T, typename... Args>
auto PyWrap(ReturnT (T::*method_pointer)(Args...) const) {
return PyWrapHelper<decltype(method_pointer), ReturnT, T, Args...>(
method_pointer);
}
// PyWrap for member methods. For more info see the docs on the other overload.
template <typename ReturnT, typename T, typename... Args>
auto PyWrap(ReturnT (T::*method_pointer)(Args...)) {
return PyWrapHelper<decltype(method_pointer), ReturnT, T, Args...>(
method_pointer);
}
// PyWrap for static methods and free functions. This behaves like PyWrap for
// methods, except that it is not able to wrap return values, because it doesn't
// have a pointer to a this PyHolder object that it can extract owned pointers
// from.
template <typename ReturnT, typename... Args>
auto PyWrap(ReturnT (*function_pointer)(Args...)) {
return
[function_pointer](
typename WrappedFunctionParameterTraits<Args>::WrappedType... args) {
// Because there is no wrapped this pointer, it's not possible to wrap
// the return value. This only unwraps parameters when applicable.
return (*function_pointer)(WrappedFunctionParameterTraits<Args>::Unwrap(
std::forward<
typename WrappedFunctionParameterTraits<Args>::WrappedType>(
args))...);
};
}
} // namespace xls
// Tell pybind11 how to cast a TypeHolder to a specific type. This is necessary
// to make wrapped C++ methods that return a Type* work, otherwise it's not
// possible to call methods of subtypes in Python.
namespace pybind11 {
template <>
struct polymorphic_type_hook<xls::TypeHolder> {
static const void* get(const xls::TypeHolder* src,
const std::type_info*& type) { // NOLINT
if (src == nullptr) {
return nullptr;
}
if (src->deref().IsBits()) {
type = &typeid(xls::BitsTypeHolder);
return static_cast<const xls::BitsTypeHolder*>(src);
} else if (src->deref().IsTuple()) {
type = &typeid(xls::TupleTypeHolder);
return static_cast<const xls::TupleTypeHolder*>(src);
} else if (src->deref().IsArray()) {
type = &typeid(xls::ArrayTypeHolder);
return static_cast<const xls::ArrayTypeHolder*>(src);
}
return src;
}
};
} // namespace pybind11
#endif // XLS_IR_PYTHON_WRAPPER_TYPES_H_
| 35.941909 | 80 | 0.722235 | [
"object",
"vector"
] |
bbd662e9c9b3a1c016f8afb1230d67f240fd44e9 | 2,947 | h | C | gui/main_window/contact_list/RecentsModel.h | Vavilon3000/icq | 9fe7a3c42c07eb665d2e3b0ec50052de382fd89c | [
"Apache-2.0"
] | 1 | 2021-03-18T20:00:07.000Z | 2021-03-18T20:00:07.000Z | gui/main_window/contact_list/RecentsModel.h | Vavilon3000/icq | 9fe7a3c42c07eb665d2e3b0ec50052de382fd89c | [
"Apache-2.0"
] | null | null | null | gui/main_window/contact_list/RecentsModel.h | Vavilon3000/icq | 9fe7a3c42c07eb665d2e3b0ec50052de382fd89c | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "CustomAbstractListModel.h"
#include "../../types/contact.h"
#include "../../types/message.h"
namespace Ui
{
class MainWindow;
}
namespace Logic
{
class RecentsModel : public CustomAbstractListModel
{
Q_OBJECT
Q_SIGNALS:
void orderChanged();
void updated();
void readStateChanged(const QString&);
void selectContact(const QString&);
void dlgStatesHandled(const QVector<Data::DlgState>&);
void favoriteChanged(const QString&);
public Q_SLOTS:
void refresh();
private Q_SLOTS:
void activeDialogHide(const QString&);
void contactChanged(const QString&);
void dlgStates(const QVector<Data::DlgState>&);
void sortDialogs();
void contactRemoved(const QString&);
public:
explicit RecentsModel(QObject *parent);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
Data::DlgState getDlgState(const QString& aimId = QString(), bool fromDialog = false);
void unknownToRecents(const Data::DlgState&);
void toggleFavoritesVisible();
void unknownAppearance();
void sendLastRead(const QString& aimId = QString());
void markAllRead();
void hideChat(const QString& aimId);
void muteChat(const QString& aimId, bool mute);
bool isFavorite(const QString& aimid) const;
bool isServiceItem(const QModelIndex& i) const;
bool isFavoritesGroupButton(const QModelIndex& i) const;
bool isFavoritesVisible() const;
quint16 getFavoritesCount() const;
bool isUnknownsButton(const QModelIndex& i) const;
bool isRecentsHeader(const QModelIndex& i) const;
void setFavoritesHeadVisible(bool _isVisible);
bool isServiceAimId(const QString& _aimId) const;
QModelIndex contactIndex(const QString& aimId) const;
int totalUnreads() const;
int recentsUnreads() const;
int favoritesUnreads() const;
QString firstContact() const;
QString nextUnreadAimId() const;
QString nextAimId(const QString& aimId) const;
QString prevAimId(const QString& aimId) const;
bool lessRecents(const QString& _aimid1, const QString& _aimid2);
std::vector<QString> getSortedRecentsContacts() const;
private:
int correctIndex(int i) const;
int visibleContactsInFavorites() const;
int getUnknownsButtonIndex() const;
int getSizeOfUnknownBlock() const;
int getFavoritesHeaderIndex() const;
int getRecentsHeaderIndex() const;
int getVisibleServiceItemInFavorites() const;
std::vector<Data::DlgState> Dialogs_;
QHash<QString, int> Indexes_;
QTimer* Timer_;
quint16 FavoritesCount_;
bool FavoritesVisible_;
bool FavoritesHeadVisible_;
};
RecentsModel* getRecentsModel();
void ResetRecentsModel();
} | 28.61165 | 88 | 0.698677 | [
"vector"
] |
bbe3f400e0b9b6bcf6e5cda91c5dd5bd184c1a22 | 2,171 | h | C | components/dom_distiller/core/page_distiller.h | iplo/Chain | 8bc8943d66285d5258fffc41bed7c840516c4422 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | components/dom_distiller/core/page_distiller.h | JasonEric/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-02-14T21:55:58.000Z | 2017-02-14T21:55:58.000Z | components/dom_distiller/core/page_distiller.h | JasonEric/chromium | c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_DOM_DISTILLER_CORE_PAGE_DISTILLER_H_
#define COMPONENTS_DOM_DISTILLER_CORE_PAGE_DISTILLER_H_
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/memory/scoped_ptr.h"
#include "base/values.h"
#include "components/dom_distiller/core/distiller_page.h"
#include "url/gurl.h"
namespace dom_distiller {
class DistillerImpl;
struct DistilledPageInfo {
std::string title;
std::string html;
std::string next_page_url;
std::string prev_page_url;
std::vector<std::string> image_urls;
DistilledPageInfo();
~DistilledPageInfo();
private:
DISALLOW_COPY_AND_ASSIGN(DistilledPageInfo);
};
// Distills a single page of an article.
class PageDistiller : public DistillerPage::Delegate {
public:
typedef base::Callback<void(scoped_ptr<DistilledPageInfo> distilled_page,
bool distillation_successful)>
PageDistillerCallback;
explicit PageDistiller(const DistillerPageFactory& distiller_page_factory);
virtual ~PageDistiller();
// Creates an execution context. This must be called once before any calls are
// made to distill the page.
virtual void Init();
// Distills the |url| and posts the |callback| with results.
virtual void DistillPage(const GURL& url,
const PageDistillerCallback& callback);
// DistillerPage::Delegate
virtual void OnLoadURLDone() OVERRIDE;
virtual void OnExecuteJavaScriptDone(const GURL& page_url,
const base::Value* value) OVERRIDE;
private:
virtual void LoadURL(const GURL& url);
// Injects JavaScript to distill a loaded page down to its important content,
// e.g., extracting a news article from its surrounding boilerplate.
void GetDistilledContent();
scoped_ptr<DistillerPage> distiller_page_;
PageDistillerCallback page_distiller_callback_;
DISALLOW_COPY_AND_ASSIGN(PageDistiller);
};
} // namespace dom_distiller
#endif // COMPONENTS_DOM_DISTILLER_CORE_PAGE_DISTILLER_H_
| 30.152778 | 80 | 0.746661 | [
"vector"
] |
f4bbbafe2774e8900898a329e51867140980aece | 7,688 | h | C | include/grd3dinternal.h | ptitSeb/freespace2 | 500ee249f7033aac9b389436b1737a404277259c | [
"Linux-OpenIB"
] | 1 | 2020-07-14T07:29:18.000Z | 2020-07-14T07:29:18.000Z | include/grd3dinternal.h | ptitSeb/freespace2 | 500ee249f7033aac9b389436b1737a404277259c | [
"Linux-OpenIB"
] | 2 | 2019-01-01T22:35:56.000Z | 2022-03-14T07:34:00.000Z | include/grd3dinternal.h | ptitSeb/freespace2 | 500ee249f7033aac9b389436b1737a404277259c | [
"Linux-OpenIB"
] | 2 | 2021-03-07T11:40:42.000Z | 2021-12-26T21:40:39.000Z | /*
* Copyright (C) Volition, Inc. 1999. All rights reserved.
*
* All source code herein is the property of Volition, Inc. You may not sell
* or otherwise commercially exploit the source or things you created based on
* the source.
*/
/*
* $Logfile: /Freespace2/code/Graphics/GrD3DInternal.h $
* $Revision: 246 $
* $Date: 2004-09-20 03:31:45 +0200 (Mon, 20 Sep 2004) $
* $Author: theoddone33 $
*
* Prototypes for the variables used internally by the Direct3D renderer
*
* $Log$
* Revision 1.3 2004/09/20 01:31:44 theoddone33
* GCC 3.4 fixes.
*
* Revision 1.2 2002/06/09 04:41:13 relnev
* added copyright header
*
* Revision 1.1.1.1 2002/05/03 03:28:12 root
* Initial import.
*
*
* 5 7/13/99 1:15p Dave
* 32 bit support. Whee!
*
* 4 7/09/99 9:51a Dave
* Added thick polyline code.
*
* 3 6/29/99 10:35a Dave
* Interface polygon bitmaps! Whee!
*
* 2 10/07/98 10:52a Dave
* Initial checkin.
*
* 1 10/07/98 10:49a Dave
*
* 21 5/23/98 4:14p John
* Added code to preload textures to video card for AGP. Added in code
* to page in some bitmaps that weren't getting paged in at level start.
*
* 20 5/20/98 9:45p John
* added code so the places in code that change half the palette don't
* have to clear the screen.
*
* 19 5/12/98 10:34a John
* Added d3d_shade functionality. Added d3d_flush function, since the
* shader seems to get reorganzed behind the overlay text stuff!
*
* 18 5/12/98 8:18a John
* Put in code to use a different texture format for alpha textures and
* normal textures. Turned off filtering for aabitmaps. Took out
* destblend=invsrccolor alpha mode that doesn't work on riva128.
*
* 17 5/11/98 10:19a John
* Added caps checking
*
* 16 5/07/98 3:02p John
* Mpre texture cleanup. You can now reinit d3d without a crash.
*
* 15 5/07/98 9:54a John
* Added in palette flash functionallity.
*
* 14 5/06/98 11:21p John
* Fixed a bitmap bug with Direct3D. Started adding new caching code into
* D3D.
*
* 13 5/06/98 8:41p John
* Fixed some font clipping bugs. Moved texture handle set code for d3d
* into the texture module.
*
* 12 5/06/98 5:30p John
* Removed unused cfilearchiver. Removed/replaced some unused/little used
* graphics functions, namely gradient_h and _v and pixel_sp. Put in new
* DirectX header files and libs that fixed the Direct3D alpha blending
* problems.
*
* 11 5/05/98 10:37p John
* Added code to optionally use execute buffers.
*
* 10 5/04/98 3:36p John
* Got zbuffering working with Direct3D.
*
* 9 4/14/98 12:15p John
* Made 16-bpp movies work.
*
* 8 3/12/98 5:36p John
* Took out any unused shaders. Made shader code take rgbc instead of
* matrix and vector since noone used it like a matrix and it would have
* been impossible to do in hardware. Made Glide implement a basic
* shader for online help.
*
* 7 3/10/98 4:18p John
* Cleaned up graphics lib. Took out most unused gr functions. Made D3D
* & Glide have popups and print screen. Took out all >8bpp software
* support. Made Fred zbuffer. Made zbuffer allocate dynamically to
* support Fred. Made zbuffering key off of functions rather than one
* global variable.
*
* 6 3/09/98 6:06p John
* Restructured font stuff to avoid duplicate code in Direct3D and Glide.
* Restructured Glide to avoid redundent state setting.
*
* 5 3/08/98 12:33p John
* Made d3d cleanup free textures. Made d3d always divide texture size by
* 2 for now.
*
* 4 3/07/98 8:29p John
* Put in some Direct3D features. Transparency on bitmaps. Made fonts &
* aabitmaps render nice.
*
* 3 2/17/98 7:28p John
* Got fonts and texturing working in Direct3D
*
* 2 2/07/98 7:50p John
* Added code so that we can use the old blending type of alphacolors if
* we want to. Made the stars use them.
*
* 1 2/03/98 9:24p John
*
* $NoKeywords: $
*/
#ifndef _GRD3DINTERNAL_H
#define _GRD3DINTERNAL_H
#include <windows.h>
#include <windowsx.h>
#define D3D_OVERLOADS
#include "vddraw.h"
// To remove an otherwise well-lodged compiler error
// 4201 nonstandard extension used : nameless struct/union (happens a lot in Windows include headers)
#pragma warning(disable: 4201)
#include "vd3d.h"
#include "2d.h"
#include "grinternal.h"
extern LPDIRECTDRAW lpDD1;
extern LPDIRECTDRAW2 lpDD;
extern LPDIRECT3D2 lpD3D;
extern LPDIRECT3DDEVICE lpD3DDeviceEB;
extern LPDIRECT3DDEVICE2 lpD3DDevice;
extern LPDIRECTDRAWSURFACE lpBackBuffer;
extern LPDIRECTDRAWSURFACE lpFrontBuffer;
extern LPDIRECTDRAWSURFACE lpZBuffer;
extern LPDIRECT3DVIEWPORT2 lpViewport;
extern LPDIRECTDRAWPALETTE lpPalette;
extern DDPIXELFORMAT AlphaTextureFormat;
extern DDPIXELFORMAT NonAlphaTextureFormat;
extern DDPIXELFORMAT ScreenFormat;
extern D3DDEVICEDESC D3DHWDevDesc, D3DHELDevDesc;
extern LPD3DDEVICEDESC lpDevDesc;
extern DDCAPS DD_driver_caps;
extern DDCAPS DD_hel_caps;
extern int D3D_texture_divider;
extern int D3D_32bit;
extern char* d3d_error_string(HRESULT error);
void d3d_tcache_init(int use_sections);
void d3d_tcache_cleanup();
void d3d_tcache_flush();
void d3d_tcache_frame();
// Flushes any pending operations
void d3d_flush();
int d3d_tcache_set(int bitmap_id, int bitmap_type, float *u_ratio, float *v_ratio, int fail_on_full=0, int sx = -1, int sy = -1, int force = 0);
// Functions in GrD3DRender.cpp stuffed into gr_screen structure
void gr_d3d_flash(int r, int g, int b);
void gr_d3d_zbuffer_clear(int mode);
int gr_d3d_zbuffer_get();
int gr_d3d_zbuffer_set(int mode);
void gr_d3d_tmapper( int nverts, vertex **verts, uint flags );
void gr_d3d_scaler(vertex *va, vertex *vb );
void gr_d3d_aascaler(vertex *va, vertex *vb );
void gr_d3d_pixel(int x, int y);
void gr_d3d_clear();
void gr_d3d_set_clip(int x,int y,int w,int h);
void gr_d3d_reset_clip();
void gr_d3d_init_color(color *c, int r, int g, int b);
void gr_d3d_init_alphacolor( color *clr, int r, int g, int b, int alpha, int type=AC_TYPE_HUD );
void gr_d3d_set_color( int r, int g, int b );
void gr_d3d_get_color( int * r, int * g, int * b );
void gr_d3d_set_color_fast(color *dst);
void gr_d3d_set_bitmap( int bitmap_num, int alphablend_mode=GR_ALPHABLEND_NONE, int bitblt_mode=GR_BITBLT_MODE_NORMAL, float alpha=1.0f, int sx=-1, int sy=-1 );
void gr_d3d_bitmap_ex(int x,int y,int w,int h,int sx,int sy);
void gr_d3d_bitmap(int x, int y);
void gr_d3d_aabitmap_ex(int x,int y,int w,int h,int sx,int sy);
void gr_d3d_aabitmap(int x, int y);
void gr_d3d_rect(int x,int y,int w,int h);
void gr_d3d_create_shader(shader * shade, float r, float g, float b, float c );
void gr_d3d_set_shader( shader * shade );
void gr_d3d_shade(int x,int y,int w,int h);
void gr_d3d_create_font_bitmap();
void gr_d3d_char(int x,int y,int letter);
void gr_d3d_string( int sx, int sy, char *s );
void gr_d3d_circle( int xc, int yc, int d );
void gr_d3d_line(int x1,int y1,int x2,int y2);
void gr_d3d_aaline(vertex *v1, vertex *v2);
void gr_d3d_gradient(int x1,int y1,int x2,int y2);
void gr_d3d_set_palette(ubyte *new_palette, int restrict_alphacolor = 0);
void gr_d3d_diamond(int x, int y, int width, int height);
void gr_d3d_print_screen(char *filename);
void gr_d3d_fog_set(int fog_mode, int r, int g, int b, float fog_near = -1.0f, float fog_far = -1.0f);
// Functions used to render. Calls either DrawPrim or Execute buffer code
HRESULT d3d_SetRenderState( D3DRENDERSTATETYPE dwRenderStateType, DWORD dwRenderState );
HRESULT d3d_DrawPrimitive( D3DPRIMITIVETYPE dptPrimitiveType, D3DVERTEXTYPE dvtVertexType, LPVOID lpvVertices, DWORD dwVertexCount, DWORD dwFlags );
#endif //_GRD3DINTERNAL_H
| 33.426087 | 160 | 0.727367 | [
"render",
"vector"
] |
f4beda9380983bfd9e4beb9fd84ede3d6ed7ffd6 | 3,214 | h | C | DigitalPlayprint/master/common/include/mle/DppGenMakefile.h | magic-lantern-studio/mle-core-dpp | ec901206b718c57163d8ac62afab7a1e1d6371d9 | [
"MIT"
] | null | null | null | DigitalPlayprint/master/common/include/mle/DppGenMakefile.h | magic-lantern-studio/mle-core-dpp | ec901206b718c57163d8ac62afab7a1e1d6371d9 | [
"MIT"
] | null | null | null | DigitalPlayprint/master/common/include/mle/DppGenMakefile.h | magic-lantern-studio/mle-core-dpp | ec901206b718c57163d8ac62afab7a1e1d6371d9 | [
"MIT"
] | null | null | null | /** @defgroup MleDPPMaster Magic Lantern Digital Playprint Library API - Master */
/**
* @file DppGenMakefile.h
* @ingroup MleDPPMaster
*
* Magic Lantern Digital Playprint Library API.
*
* @author Mark S. Millard
* @date September 15, 2004
*/
// COPYRIGHT_BEGIN
//
// Copyright (c) 2015 Wizzer Works
//
// 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.
//
// For information concerning this header file, contact Mark S. Millard,
// of Wizzer Works at msm@wizzerworks.com.
//
// More information concerning Wizzer Works may be found at
//
// http://www.wizzerworks.com
//
// COPYRIGHT_END
#ifndef __MLE_DPP_GENMAKEFILE_H_
#define __MLE_DPP_GENMAKEFILE_H_
// Include Magic Lantern header files.
#include <mle/mlTypes.h>
#include <mle/MleTemplate.h>
#include "mle/Dpp.h"
class MleDwpInput;
class MleDwpItem;
/**
* This class is used to generate Makefiles for Magic Lantern titles.
*/
class MleDppGenMakefile
{
// Declare member variables.
private:
MleDwpInput *m_wp; // DWP input object for reader/writer.
MleDwpItem *m_root; // Root of instantiated DWP.
// Declare member functions.
public:
MleDppGenMakefile(char *filename);
virtual ~MleDppGenMakefile(void);
MlBoolean isError()
{ return m_root == NULL; }
MleDwpItem *getRoot(void)
{ return(m_root); };
MlBoolean generateMakefile(void);
/**
* Override operator new.
*
* @param tSize The size, in bytes, to allocate.
*/
void* operator new(size_t tSize);
/**
* Override operator delete.
*
* @param p A pointer to the memory to delete.
*/
void operator delete(void *p);
private:
// Hide the default constructor.
MleDppGenMakefile(void) {};
// Read the Makefile generator template.
void readMakefileTemplate(MleTemplate &pTemplate);
};
// Declare function prototypes.
void doGenMakefileActors(MleTemplateProcess *process, char *section, void *clientdata);
void doGenMakefileRoles(MleTemplateProcess *process, char *section, void *clientdata);
void doGenMakefileSets(MleTemplateProcess *process, char *section, void *clientdata);
#endif /* __MLE_DPP_GENMAKEFILE_H_ */
| 27.706897 | 87 | 0.719042 | [
"object"
] |
f4bfd07746913c468945c64f7966cc2f12d7bc6c | 735 | h | C | models/tesseract_model.h | rockyzhengwu/labeldoc | 1782c1ce7cfb3d2c3c92df16b8b5d4b94a9bd1c6 | [
"Apache-2.0"
] | 5 | 2020-06-08T06:32:25.000Z | 2021-11-24T08:42:56.000Z | models/tesseract_model.h | rockyzhengwu/labeldoc | 1782c1ce7cfb3d2c3c92df16b8b5d4b94a9bd1c6 | [
"Apache-2.0"
] | null | null | null | models/tesseract_model.h | rockyzhengwu/labeldoc | 1782c1ce7cfb3d2c3c92df16b8b5d4b94a9bd1c6 | [
"Apache-2.0"
] | 2 | 2020-06-08T10:02:04.000Z | 2021-11-24T08:42:59.000Z | #ifndef TESSERACT_MODEL_H
#define TESSERACT_MODEL_H
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <vector>
#include "pageitem.h"
namespace ocrmodel {
// input_image is binary at there
class TesseractHandler{
public:
TesseractHandler();
~TesseractHandler();
std::vector<PageItem> tesseract_analysis(cv::Mat input_image);
std::vector<PageItem> tesseract_analysis_rects(cv::Mat input_image, std::vector<cv::Rect> areas);
void close();
private:
tesseract::TessBaseAPI *api;
std::vector<PageItem> analysis_textline(cv::Mat image, tesseract::TessBaseAPI * api=nullptr);
};
}
#endif
| 23.709677 | 100 | 0.745578 | [
"vector"
] |
f4ce13c4e2ede64c2a0b2bff591eebd2c6664b31 | 247 | h | C | GherkinPreprocessor/CSVParser.h | atdd-bdd/GherkinPreprocessor | 5dc011ee9c7a1ac55300d9a7f1040e879ebf5f3e | [
"MIT"
] | null | null | null | GherkinPreprocessor/CSVParser.h | atdd-bdd/GherkinPreprocessor | 5dc011ee9c7a1ac55300d9a7f1040e879ebf5f3e | [
"MIT"
] | null | null | null | GherkinPreprocessor/CSVParser.h | atdd-bdd/GherkinPreprocessor | 5dc011ee9c7a1ac55300d9a7f1040e879ebf5f3e | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <string>
#include <istream>
class CSVParser
{
public: static std::vector<std::string> readCSVRow(const std::string& row);
public: static std::vector<std::vector<std::string>> readCSV(std::istream& in);
};
| 22.454545 | 80 | 0.724696 | [
"vector"
] |
f4d7ab1b755023bfa5a2a11c33b970ae2472c5d0 | 1,968 | h | C | src/nimbro_robotcontrol/hardware/robotcontrol/include/robotcontrol/hw/dummyinterface.h | hfarazi/humanoid_op_ros_kinetic | 84712bd541d0130b840ad1935d5bfe301814dbe6 | [
"BSD-3-Clause"
] | 45 | 2015-11-04T01:29:12.000Z | 2022-02-11T05:37:42.000Z | src/nimbro_robotcontrol/hardware/robotcontrol/include/robotcontrol/hw/dummyinterface.h | hfarazi/humanoid_op_ros_kinetic | 84712bd541d0130b840ad1935d5bfe301814dbe6 | [
"BSD-3-Clause"
] | 1 | 2016-08-10T04:00:32.000Z | 2016-08-10T12:59:36.000Z | src/nimbro_robotcontrol/hardware/robotcontrol/include/robotcontrol/hw/dummyinterface.h | hfarazi/humanoid_op_ros_kinetic | 84712bd541d0130b840ad1935d5bfe301814dbe6 | [
"BSD-3-Clause"
] | 20 | 2016-03-05T14:28:45.000Z | 2021-01-30T00:50:47.000Z | // Dummy hardware interface
// Author: Max Schwarz <max.schwarz@uni-bonn.de>
// Philipp Allgeuer <pallgeuer@ais.uni-bonn.de>
#ifndef DUMMYINTERFACE_H
#define DUMMYINTERFACE_H
#include <robotcontrol/hw/hardwareinterface.h>
#include <robotcontrol/model/joint.h>
#include <config_server/parameter.h>
#include <boost/circular_buffer.hpp>
namespace robotcontrol
{
/**
* @brief Dummy hardware interface
*
* This provides a simple loopback hardware interface. The joint commands
* are simply stored and returned as position feedback.
**/
class DummyInterface : public HardwareInterface
{
public:
DummyInterface();
virtual ~DummyInterface();
virtual bool init(RobotModel* model);
virtual boost::shared_ptr<Joint> createJoint(const std::string& name);
virtual void getDiagnostics(robotcontrol::DiagnosticsPtr ptr);
virtual bool readJointStates();
virtual bool sendJointTargets();
virtual bool setStiffness(float torque);
private:
// Constants
const std::string CONFIG_PARAM_PATH;
RobotModel* m_model;
struct DummyJoint : public Joint
{
explicit DummyJoint(const std::string& name);
config_server::Parameter<bool> velocityMode;
};
// Config server parameters
config_server::Parameter<bool> m_addDelay;
config_server::Parameter<bool> m_noiseEnable;
config_server::Parameter<float> m_noiseMagnitude;
config_server::Parameter<float> m_fakeIMUGyroX;
config_server::Parameter<float> m_fakeIMUGyroY;
config_server::Parameter<float> m_fakeIMUGyroZ;
config_server::Parameter<float> m_fakeIMUAccX;
config_server::Parameter<float> m_fakeIMUAccY;
config_server::Parameter<float> m_fakeIMUAccZ;
config_server::Parameter<float> m_fakeIMUMagX;
config_server::Parameter<float> m_fakeIMUMagY;
config_server::Parameter<float> m_fakeIMUMagZ;
config_server::Parameter<float> m_fakeAttFusedX;
config_server::Parameter<float> m_fakeAttFusedY;
typedef boost::circular_buffer<std::vector<double> > DataBuf;
DataBuf m_dataBuf;
};
}
#endif
| 28.114286 | 73 | 0.787602 | [
"vector",
"model"
] |
f4e0066733420d817a1b67266e182d470a56e1a6 | 60,324 | c | C | src/intel/vulkan/anv_descriptor_set.c | thermasol/mesa3d | 6f1bc4e7edfface197ef281cffdf399b5389e24a | [
"MIT"
] | null | null | null | src/intel/vulkan/anv_descriptor_set.c | thermasol/mesa3d | 6f1bc4e7edfface197ef281cffdf399b5389e24a | [
"MIT"
] | null | null | null | src/intel/vulkan/anv_descriptor_set.c | thermasol/mesa3d | 6f1bc4e7edfface197ef281cffdf399b5389e24a | [
"MIT"
] | null | null | null | /*
* Copyright © 2015 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) 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 <assert.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include "util/mesa-sha1.h"
#include "vk_util.h"
#include "anv_private.h"
/*
* Descriptor set layouts.
*/
static enum anv_descriptor_data
anv_descriptor_data_for_type(const struct anv_physical_device *device,
VkDescriptorType type)
{
enum anv_descriptor_data data = 0;
switch (type) {
case VK_DESCRIPTOR_TYPE_SAMPLER:
data = ANV_DESCRIPTOR_SAMPLER_STATE;
if (device->has_bindless_samplers)
data |= ANV_DESCRIPTOR_SAMPLED_IMAGE;
break;
case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
data = ANV_DESCRIPTOR_SURFACE_STATE |
ANV_DESCRIPTOR_SAMPLER_STATE;
if (device->has_bindless_images || device->has_bindless_samplers)
data |= ANV_DESCRIPTOR_SAMPLED_IMAGE;
break;
case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
data = ANV_DESCRIPTOR_SURFACE_STATE;
if (device->has_bindless_images)
data |= ANV_DESCRIPTOR_SAMPLED_IMAGE;
break;
case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
data = ANV_DESCRIPTOR_SURFACE_STATE;
break;
case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
data = ANV_DESCRIPTOR_SURFACE_STATE;
if (device->info.gen < 9)
data |= ANV_DESCRIPTOR_IMAGE_PARAM;
if (device->has_bindless_images)
data |= ANV_DESCRIPTOR_STORAGE_IMAGE;
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
data = ANV_DESCRIPTOR_SURFACE_STATE |
ANV_DESCRIPTOR_BUFFER_VIEW;
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
data = ANV_DESCRIPTOR_SURFACE_STATE;
break;
case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT:
data = ANV_DESCRIPTOR_INLINE_UNIFORM;
break;
default:
unreachable("Unsupported descriptor type");
}
/* On gen8 and above when we have softpin enabled, we also need to push
* SSBO address ranges so that we can use A64 messages in the shader.
*/
if (device->has_a64_buffer_access &&
(type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER ||
type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC))
data |= ANV_DESCRIPTOR_ADDRESS_RANGE;
/* On Ivy Bridge and Bay Trail, we need swizzles textures in the shader
* Do not handle VK_DESCRIPTOR_TYPE_STORAGE_IMAGE and
* VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT because they already must
* have identity swizzle.
*/
if (device->info.gen == 7 && !device->info.is_haswell &&
(type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE ||
type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER))
data |= ANV_DESCRIPTOR_TEXTURE_SWIZZLE;
return data;
}
static unsigned
anv_descriptor_data_size(enum anv_descriptor_data data)
{
unsigned size = 0;
if (data & ANV_DESCRIPTOR_SAMPLED_IMAGE)
size += sizeof(struct anv_sampled_image_descriptor);
if (data & ANV_DESCRIPTOR_STORAGE_IMAGE)
size += sizeof(struct anv_storage_image_descriptor);
if (data & ANV_DESCRIPTOR_IMAGE_PARAM)
size += BRW_IMAGE_PARAM_SIZE * 4;
if (data & ANV_DESCRIPTOR_ADDRESS_RANGE)
size += sizeof(struct anv_address_range_descriptor);
if (data & ANV_DESCRIPTOR_TEXTURE_SWIZZLE)
size += sizeof(struct anv_texture_swizzle_descriptor);
return size;
}
/** Returns the size in bytes of each descriptor with the given layout */
unsigned
anv_descriptor_size(const struct anv_descriptor_set_binding_layout *layout)
{
if (layout->data & ANV_DESCRIPTOR_INLINE_UNIFORM) {
assert(layout->data == ANV_DESCRIPTOR_INLINE_UNIFORM);
return layout->array_size;
}
unsigned size = anv_descriptor_data_size(layout->data);
/* For multi-planar bindings, we make every descriptor consume the maximum
* number of planes so we don't have to bother with walking arrays and
* adding things up every time. Fortunately, YCbCr samplers aren't all
* that common and likely won't be in the middle of big arrays.
*/
if (layout->max_plane_count > 1)
size *= layout->max_plane_count;
return size;
}
/** Returns the size in bytes of each descriptor of the given type
*
* This version of the function does not have access to the entire layout so
* it may only work on certain descriptor types where the descriptor size is
* entirely determined by the descriptor type. Whenever possible, code should
* use anv_descriptor_size() instead.
*/
unsigned
anv_descriptor_type_size(const struct anv_physical_device *pdevice,
VkDescriptorType type)
{
assert(type != VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT &&
type != VK_DESCRIPTOR_TYPE_SAMPLER &&
type != VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE &&
type != VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER);
return anv_descriptor_data_size(anv_descriptor_data_for_type(pdevice, type));
}
static bool
anv_descriptor_data_supports_bindless(const struct anv_physical_device *pdevice,
enum anv_descriptor_data data,
bool sampler)
{
if (data & ANV_DESCRIPTOR_ADDRESS_RANGE) {
assert(pdevice->has_a64_buffer_access);
return true;
}
if (data & ANV_DESCRIPTOR_SAMPLED_IMAGE) {
assert(pdevice->has_bindless_images || pdevice->has_bindless_samplers);
return sampler ? pdevice->has_bindless_samplers :
pdevice->has_bindless_images;
}
if (data & ANV_DESCRIPTOR_STORAGE_IMAGE) {
assert(pdevice->has_bindless_images);
return true;
}
return false;
}
bool
anv_descriptor_supports_bindless(const struct anv_physical_device *pdevice,
const struct anv_descriptor_set_binding_layout *binding,
bool sampler)
{
return anv_descriptor_data_supports_bindless(pdevice, binding->data,
sampler);
}
bool
anv_descriptor_requires_bindless(const struct anv_physical_device *pdevice,
const struct anv_descriptor_set_binding_layout *binding,
bool sampler)
{
if (pdevice->always_use_bindless)
return anv_descriptor_supports_bindless(pdevice, binding, sampler);
static const VkDescriptorBindingFlagBitsEXT flags_requiring_bindless =
VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT |
VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT |
VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT;
return (binding->flags & flags_requiring_bindless) != 0;
}
void anv_GetDescriptorSetLayoutSupport(
VkDevice _device,
const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
VkDescriptorSetLayoutSupport* pSupport)
{
ANV_FROM_HANDLE(anv_device, device, _device);
const struct anv_physical_device *pdevice =
&device->instance->physicalDevice;
uint32_t surface_count[MESA_SHADER_STAGES] = { 0, };
for (uint32_t b = 0; b < pCreateInfo->bindingCount; b++) {
const VkDescriptorSetLayoutBinding *binding = &pCreateInfo->pBindings[b];
enum anv_descriptor_data desc_data =
anv_descriptor_data_for_type(pdevice, binding->descriptorType);
switch (binding->descriptorType) {
case VK_DESCRIPTOR_TYPE_SAMPLER:
/* There is no real limit on samplers */
break;
case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
if (anv_descriptor_data_supports_bindless(pdevice, desc_data, false))
break;
if (binding->pImmutableSamplers) {
for (uint32_t i = 0; i < binding->descriptorCount; i++) {
ANV_FROM_HANDLE(anv_sampler, sampler,
binding->pImmutableSamplers[i]);
anv_foreach_stage(s, binding->stageFlags)
surface_count[s] += sampler->n_planes;
}
} else {
anv_foreach_stage(s, binding->stageFlags)
surface_count[s] += binding->descriptorCount;
}
break;
default:
if (anv_descriptor_data_supports_bindless(pdevice, desc_data, false))
break;
anv_foreach_stage(s, binding->stageFlags)
surface_count[s] += binding->descriptorCount;
break;
}
}
bool supported = true;
for (unsigned s = 0; s < MESA_SHADER_STAGES; s++) {
/* Our maximum binding table size is 240 and we need to reserve 8 for
* render targets.
*/
if (surface_count[s] >= MAX_BINDING_TABLE_SIZE - MAX_RTS)
supported = false;
}
pSupport->supported = supported;
}
VkResult anv_CreateDescriptorSetLayout(
VkDevice _device,
const VkDescriptorSetLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorSetLayout* pSetLayout)
{
ANV_FROM_HANDLE(anv_device, device, _device);
assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO);
uint32_t max_binding = 0;
uint32_t immutable_sampler_count = 0;
for (uint32_t j = 0; j < pCreateInfo->bindingCount; j++) {
max_binding = MAX2(max_binding, pCreateInfo->pBindings[j].binding);
/* From the Vulkan 1.1.97 spec for VkDescriptorSetLayoutBinding:
*
* "If descriptorType specifies a VK_DESCRIPTOR_TYPE_SAMPLER or
* VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER type descriptor, then
* pImmutableSamplers can be used to initialize a set of immutable
* samplers. [...] If descriptorType is not one of these descriptor
* types, then pImmutableSamplers is ignored.
*
* We need to be careful here and only parse pImmutableSamplers if we
* have one of the right descriptor types.
*/
VkDescriptorType desc_type = pCreateInfo->pBindings[j].descriptorType;
if ((desc_type == VK_DESCRIPTOR_TYPE_SAMPLER ||
desc_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) &&
pCreateInfo->pBindings[j].pImmutableSamplers)
immutable_sampler_count += pCreateInfo->pBindings[j].descriptorCount;
}
struct anv_descriptor_set_layout *set_layout;
struct anv_descriptor_set_binding_layout *bindings;
struct anv_sampler **samplers;
/* We need to allocate decriptor set layouts off the device allocator
* with DEVICE scope because they are reference counted and may not be
* destroyed when vkDestroyDescriptorSetLayout is called.
*/
ANV_MULTIALLOC(ma);
anv_multialloc_add(&ma, &set_layout, 1);
anv_multialloc_add(&ma, &bindings, max_binding + 1);
anv_multialloc_add(&ma, &samplers, immutable_sampler_count);
if (!anv_multialloc_alloc(&ma, &device->alloc,
VK_SYSTEM_ALLOCATION_SCOPE_DEVICE))
return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
memset(set_layout, 0, sizeof(*set_layout));
set_layout->ref_cnt = 1;
set_layout->binding_count = max_binding + 1;
for (uint32_t b = 0; b <= max_binding; b++) {
/* Initialize all binding_layout entries to -1 */
memset(&set_layout->binding[b], -1, sizeof(set_layout->binding[b]));
set_layout->binding[b].flags = 0;
set_layout->binding[b].data = 0;
set_layout->binding[b].max_plane_count = 0;
set_layout->binding[b].array_size = 0;
set_layout->binding[b].immutable_samplers = NULL;
}
/* Initialize all samplers to 0 */
memset(samplers, 0, immutable_sampler_count * sizeof(*samplers));
uint32_t buffer_view_count = 0;
uint32_t dynamic_offset_count = 0;
uint32_t descriptor_buffer_size = 0;
for (uint32_t j = 0; j < pCreateInfo->bindingCount; j++) {
const VkDescriptorSetLayoutBinding *binding = &pCreateInfo->pBindings[j];
uint32_t b = binding->binding;
/* We temporarily store pCreateInfo->pBindings[] index (plus one) in the
* immutable_samplers pointer. This provides us with a quick-and-dirty
* way to sort the bindings by binding number.
*/
set_layout->binding[b].immutable_samplers = (void *)(uintptr_t)(j + 1);
}
const VkDescriptorSetLayoutBindingFlagsCreateInfoEXT *binding_flags_info =
vk_find_struct_const(pCreateInfo->pNext,
DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO_EXT);
for (uint32_t b = 0; b <= max_binding; b++) {
/* We stashed the pCreateInfo->pBindings[] index (plus one) in the
* immutable_samplers pointer. Check for NULL (empty binding) and then
* reset it and compute the index.
*/
if (set_layout->binding[b].immutable_samplers == NULL)
continue;
const uint32_t info_idx =
(uintptr_t)(void *)set_layout->binding[b].immutable_samplers - 1;
set_layout->binding[b].immutable_samplers = NULL;
const VkDescriptorSetLayoutBinding *binding =
&pCreateInfo->pBindings[info_idx];
if (binding->descriptorCount == 0)
continue;
#ifndef NDEBUG
set_layout->binding[b].type = binding->descriptorType;
#endif
if (binding_flags_info && binding_flags_info->bindingCount > 0) {
assert(binding_flags_info->bindingCount == pCreateInfo->bindingCount);
set_layout->binding[b].flags =
binding_flags_info->pBindingFlags[info_idx];
}
set_layout->binding[b].data =
anv_descriptor_data_for_type(&device->instance->physicalDevice,
binding->descriptorType);
set_layout->binding[b].array_size = binding->descriptorCount;
set_layout->binding[b].descriptor_index = set_layout->size;
set_layout->size += binding->descriptorCount;
if (set_layout->binding[b].data & ANV_DESCRIPTOR_BUFFER_VIEW) {
set_layout->binding[b].buffer_view_index = buffer_view_count;
buffer_view_count += binding->descriptorCount;
}
switch (binding->descriptorType) {
case VK_DESCRIPTOR_TYPE_SAMPLER:
case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
set_layout->binding[b].max_plane_count = 1;
if (binding->pImmutableSamplers) {
set_layout->binding[b].immutable_samplers = samplers;
samplers += binding->descriptorCount;
for (uint32_t i = 0; i < binding->descriptorCount; i++) {
ANV_FROM_HANDLE(anv_sampler, sampler,
binding->pImmutableSamplers[i]);
set_layout->binding[b].immutable_samplers[i] = sampler;
if (set_layout->binding[b].max_plane_count < sampler->n_planes)
set_layout->binding[b].max_plane_count = sampler->n_planes;
}
}
break;
case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
set_layout->binding[b].max_plane_count = 1;
break;
default:
break;
}
switch (binding->descriptorType) {
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
set_layout->binding[b].dynamic_offset_index = dynamic_offset_count;
dynamic_offset_count += binding->descriptorCount;
break;
default:
break;
}
if (binding->descriptorType ==
VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) {
/* Inline uniform blocks are specified to use the descriptor array
* size as the size in bytes of the block.
*/
descriptor_buffer_size = align_u32(descriptor_buffer_size, 32);
set_layout->binding[b].descriptor_offset = descriptor_buffer_size;
descriptor_buffer_size += binding->descriptorCount;
} else {
set_layout->binding[b].descriptor_offset = descriptor_buffer_size;
descriptor_buffer_size += anv_descriptor_size(&set_layout->binding[b]) *
binding->descriptorCount;
}
set_layout->shader_stages |= binding->stageFlags;
}
set_layout->buffer_view_count = buffer_view_count;
set_layout->dynamic_offset_count = dynamic_offset_count;
set_layout->descriptor_buffer_size = descriptor_buffer_size;
*pSetLayout = anv_descriptor_set_layout_to_handle(set_layout);
return VK_SUCCESS;
}
void anv_DestroyDescriptorSetLayout(
VkDevice _device,
VkDescriptorSetLayout _set_layout,
const VkAllocationCallbacks* pAllocator)
{
ANV_FROM_HANDLE(anv_device, device, _device);
ANV_FROM_HANDLE(anv_descriptor_set_layout, set_layout, _set_layout);
if (!set_layout)
return;
anv_descriptor_set_layout_unref(device, set_layout);
}
#define SHA1_UPDATE_VALUE(ctx, x) _mesa_sha1_update(ctx, &(x), sizeof(x));
static void
sha1_update_immutable_sampler(struct mesa_sha1 *ctx,
const struct anv_sampler *sampler)
{
if (!sampler->conversion)
return;
/* The only thing that affects the shader is ycbcr conversion */
_mesa_sha1_update(ctx, sampler->conversion,
sizeof(*sampler->conversion));
}
static void
sha1_update_descriptor_set_binding_layout(struct mesa_sha1 *ctx,
const struct anv_descriptor_set_binding_layout *layout)
{
SHA1_UPDATE_VALUE(ctx, layout->flags);
SHA1_UPDATE_VALUE(ctx, layout->data);
SHA1_UPDATE_VALUE(ctx, layout->max_plane_count);
SHA1_UPDATE_VALUE(ctx, layout->array_size);
SHA1_UPDATE_VALUE(ctx, layout->descriptor_index);
SHA1_UPDATE_VALUE(ctx, layout->dynamic_offset_index);
SHA1_UPDATE_VALUE(ctx, layout->buffer_view_index);
SHA1_UPDATE_VALUE(ctx, layout->descriptor_offset);
if (layout->immutable_samplers) {
for (uint16_t i = 0; i < layout->array_size; i++)
sha1_update_immutable_sampler(ctx, layout->immutable_samplers[i]);
}
}
static void
sha1_update_descriptor_set_layout(struct mesa_sha1 *ctx,
const struct anv_descriptor_set_layout *layout)
{
SHA1_UPDATE_VALUE(ctx, layout->binding_count);
SHA1_UPDATE_VALUE(ctx, layout->size);
SHA1_UPDATE_VALUE(ctx, layout->shader_stages);
SHA1_UPDATE_VALUE(ctx, layout->buffer_view_count);
SHA1_UPDATE_VALUE(ctx, layout->dynamic_offset_count);
SHA1_UPDATE_VALUE(ctx, layout->descriptor_buffer_size);
for (uint16_t i = 0; i < layout->binding_count; i++)
sha1_update_descriptor_set_binding_layout(ctx, &layout->binding[i]);
}
/*
* Pipeline layouts. These have nothing to do with the pipeline. They are
* just multiple descriptor set layouts pasted together
*/
VkResult anv_CreatePipelineLayout(
VkDevice _device,
const VkPipelineLayoutCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkPipelineLayout* pPipelineLayout)
{
ANV_FROM_HANDLE(anv_device, device, _device);
struct anv_pipeline_layout *layout;
assert(pCreateInfo->sType == VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO);
layout = vk_alloc2(&device->alloc, pAllocator, sizeof(*layout), 8,
VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
if (layout == NULL)
return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
layout->num_sets = pCreateInfo->setLayoutCount;
unsigned dynamic_offset_count = 0;
for (uint32_t set = 0; set < pCreateInfo->setLayoutCount; set++) {
ANV_FROM_HANDLE(anv_descriptor_set_layout, set_layout,
pCreateInfo->pSetLayouts[set]);
layout->set[set].layout = set_layout;
anv_descriptor_set_layout_ref(set_layout);
layout->set[set].dynamic_offset_start = dynamic_offset_count;
for (uint32_t b = 0; b < set_layout->binding_count; b++) {
if (set_layout->binding[b].dynamic_offset_index < 0)
continue;
dynamic_offset_count += set_layout->binding[b].array_size;
}
}
struct mesa_sha1 ctx;
_mesa_sha1_init(&ctx);
for (unsigned s = 0; s < layout->num_sets; s++) {
sha1_update_descriptor_set_layout(&ctx, layout->set[s].layout);
_mesa_sha1_update(&ctx, &layout->set[s].dynamic_offset_start,
sizeof(layout->set[s].dynamic_offset_start));
}
_mesa_sha1_update(&ctx, &layout->num_sets, sizeof(layout->num_sets));
_mesa_sha1_final(&ctx, layout->sha1);
*pPipelineLayout = anv_pipeline_layout_to_handle(layout);
return VK_SUCCESS;
}
void anv_DestroyPipelineLayout(
VkDevice _device,
VkPipelineLayout _pipelineLayout,
const VkAllocationCallbacks* pAllocator)
{
ANV_FROM_HANDLE(anv_device, device, _device);
ANV_FROM_HANDLE(anv_pipeline_layout, pipeline_layout, _pipelineLayout);
if (!pipeline_layout)
return;
for (uint32_t i = 0; i < pipeline_layout->num_sets; i++)
anv_descriptor_set_layout_unref(device, pipeline_layout->set[i].layout);
vk_free2(&device->alloc, pAllocator, pipeline_layout);
}
/*
* Descriptor pools.
*
* These are implemented using a big pool of memory and a free-list for the
* host memory allocations and a state_stream and a free list for the buffer
* view surface state. The spec allows us to fail to allocate due to
* fragmentation in all cases but two: 1) after pool reset, allocating up
* until the pool size with no freeing must succeed and 2) allocating and
* freeing only descriptor sets with the same layout. Case 1) is easy enogh,
* and the free lists lets us recycle blocks for case 2).
*/
/* The vma heap reserves 0 to mean NULL; we have to offset by some ammount to
* ensure we can allocate the entire BO without hitting zero. The actual
* amount doesn't matter.
*/
#define POOL_HEAP_OFFSET 64
#define EMPTY 1
VkResult anv_CreateDescriptorPool(
VkDevice _device,
const VkDescriptorPoolCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorPool* pDescriptorPool)
{
ANV_FROM_HANDLE(anv_device, device, _device);
struct anv_descriptor_pool *pool;
const VkDescriptorPoolInlineUniformBlockCreateInfoEXT *inline_info =
vk_find_struct_const(pCreateInfo->pNext,
DESCRIPTOR_POOL_INLINE_UNIFORM_BLOCK_CREATE_INFO_EXT);
uint32_t descriptor_count = 0;
uint32_t buffer_view_count = 0;
uint32_t descriptor_bo_size = 0;
for (uint32_t i = 0; i < pCreateInfo->poolSizeCount; i++) {
enum anv_descriptor_data desc_data =
anv_descriptor_data_for_type(&device->instance->physicalDevice,
pCreateInfo->pPoolSizes[i].type);
if (desc_data & ANV_DESCRIPTOR_BUFFER_VIEW)
buffer_view_count += pCreateInfo->pPoolSizes[i].descriptorCount;
unsigned desc_data_size = anv_descriptor_data_size(desc_data) *
pCreateInfo->pPoolSizes[i].descriptorCount;
/* Combined image sampler descriptors can take up to 3 slots if they
* hold a YCbCr image.
*/
if (pCreateInfo->pPoolSizes[i].type ==
VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER)
desc_data_size *= 3;
if (pCreateInfo->pPoolSizes[i].type ==
VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) {
/* Inline uniform blocks are specified to use the descriptor array
* size as the size in bytes of the block.
*/
assert(inline_info);
desc_data_size += pCreateInfo->pPoolSizes[i].descriptorCount;
}
descriptor_bo_size += desc_data_size;
descriptor_count += pCreateInfo->pPoolSizes[i].descriptorCount;
}
/* We have to align descriptor buffer allocations to 32B so that we can
* push descriptor buffers. This means that each descriptor buffer
* allocated may burn up to 32B of extra space to get the right alignment.
* (Technically, it's at most 28B because we're always going to start at
* least 4B aligned but we're being conservative here.) Allocate enough
* extra space that we can chop it into maxSets pieces and align each one
* of them to 32B.
*/
descriptor_bo_size += 32 * pCreateInfo->maxSets;
/* We align inline uniform blocks to 32B */
if (inline_info)
descriptor_bo_size += 32 * inline_info->maxInlineUniformBlockBindings;
descriptor_bo_size = ALIGN(descriptor_bo_size, 4096);
const size_t pool_size =
pCreateInfo->maxSets * sizeof(struct anv_descriptor_set) +
descriptor_count * sizeof(struct anv_descriptor) +
buffer_view_count * sizeof(struct anv_buffer_view);
const size_t total_size = sizeof(*pool) + pool_size;
pool = vk_alloc2(&device->alloc, pAllocator, total_size, 8,
VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
if (!pool)
return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
pool->size = pool_size;
pool->next = 0;
pool->free_list = EMPTY;
if (descriptor_bo_size > 0) {
VkResult result = anv_bo_init_new(&pool->bo, device, descriptor_bo_size);
if (result != VK_SUCCESS) {
vk_free2(&device->alloc, pAllocator, pool);
return result;
}
anv_gem_set_caching(device, pool->bo.gem_handle, I915_CACHING_CACHED);
pool->bo.map = anv_gem_mmap(device, pool->bo.gem_handle, 0,
descriptor_bo_size, 0);
if (pool->bo.map == NULL) {
anv_gem_close(device, pool->bo.gem_handle);
vk_free2(&device->alloc, pAllocator, pool);
return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
}
if (device->instance->physicalDevice.use_softpin) {
pool->bo.flags |= EXEC_OBJECT_PINNED;
anv_vma_alloc(device, &pool->bo);
}
util_vma_heap_init(&pool->bo_heap, POOL_HEAP_OFFSET, descriptor_bo_size);
} else {
pool->bo.size = 0;
}
anv_state_stream_init(&pool->surface_state_stream,
&device->surface_state_pool, 4096);
pool->surface_state_free_list = NULL;
list_inithead(&pool->desc_sets);
*pDescriptorPool = anv_descriptor_pool_to_handle(pool);
return VK_SUCCESS;
}
void anv_DestroyDescriptorPool(
VkDevice _device,
VkDescriptorPool _pool,
const VkAllocationCallbacks* pAllocator)
{
ANV_FROM_HANDLE(anv_device, device, _device);
ANV_FROM_HANDLE(anv_descriptor_pool, pool, _pool);
if (!pool)
return;
list_for_each_entry_safe(struct anv_descriptor_set, set,
&pool->desc_sets, pool_link) {
anv_descriptor_set_layout_unref(device, set->layout);
}
if (pool->bo.size) {
anv_gem_munmap(pool->bo.map, pool->bo.size);
anv_vma_free(device, &pool->bo);
anv_gem_close(device, pool->bo.gem_handle);
util_vma_heap_finish(&pool->bo_heap);
}
anv_state_stream_finish(&pool->surface_state_stream);
vk_free2(&device->alloc, pAllocator, pool);
}
VkResult anv_ResetDescriptorPool(
VkDevice _device,
VkDescriptorPool descriptorPool,
VkDescriptorPoolResetFlags flags)
{
ANV_FROM_HANDLE(anv_device, device, _device);
ANV_FROM_HANDLE(anv_descriptor_pool, pool, descriptorPool);
list_for_each_entry_safe(struct anv_descriptor_set, set,
&pool->desc_sets, pool_link) {
anv_descriptor_set_layout_unref(device, set->layout);
}
list_inithead(&pool->desc_sets);
pool->next = 0;
pool->free_list = EMPTY;
if (pool->bo.size) {
util_vma_heap_finish(&pool->bo_heap);
util_vma_heap_init(&pool->bo_heap, POOL_HEAP_OFFSET, pool->bo.size);
}
anv_state_stream_finish(&pool->surface_state_stream);
anv_state_stream_init(&pool->surface_state_stream,
&device->surface_state_pool, 4096);
pool->surface_state_free_list = NULL;
return VK_SUCCESS;
}
struct pool_free_list_entry {
uint32_t next;
uint32_t size;
};
static VkResult
anv_descriptor_pool_alloc_set(struct anv_descriptor_pool *pool,
uint32_t size,
struct anv_descriptor_set **set)
{
if (size <= pool->size - pool->next) {
*set = (struct anv_descriptor_set *) (pool->data + pool->next);
pool->next += size;
return VK_SUCCESS;
} else {
struct pool_free_list_entry *entry;
uint32_t *link = &pool->free_list;
for (uint32_t f = pool->free_list; f != EMPTY; f = entry->next) {
entry = (struct pool_free_list_entry *) (pool->data + f);
if (size <= entry->size) {
*link = entry->next;
*set = (struct anv_descriptor_set *) entry;
return VK_SUCCESS;
}
link = &entry->next;
}
if (pool->free_list != EMPTY) {
return vk_error(VK_ERROR_FRAGMENTED_POOL);
} else {
return vk_error(VK_ERROR_OUT_OF_POOL_MEMORY);
}
}
}
static void
anv_descriptor_pool_free_set(struct anv_descriptor_pool *pool,
struct anv_descriptor_set *set)
{
/* Put the descriptor set allocation back on the free list. */
const uint32_t index = (char *) set - pool->data;
if (index + set->size == pool->next) {
pool->next = index;
} else {
struct pool_free_list_entry *entry = (struct pool_free_list_entry *) set;
entry->next = pool->free_list;
entry->size = set->size;
pool->free_list = (char *) entry - pool->data;
}
}
struct surface_state_free_list_entry {
void *next;
struct anv_state state;
};
static struct anv_state
anv_descriptor_pool_alloc_state(struct anv_descriptor_pool *pool)
{
struct surface_state_free_list_entry *entry =
pool->surface_state_free_list;
if (entry) {
struct anv_state state = entry->state;
pool->surface_state_free_list = entry->next;
assert(state.alloc_size == 64);
return state;
} else {
return anv_state_stream_alloc(&pool->surface_state_stream, 64, 64);
}
}
static void
anv_descriptor_pool_free_state(struct anv_descriptor_pool *pool,
struct anv_state state)
{
/* Put the buffer view surface state back on the free list. */
struct surface_state_free_list_entry *entry = state.map;
entry->next = pool->surface_state_free_list;
entry->state = state;
pool->surface_state_free_list = entry;
}
size_t
anv_descriptor_set_layout_size(const struct anv_descriptor_set_layout *layout)
{
return
sizeof(struct anv_descriptor_set) +
layout->size * sizeof(struct anv_descriptor) +
layout->buffer_view_count * sizeof(struct anv_buffer_view);
}
VkResult
anv_descriptor_set_create(struct anv_device *device,
struct anv_descriptor_pool *pool,
struct anv_descriptor_set_layout *layout,
struct anv_descriptor_set **out_set)
{
struct anv_descriptor_set *set;
const size_t size = anv_descriptor_set_layout_size(layout);
VkResult result = anv_descriptor_pool_alloc_set(pool, size, &set);
if (result != VK_SUCCESS)
return result;
if (layout->descriptor_buffer_size) {
/* Align the size to 32 so that alignment gaps don't cause extra holes
* in the heap which can lead to bad performance.
*/
uint32_t set_buffer_size = ALIGN(layout->descriptor_buffer_size, 32);
uint64_t pool_vma_offset =
util_vma_heap_alloc(&pool->bo_heap, set_buffer_size, 32);
if (pool_vma_offset == 0) {
anv_descriptor_pool_free_set(pool, set);
return vk_error(VK_ERROR_FRAGMENTED_POOL);
}
assert(pool_vma_offset >= POOL_HEAP_OFFSET &&
pool_vma_offset - POOL_HEAP_OFFSET <= INT32_MAX);
set->desc_mem.offset = pool_vma_offset - POOL_HEAP_OFFSET;
set->desc_mem.alloc_size = set_buffer_size;
set->desc_mem.map = pool->bo.map + set->desc_mem.offset;
set->desc_surface_state = anv_descriptor_pool_alloc_state(pool);
anv_fill_buffer_surface_state(device, set->desc_surface_state,
ISL_FORMAT_R32G32B32A32_FLOAT,
(struct anv_address) {
.bo = &pool->bo,
.offset = set->desc_mem.offset,
},
layout->descriptor_buffer_size, 1);
} else {
set->desc_mem = ANV_STATE_NULL;
set->desc_surface_state = ANV_STATE_NULL;
}
set->pool = pool;
set->layout = layout;
anv_descriptor_set_layout_ref(layout);
set->size = size;
set->buffer_views =
(struct anv_buffer_view *) &set->descriptors[layout->size];
set->buffer_view_count = layout->buffer_view_count;
/* By defining the descriptors to be zero now, we can later verify that
* a descriptor has not been populated with user data.
*/
memset(set->descriptors, 0, sizeof(struct anv_descriptor) * layout->size);
/* Go through and fill out immutable samplers if we have any */
struct anv_descriptor *desc = set->descriptors;
for (uint32_t b = 0; b < layout->binding_count; b++) {
if (layout->binding[b].immutable_samplers) {
for (uint32_t i = 0; i < layout->binding[b].array_size; i++) {
/* The type will get changed to COMBINED_IMAGE_SAMPLER in
* UpdateDescriptorSets if needed. However, if the descriptor
* set has an immutable sampler, UpdateDescriptorSets may never
* touch it, so we need to make sure it's 100% valid now.
*
* We don't need to actually provide a sampler because the helper
* will always write in the immutable sampler regardless of what
* is in the sampler parameter.
*/
struct VkDescriptorImageInfo info = { };
anv_descriptor_set_write_image_view(device, set, &info,
VK_DESCRIPTOR_TYPE_SAMPLER,
b, i);
}
}
desc += layout->binding[b].array_size;
}
/* Allocate surface state for the buffer views. */
for (uint32_t b = 0; b < layout->buffer_view_count; b++) {
set->buffer_views[b].surface_state =
anv_descriptor_pool_alloc_state(pool);
}
list_addtail(&set->pool_link, &pool->desc_sets);
*out_set = set;
return VK_SUCCESS;
}
void
anv_descriptor_set_destroy(struct anv_device *device,
struct anv_descriptor_pool *pool,
struct anv_descriptor_set *set)
{
anv_descriptor_set_layout_unref(device, set->layout);
if (set->desc_mem.alloc_size) {
util_vma_heap_free(&pool->bo_heap,
(uint64_t)set->desc_mem.offset + POOL_HEAP_OFFSET,
set->desc_mem.alloc_size);
anv_descriptor_pool_free_state(pool, set->desc_surface_state);
}
for (uint32_t b = 0; b < set->buffer_view_count; b++)
anv_descriptor_pool_free_state(pool, set->buffer_views[b].surface_state);
list_del(&set->pool_link);
anv_descriptor_pool_free_set(pool, set);
}
VkResult anv_AllocateDescriptorSets(
VkDevice _device,
const VkDescriptorSetAllocateInfo* pAllocateInfo,
VkDescriptorSet* pDescriptorSets)
{
ANV_FROM_HANDLE(anv_device, device, _device);
ANV_FROM_HANDLE(anv_descriptor_pool, pool, pAllocateInfo->descriptorPool);
VkResult result = VK_SUCCESS;
struct anv_descriptor_set *set;
uint32_t i;
for (i = 0; i < pAllocateInfo->descriptorSetCount; i++) {
ANV_FROM_HANDLE(anv_descriptor_set_layout, layout,
pAllocateInfo->pSetLayouts[i]);
result = anv_descriptor_set_create(device, pool, layout, &set);
if (result != VK_SUCCESS)
break;
pDescriptorSets[i] = anv_descriptor_set_to_handle(set);
}
if (result != VK_SUCCESS)
anv_FreeDescriptorSets(_device, pAllocateInfo->descriptorPool,
i, pDescriptorSets);
return result;
}
VkResult anv_FreeDescriptorSets(
VkDevice _device,
VkDescriptorPool descriptorPool,
uint32_t count,
const VkDescriptorSet* pDescriptorSets)
{
ANV_FROM_HANDLE(anv_device, device, _device);
ANV_FROM_HANDLE(anv_descriptor_pool, pool, descriptorPool);
for (uint32_t i = 0; i < count; i++) {
ANV_FROM_HANDLE(anv_descriptor_set, set, pDescriptorSets[i]);
if (!set)
continue;
anv_descriptor_set_destroy(device, pool, set);
}
return VK_SUCCESS;
}
static void
anv_descriptor_set_write_image_param(uint32_t *param_desc_map,
const struct brw_image_param *param)
{
#define WRITE_PARAM_FIELD(field, FIELD) \
for (unsigned i = 0; i < ARRAY_SIZE(param->field); i++) \
param_desc_map[BRW_IMAGE_PARAM_##FIELD##_OFFSET + i] = param->field[i]
WRITE_PARAM_FIELD(offset, OFFSET);
WRITE_PARAM_FIELD(size, SIZE);
WRITE_PARAM_FIELD(stride, STRIDE);
WRITE_PARAM_FIELD(tiling, TILING);
WRITE_PARAM_FIELD(swizzling, SWIZZLING);
WRITE_PARAM_FIELD(size, SIZE);
#undef WRITE_PARAM_FIELD
}
static uint32_t
anv_surface_state_to_handle(struct anv_state state)
{
/* Bits 31:12 of the bindless surface offset in the extended message
* descriptor is bits 25:6 of the byte-based address.
*/
assert(state.offset >= 0);
uint32_t offset = state.offset;
assert((offset & 0x3f) == 0 && offset < (1 << 26));
return offset << 6;
}
void
anv_descriptor_set_write_image_view(struct anv_device *device,
struct anv_descriptor_set *set,
const VkDescriptorImageInfo * const info,
VkDescriptorType type,
uint32_t binding,
uint32_t element)
{
const struct anv_descriptor_set_binding_layout *bind_layout =
&set->layout->binding[binding];
struct anv_descriptor *desc =
&set->descriptors[bind_layout->descriptor_index + element];
struct anv_image_view *image_view = NULL;
struct anv_sampler *sampler = NULL;
/* We get called with just VK_DESCRIPTOR_TYPE_SAMPLER as part of descriptor
* set initialization to set the bindless samplers.
*/
assert(type == bind_layout->type ||
type == VK_DESCRIPTOR_TYPE_SAMPLER);
switch (type) {
case VK_DESCRIPTOR_TYPE_SAMPLER:
sampler = anv_sampler_from_handle(info->sampler);
break;
case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
image_view = anv_image_view_from_handle(info->imageView);
sampler = anv_sampler_from_handle(info->sampler);
break;
case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
image_view = anv_image_view_from_handle(info->imageView);
break;
default:
unreachable("invalid descriptor type");
}
/* If this descriptor has an immutable sampler, we don't want to stomp on
* it.
*/
sampler = bind_layout->immutable_samplers ?
bind_layout->immutable_samplers[element] :
sampler;
*desc = (struct anv_descriptor) {
.type = type,
.layout = info->imageLayout,
.image_view = image_view,
.sampler = sampler,
};
void *desc_map = set->desc_mem.map + bind_layout->descriptor_offset +
element * anv_descriptor_size(bind_layout);
if (bind_layout->data & ANV_DESCRIPTOR_SAMPLED_IMAGE) {
struct anv_sampled_image_descriptor desc_data[3];
memset(desc_data, 0, sizeof(desc_data));
if (image_view) {
for (unsigned p = 0; p < image_view->n_planes; p++) {
struct anv_surface_state sstate =
(desc->layout == VK_IMAGE_LAYOUT_GENERAL) ?
image_view->planes[p].general_sampler_surface_state :
image_view->planes[p].optimal_sampler_surface_state;
desc_data[p].image = anv_surface_state_to_handle(sstate.state);
}
}
if (sampler) {
for (unsigned p = 0; p < sampler->n_planes; p++)
desc_data[p].sampler = sampler->bindless_state.offset + p * 32;
}
/* We may have max_plane_count < 0 if this isn't a sampled image but it
* can be no more than the size of our array of handles.
*/
assert(bind_layout->max_plane_count <= ARRAY_SIZE(desc_data));
memcpy(desc_map, desc_data,
MAX2(1, bind_layout->max_plane_count) * sizeof(desc_data[0]));
}
if (bind_layout->data & ANV_DESCRIPTOR_STORAGE_IMAGE) {
assert(!(bind_layout->data & ANV_DESCRIPTOR_IMAGE_PARAM));
assert(image_view->n_planes == 1);
struct anv_storage_image_descriptor desc_data = {
.read_write = anv_surface_state_to_handle(
image_view->planes[0].storage_surface_state.state),
.write_only = anv_surface_state_to_handle(
image_view->planes[0].writeonly_storage_surface_state.state),
};
memcpy(desc_map, &desc_data, sizeof(desc_data));
}
if (bind_layout->data & ANV_DESCRIPTOR_IMAGE_PARAM) {
/* Storage images can only ever have one plane */
assert(image_view->n_planes == 1);
const struct brw_image_param *image_param =
&image_view->planes[0].storage_image_param;
anv_descriptor_set_write_image_param(desc_map, image_param);
}
if (image_view && (bind_layout->data & ANV_DESCRIPTOR_TEXTURE_SWIZZLE)) {
assert(!(bind_layout->data & ANV_DESCRIPTOR_SAMPLED_IMAGE));
assert(image_view);
struct anv_texture_swizzle_descriptor desc_data[3];
memset(desc_data, 0, sizeof(desc_data));
for (unsigned p = 0; p < image_view->n_planes; p++) {
desc_data[p] = (struct anv_texture_swizzle_descriptor) {
.swizzle = {
(uint8_t)image_view->planes[p].isl.swizzle.r,
(uint8_t)image_view->planes[p].isl.swizzle.g,
(uint8_t)image_view->planes[p].isl.swizzle.b,
(uint8_t)image_view->planes[p].isl.swizzle.a,
},
};
}
memcpy(desc_map, desc_data,
MAX2(1, bind_layout->max_plane_count) * sizeof(desc_data[0]));
}
}
void
anv_descriptor_set_write_buffer_view(struct anv_device *device,
struct anv_descriptor_set *set,
VkDescriptorType type,
struct anv_buffer_view *buffer_view,
uint32_t binding,
uint32_t element)
{
const struct anv_descriptor_set_binding_layout *bind_layout =
&set->layout->binding[binding];
struct anv_descriptor *desc =
&set->descriptors[bind_layout->descriptor_index + element];
assert(type == bind_layout->type);
*desc = (struct anv_descriptor) {
.type = type,
.buffer_view = buffer_view,
};
void *desc_map = set->desc_mem.map + bind_layout->descriptor_offset +
element * anv_descriptor_size(bind_layout);
if (bind_layout->data & ANV_DESCRIPTOR_SAMPLED_IMAGE) {
struct anv_sampled_image_descriptor desc_data = {
.image = anv_surface_state_to_handle(buffer_view->surface_state),
};
memcpy(desc_map, &desc_data, sizeof(desc_data));
}
if (bind_layout->data & ANV_DESCRIPTOR_STORAGE_IMAGE) {
assert(!(bind_layout->data & ANV_DESCRIPTOR_IMAGE_PARAM));
struct anv_storage_image_descriptor desc_data = {
.read_write = anv_surface_state_to_handle(
buffer_view->storage_surface_state),
.write_only = anv_surface_state_to_handle(
buffer_view->writeonly_storage_surface_state),
};
memcpy(desc_map, &desc_data, sizeof(desc_data));
}
if (bind_layout->data & ANV_DESCRIPTOR_IMAGE_PARAM) {
anv_descriptor_set_write_image_param(desc_map,
&buffer_view->storage_image_param);
}
}
void
anv_descriptor_set_write_buffer(struct anv_device *device,
struct anv_descriptor_set *set,
struct anv_state_stream *alloc_stream,
VkDescriptorType type,
struct anv_buffer *buffer,
uint32_t binding,
uint32_t element,
VkDeviceSize offset,
VkDeviceSize range)
{
const struct anv_descriptor_set_binding_layout *bind_layout =
&set->layout->binding[binding];
struct anv_descriptor *desc =
&set->descriptors[bind_layout->descriptor_index + element];
assert(type == bind_layout->type);
struct anv_address bind_addr = anv_address_add(buffer->address, offset);
uint64_t bind_range = anv_buffer_get_range(buffer, offset, range);
if (type == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC ||
type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) {
*desc = (struct anv_descriptor) {
.type = type,
.buffer = buffer,
.offset = offset,
.range = range,
};
} else {
assert(bind_layout->data & ANV_DESCRIPTOR_BUFFER_VIEW);
struct anv_buffer_view *bview =
&set->buffer_views[bind_layout->buffer_view_index + element];
bview->format = anv_isl_format_for_descriptor_type(type);
bview->range = bind_range;
bview->address = bind_addr;
/* If we're writing descriptors through a push command, we need to
* allocate the surface state from the command buffer. Otherwise it will
* be allocated by the descriptor pool when calling
* vkAllocateDescriptorSets. */
if (alloc_stream)
bview->surface_state = anv_state_stream_alloc(alloc_stream, 64, 64);
anv_fill_buffer_surface_state(device, bview->surface_state,
bview->format, bind_addr, bind_range, 1);
*desc = (struct anv_descriptor) {
.type = type,
.buffer_view = bview,
};
}
void *desc_map = set->desc_mem.map + bind_layout->descriptor_offset +
element * anv_descriptor_size(bind_layout);
if (bind_layout->data & ANV_DESCRIPTOR_ADDRESS_RANGE) {
struct anv_address_range_descriptor desc = {
.address = anv_address_physical(bind_addr),
.range = bind_range,
};
memcpy(desc_map, &desc, sizeof(desc));
}
}
void
anv_descriptor_set_write_inline_uniform_data(struct anv_device *device,
struct anv_descriptor_set *set,
uint32_t binding,
const void *data,
size_t offset,
size_t size)
{
const struct anv_descriptor_set_binding_layout *bind_layout =
&set->layout->binding[binding];
assert(bind_layout->data & ANV_DESCRIPTOR_INLINE_UNIFORM);
void *desc_map = set->desc_mem.map + bind_layout->descriptor_offset;
memcpy(desc_map + offset, data, size);
}
void anv_UpdateDescriptorSets(
VkDevice _device,
uint32_t descriptorWriteCount,
const VkWriteDescriptorSet* pDescriptorWrites,
uint32_t descriptorCopyCount,
const VkCopyDescriptorSet* pDescriptorCopies)
{
ANV_FROM_HANDLE(anv_device, device, _device);
for (uint32_t i = 0; i < descriptorWriteCount; i++) {
const VkWriteDescriptorSet *write = &pDescriptorWrites[i];
ANV_FROM_HANDLE(anv_descriptor_set, set, write->dstSet);
switch (write->descriptorType) {
case VK_DESCRIPTOR_TYPE_SAMPLER:
case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
for (uint32_t j = 0; j < write->descriptorCount; j++) {
anv_descriptor_set_write_image_view(device, set,
write->pImageInfo + j,
write->descriptorType,
write->dstBinding,
write->dstArrayElement + j);
}
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
for (uint32_t j = 0; j < write->descriptorCount; j++) {
ANV_FROM_HANDLE(anv_buffer_view, bview,
write->pTexelBufferView[j]);
anv_descriptor_set_write_buffer_view(device, set,
write->descriptorType,
bview,
write->dstBinding,
write->dstArrayElement + j);
}
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
for (uint32_t j = 0; j < write->descriptorCount; j++) {
assert(write->pBufferInfo[j].buffer);
ANV_FROM_HANDLE(anv_buffer, buffer, write->pBufferInfo[j].buffer);
assert(buffer);
anv_descriptor_set_write_buffer(device, set,
NULL,
write->descriptorType,
buffer,
write->dstBinding,
write->dstArrayElement + j,
write->pBufferInfo[j].offset,
write->pBufferInfo[j].range);
}
break;
case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT: {
const VkWriteDescriptorSetInlineUniformBlockEXT *inline_write =
vk_find_struct_const(write->pNext,
WRITE_DESCRIPTOR_SET_INLINE_UNIFORM_BLOCK_EXT);
assert(inline_write->dataSize == write->descriptorCount);
anv_descriptor_set_write_inline_uniform_data(device, set,
write->dstBinding,
inline_write->pData,
write->dstArrayElement,
inline_write->dataSize);
break;
}
default:
break;
}
}
for (uint32_t i = 0; i < descriptorCopyCount; i++) {
const VkCopyDescriptorSet *copy = &pDescriptorCopies[i];
ANV_FROM_HANDLE(anv_descriptor_set, src, copy->srcSet);
ANV_FROM_HANDLE(anv_descriptor_set, dst, copy->dstSet);
const struct anv_descriptor_set_binding_layout *src_layout =
&src->layout->binding[copy->srcBinding];
struct anv_descriptor *src_desc =
&src->descriptors[src_layout->descriptor_index];
src_desc += copy->srcArrayElement;
const struct anv_descriptor_set_binding_layout *dst_layout =
&dst->layout->binding[copy->dstBinding];
struct anv_descriptor *dst_desc =
&dst->descriptors[dst_layout->descriptor_index];
dst_desc += copy->dstArrayElement;
for (uint32_t j = 0; j < copy->descriptorCount; j++)
dst_desc[j] = src_desc[j];
if (src_layout->data & ANV_DESCRIPTOR_INLINE_UNIFORM) {
assert(src_layout->data == ANV_DESCRIPTOR_INLINE_UNIFORM);
memcpy(dst->desc_mem.map + dst_layout->descriptor_offset +
copy->dstArrayElement,
src->desc_mem.map + src_layout->descriptor_offset +
copy->srcArrayElement,
copy->descriptorCount);
} else {
unsigned desc_size = anv_descriptor_size(src_layout);
if (desc_size > 0) {
assert(desc_size == anv_descriptor_size(dst_layout));
memcpy(dst->desc_mem.map + dst_layout->descriptor_offset +
copy->dstArrayElement * desc_size,
src->desc_mem.map + src_layout->descriptor_offset +
copy->srcArrayElement * desc_size,
copy->descriptorCount * desc_size);
}
}
}
}
/*
* Descriptor update templates.
*/
void
anv_descriptor_set_write_template(struct anv_device *device,
struct anv_descriptor_set *set,
struct anv_state_stream *alloc_stream,
const struct anv_descriptor_update_template *template,
const void *data)
{
for (uint32_t i = 0; i < template->entry_count; i++) {
const struct anv_descriptor_template_entry *entry =
&template->entries[i];
switch (entry->type) {
case VK_DESCRIPTOR_TYPE_SAMPLER:
case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER:
case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE:
case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE:
case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT:
for (uint32_t j = 0; j < entry->array_count; j++) {
const VkDescriptorImageInfo *info =
data + entry->offset + j * entry->stride;
anv_descriptor_set_write_image_view(device, set,
info, entry->type,
entry->binding,
entry->array_element + j);
}
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER:
case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER:
for (uint32_t j = 0; j < entry->array_count; j++) {
const VkBufferView *_bview =
data + entry->offset + j * entry->stride;
ANV_FROM_HANDLE(anv_buffer_view, bview, *_bview);
anv_descriptor_set_write_buffer_view(device, set,
entry->type,
bview,
entry->binding,
entry->array_element + j);
}
break;
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER:
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER:
case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC:
case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC:
for (uint32_t j = 0; j < entry->array_count; j++) {
const VkDescriptorBufferInfo *info =
data + entry->offset + j * entry->stride;
ANV_FROM_HANDLE(anv_buffer, buffer, info->buffer);
anv_descriptor_set_write_buffer(device, set,
alloc_stream,
entry->type,
buffer,
entry->binding,
entry->array_element + j,
info->offset, info->range);
}
break;
case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT:
anv_descriptor_set_write_inline_uniform_data(device, set,
entry->binding,
data + entry->offset,
entry->array_element,
entry->array_count);
break;
default:
break;
}
}
}
VkResult anv_CreateDescriptorUpdateTemplate(
VkDevice _device,
const VkDescriptorUpdateTemplateCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkDescriptorUpdateTemplate* pDescriptorUpdateTemplate)
{
ANV_FROM_HANDLE(anv_device, device, _device);
struct anv_descriptor_update_template *template;
size_t size = sizeof(*template) +
pCreateInfo->descriptorUpdateEntryCount * sizeof(template->entries[0]);
template = vk_alloc2(&device->alloc, pAllocator, size, 8,
VK_SYSTEM_ALLOCATION_SCOPE_OBJECT);
if (template == NULL)
return vk_error(VK_ERROR_OUT_OF_HOST_MEMORY);
template->bind_point = pCreateInfo->pipelineBindPoint;
if (pCreateInfo->templateType == VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET)
template->set = pCreateInfo->set;
template->entry_count = pCreateInfo->descriptorUpdateEntryCount;
for (uint32_t i = 0; i < template->entry_count; i++) {
const VkDescriptorUpdateTemplateEntry *pEntry =
&pCreateInfo->pDescriptorUpdateEntries[i];
template->entries[i] = (struct anv_descriptor_template_entry) {
.type = pEntry->descriptorType,
.binding = pEntry->dstBinding,
.array_element = pEntry->dstArrayElement,
.array_count = pEntry->descriptorCount,
.offset = pEntry->offset,
.stride = pEntry->stride,
};
}
*pDescriptorUpdateTemplate =
anv_descriptor_update_template_to_handle(template);
return VK_SUCCESS;
}
void anv_DestroyDescriptorUpdateTemplate(
VkDevice _device,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const VkAllocationCallbacks* pAllocator)
{
ANV_FROM_HANDLE(anv_device, device, _device);
ANV_FROM_HANDLE(anv_descriptor_update_template, template,
descriptorUpdateTemplate);
vk_free2(&device->alloc, pAllocator, template);
}
void anv_UpdateDescriptorSetWithTemplate(
VkDevice _device,
VkDescriptorSet descriptorSet,
VkDescriptorUpdateTemplate descriptorUpdateTemplate,
const void* pData)
{
ANV_FROM_HANDLE(anv_device, device, _device);
ANV_FROM_HANDLE(anv_descriptor_set, set, descriptorSet);
ANV_FROM_HANDLE(anv_descriptor_update_template, template,
descriptorUpdateTemplate);
anv_descriptor_set_write_template(device, set, NULL, template, pData);
}
| 37.237037 | 89 | 0.636894 | [
"render"
] |
f4e452f6ab3befcf3e76671283a644a8a0265a04 | 5,668 | h | C | src/sdk/sql_sdk_base_test.h | Nicholas-SR/OpenMLDB | 368a2d087e1084da142e2fedf4637e3d0a3f6b3b | [
"Apache-2.0"
] | 1 | 2021-12-17T03:18:57.000Z | 2021-12-17T03:18:57.000Z | src/sdk/sql_sdk_base_test.h | wei20024/OpenMLDB | 16b426bcba18f70e083179f82db51e71e65d1bf6 | [
"Apache-2.0"
] | null | null | null | src/sdk/sql_sdk_base_test.h | wei20024/OpenMLDB | 16b426bcba18f70e083179f82db51e71e65d1bf6 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 4Paradigm
*
* 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 SRC_SDK_SQL_SDK_BASE_TEST_H_
#define SRC_SDK_SQL_SDK_BASE_TEST_H_
#include <sched.h>
#include <unistd.h>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "sdk/sql_router.h"
#include "test/base_test.h"
namespace openmldb {
namespace sdk {
enum InsertRule {
kNotInsertFirstInput,
kNotInsertLastRowOfFirstInput,
kInsertAllInputs,
};
class SQLSDKTest : public openmldb::test::SQLCaseTest {
public:
SQLSDKTest() : openmldb::test::SQLCaseTest() {}
~SQLSDKTest() {}
void SetUp() { LOG(INFO) << "SQLSDKTest TearDown"; }
void TearDown() { LOG(INFO) << "SQLSDKTest TearDown"; }
static void CreateDB(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router);
static void CreateTables(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, int partition_num = 1);
static void DropTables(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router);
static void InsertTables(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, InsertRule insert_rule);
static void CovertHybridSERowToRequestRow(hybridse::codec::RowView* row_view,
std::shared_ptr<openmldb::sdk::SQLRequestRow> request_row);
static void BatchExecuteSQL(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, const std::vector<std::string>& tbEndpoints);
static void RunBatchModeSDK(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, const std::vector<std::string>& tbEndpoints);
static void CreateProcedure(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, bool is_batch = false);
static void DropProcedure(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router);
};
class SQLSDKQueryTest : public SQLSDKTest {
public:
SQLSDKQueryTest() : SQLSDKTest() {}
~SQLSDKQueryTest() {}
static void RequestExecuteSQL(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, bool has_batch_request, bool is_procedure = false,
bool is_asyn = false);
static void RunRequestModeSDK(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router);
static void DistributeRunRequestModeSDK(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, int32_t partition_num = 8);
void RunRequestProcedureModeSDK(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, bool is_asyn);
void DistributeRunRequestProcedureModeSDK(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, int32_t partition_num, bool is_asyn);
static void BatchRequestExecuteSQL(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, bool has_batch_request, bool is_procedure,
bool is_asy);
static void BatchRequestExecuteSQLWithCommonColumnIndices(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router,
const std::set<size_t>& common_column_indices,
bool is_procedure = false, bool is_asyn = false);
static void RunBatchRequestModeSDK(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router);
static void DistributeRunBatchRequestModeSDK(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, int32_t partition_num = 8);
};
class SQLSDKBatchRequestQueryTest : public SQLSDKQueryTest {
public:
SQLSDKBatchRequestQueryTest() : SQLSDKQueryTest() {}
~SQLSDKBatchRequestQueryTest() {}
static void DistributeRunBatchRequestProcedureModeSDK(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, int32_t partition_num,
bool is_asyn);
static void RunBatchRequestProcedureModeSDK(hybridse::sqlcase::SqlCase& sql_case, // NOLINT
std::shared_ptr<SQLRouter> router, bool is_asyn);
};
} // namespace sdk
} // namespace openmldb
#endif // SRC_SDK_SQL_SDK_BASE_TEST_H_
| 49.719298 | 119 | 0.621383 | [
"vector"
] |
f4e8208c3f2e238a4acecab4579fc955092d5978 | 4,972 | h | C | paddle/fluid/operators/auc_op.h | yucheng20170406/Paddle | e91fa1741be58899a58e55f3f1625a51fd95aba0 | [
"Apache-2.0"
] | null | null | null | paddle/fluid/operators/auc_op.h | yucheng20170406/Paddle | e91fa1741be58899a58e55f3f1625a51fd95aba0 | [
"Apache-2.0"
] | 3 | 2018-04-11T10:25:51.000Z | 2018-04-12T01:17:22.000Z | paddle/fluid/operators/auc_op.h | zhaofenqiang/PaddleOnACL | e543af14589e2311ae2f3f6c9887b537d2048666 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#pragma once
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
namespace paddle {
namespace operators {
using Tensor = framework::Tensor;
template <typename T, int MajorType = Eigen::RowMajor,
typename IndexType = Eigen::DenseIndex>
using EigenVector = framework::EigenVector<T, MajorType, IndexType>;
template <typename DeviceContext, typename T>
class AucKernel : public framework::OpKernel<T> {
public:
void Compute(const framework::ExecutionContext& ctx) const override {
auto* inference = ctx.Input<Tensor>("Out");
auto* label = ctx.Input<Tensor>("Label");
auto* auc = ctx.Output<Tensor>("AUC");
float* auc_data = auc->mutable_data<float>(ctx.GetPlace());
std::string curve = ctx.Attr<std::string>("curve");
int num_thresholds = ctx.Attr<int>("num_thresholds");
std::vector<float> thresholds_list;
thresholds_list.reserve(num_thresholds);
for (int i = 1; i < num_thresholds - 1; i++) {
thresholds_list[i] = (float)i / (num_thresholds - 1);
}
const float kEpsilon = 1e-7;
thresholds_list[0] = 0.0f - kEpsilon;
thresholds_list[num_thresholds - 1] = 1.0f + kEpsilon;
size_t batch_size = inference->dims()[0];
size_t inference_width = inference->dims()[1];
const T* inference_data = inference->data<T>();
const int64_t* label_data = label->data<int64_t>();
// Create local tensor for storing the curve: TP, FN, TN, FP
// TODO(typhoonzero): use eigen op to caculate these values.
Tensor true_positive, false_positive, true_negative, false_negative;
true_positive.Resize({num_thresholds});
false_negative.Resize({num_thresholds});
true_negative.Resize({num_thresholds});
false_positive.Resize({num_thresholds});
int64_t* tp_data = true_positive.mutable_data<int64_t>(ctx.GetPlace());
int64_t* fn_data = false_negative.mutable_data<int64_t>(ctx.GetPlace());
int64_t* tn_data = true_negative.mutable_data<int64_t>(ctx.GetPlace());
int64_t* fp_data = false_positive.mutable_data<int64_t>(ctx.GetPlace());
for (int idx_thresh = 0; idx_thresh < num_thresholds; idx_thresh++) {
// caculate TP, FN, TN, FP for current thresh
int64_t tp = 0, fn = 0, tn = 0, fp = 0;
for (size_t i = 0; i < batch_size; i++) {
// NOTE: label_data used as bool, labels >0 will be treated as true.
if (label_data[i]) {
// use first(max) data in each row
if (inference_data[i * inference_width] >=
(thresholds_list[idx_thresh])) {
tp++;
} else {
fn++;
}
} else {
if (inference_data[i * inference_width] >=
(thresholds_list[idx_thresh])) {
fp++;
} else {
tn++;
}
}
}
// store rates
tp_data[idx_thresh] = tp;
fn_data[idx_thresh] = fn;
tn_data[idx_thresh] = tn;
fp_data[idx_thresh] = fp;
}
// epsilon to avoid divide by zero.
float epsilon = 1e-6;
// Riemann sum to caculate auc.
Tensor tp_rate, fp_rate, rec_rate;
tp_rate.Resize({num_thresholds});
fp_rate.Resize({num_thresholds});
rec_rate.Resize({num_thresholds});
float* tp_rate_data = tp_rate.mutable_data<float>(ctx.GetPlace());
float* fp_rate_data = fp_rate.mutable_data<float>(ctx.GetPlace());
float* rec_rate_data = rec_rate.mutable_data<float>(ctx.GetPlace());
for (int i = 0; i < num_thresholds; i++) {
tp_rate_data[i] =
((float)tp_data[i] + epsilon) / (tp_data[i] + fn_data[i] + epsilon);
fp_rate_data[i] = (float)fp_data[i] / (fp_data[i] + tn_data[i] + epsilon);
rec_rate_data[i] =
((float)tp_data[i] + epsilon) / (tp_data[i] + fp_data[i] + epsilon);
}
*auc_data = 0.0f;
if (curve == "ROC") {
for (int i = 0; i < num_thresholds - 1; i++) {
auto dx = fp_rate_data[i] - fp_rate_data[i + 1];
auto y = (tp_rate_data[i] + tp_rate_data[i + 1]) / 2.0f;
*auc_data = *auc_data + dx * y;
}
} else if (curve == "PR") {
for (int i = 1; i < num_thresholds; i++) {
auto dx = tp_rate_data[i] - tp_rate_data[i - 1];
auto y = (rec_rate_data[i] + rec_rate_data[i - 1]) / 2.0f;
*auc_data = *auc_data + dx * y;
}
}
}
};
} // namespace operators
} // namespace paddle
| 37.383459 | 80 | 0.640788 | [
"vector"
] |
f4e9f42729287a17931e6a1a63c86c399996b0e3 | 2,250 | h | C | cartographer_grpc/mapping/pose_graph_stub.h | RellyLiu/Cartographer | c32cb49b0174b6af7c482e1f8f1b128ac659241d | [
"Apache-2.0"
] | null | null | null | cartographer_grpc/mapping/pose_graph_stub.h | RellyLiu/Cartographer | c32cb49b0174b6af7c482e1f8f1b128ac659241d | [
"Apache-2.0"
] | null | null | null | cartographer_grpc/mapping/pose_graph_stub.h | RellyLiu/Cartographer | c32cb49b0174b6af7c482e1f8f1b128ac659241d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_GRPC_MAPPING_POSE_GRAPH_STUB_H_
#define CARTOGRAPHER_GRPC_MAPPING_POSE_GRAPH_STUB_H_
#include "cartographer/mapping/pose_graph_interface.h"
#include "grpc++/grpc++.h"
namespace cartographer_grpc {
namespace mapping {
class PoseGraphStub : public cartographer::mapping::PoseGraphInterface {
public:
PoseGraphStub(std::shared_ptr<grpc::Channel> client_channel);
PoseGraphStub(const PoseGraphStub&) = delete;
PoseGraphStub& operator=(const PoseGraphStub&) = delete;
void RunFinalOptimization() override;
cartographer::mapping::MapById<cartographer::mapping::SubmapId, SubmapData>
GetAllSubmapData() override;
cartographer::mapping::MapById<cartographer::mapping::SubmapId, SubmapPose>
GetAllSubmapPoses() override;
cartographer::transform::Rigid3d GetLocalToGlobalTransform(
int trajectory_id) override;
cartographer::mapping::MapById<cartographer::mapping::NodeId,
cartographer::mapping::TrajectoryNode>
GetTrajectoryNodes() override;
cartographer::mapping::MapById<cartographer::mapping::NodeId,
cartographer::mapping::TrajectoryNodePose>
GetTrajectoryNodePoses() override;
std::map<std::string, cartographer::transform::Rigid3d> GetLandmarkPoses()
override;
bool IsTrajectoryFinished(int trajectory_id) override;
std::vector<Constraint> constraints() override;
cartographer::mapping::proto::PoseGraph ToProto() override;
private:
std::shared_ptr<grpc::Channel> client_channel_;
};
} // namespace mapping
} // namespace cartographer_grpc
#endif // CARTOGRAPHER_GRPC_MAPPING_POSE_GRAPH_STUB_H_
| 37.5 | 77 | 0.758222 | [
"vector",
"transform"
] |
f4ef6a73261e960f4ab2494471f7365749a06da6 | 44,014 | h | C | drivers/gpu/msm/adreno.h | CaelestisZ/IrisCore | 6f0397e43335434ee58e418c9d1528833c57aea2 | [
"MIT"
] | 1 | 2020-06-28T00:49:21.000Z | 2020-06-28T00:49:21.000Z | drivers/gpu/msm/adreno.h | CaelestisZ/AetherAura | 1b30acb7e6921042722bc4aff160dc63a975abc2 | [
"MIT"
] | null | null | null | drivers/gpu/msm/adreno.h | CaelestisZ/AetherAura | 1b30acb7e6921042722bc4aff160dc63a975abc2 | [
"MIT"
] | 4 | 2020-05-26T12:40:11.000Z | 2021-07-15T06:46:33.000Z | /* Copyright (c) 2008-2014, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#ifndef __ADRENO_H
#define __ADRENO_H
#include "kgsl_device.h"
#include "kgsl_sharedmem.h"
#include "adreno_drawctxt.h"
#include "adreno_ringbuffer.h"
#include "adreno_profile.h"
#include "adreno_dispatch.h"
#include "kgsl_iommu.h"
#include <linux/stat.h>
#include <linux/delay.h>
#ifdef CONFIG_MSM_OCMEM
#include <soc/qcom/ocmem.h>
#endif
#include "a3xx_reg.h"
#include "a4xx_reg.h"
#define DEVICE_3D_NAME "kgsl-3d"
#define DEVICE_3D0_NAME "kgsl-3d0"
#define ADRENO_PRIORITY_MAX_RB_LEVELS 4
/* ADRENO_DEVICE - Given a kgsl_device return the adreno device struct */
#define ADRENO_DEVICE(device) \
container_of(device, struct adreno_device, dev)
/* ADRENO_CONTEXT - Given a context return the adreno context struct */
#define ADRENO_CONTEXT(context) \
container_of(context, struct adreno_context, base)
/* ADRENO_GPU_DEVICE - Given an adreno device return the GPU specific struct */
#define ADRENO_GPU_DEVICE(_a) ((_a)->gpucore->gpudev)
/* ADRENO_PERFCOUNTERS - Given an adreno device, return the perfcounters list */
#define ADRENO_PERFCOUNTERS(_a) \
(ADRENO_GPU_DEVICE(_a) ? ADRENO_GPU_DEVICE(_a)->perfcounters : NULL)
#define ADRENO_CHIPID_CORE(_id) (((_id) >> 24) & 0xFF)
#define ADRENO_CHIPID_MAJOR(_id) (((_id) >> 16) & 0xFF)
#define ADRENO_CHIPID_MINOR(_id) (((_id) >> 8) & 0xFF)
#define ADRENO_CHIPID_PATCH(_id) ((_id) & 0xFF)
/* ADRENO_GPUREV - Return the GPU ID for the given adreno_device */
#define ADRENO_GPUREV(_a) ((_a)->gpucore->gpurev)
/*
* ADRENO_FEATURE - return true if the specified feature is supported by the GPU
* core
*/
#define ADRENO_FEATURE(_dev, _bit) \
((_dev)->gpucore->features & (_bit))
/*
* return the dispatcher cmdqueue in which the given cmdbatch should
* be submitted
*/
#define ADRENO_CMDBATCH_DISPATCH_CMDQUEUE(c) \
(&((ADRENO_CONTEXT(c->context))->rb->dispatch_q))
/* Adreno core features */
/* The core uses OCMEM for GMEM/binning memory */
#define ADRENO_USES_OCMEM BIT(0)
/* The core requires the TLB to be flushed on map */
#define IOMMU_FLUSH_TLB_ON_MAP BIT(1)
/* The core supports an accelerated warm start */
#define ADRENO_WARM_START BIT(2)
/* The core supports the microcode bootstrap functionality */
#define ADRENO_USE_BOOTSTRAP BIT(3)
/* The microcode for the code supports the IOMMU sync lock functionality */
#define ADRENO_HAS_IOMMU_SYNC_LOCK BIT(4)
/* The core supports SP/TP hw controlled power collapse */
#define ADRENO_SPTP_PC BIT(5)
/* The core supports Peak Power Detection(PPD)*/
#define ADRENO_PPD BIT(6)
/* The microcode supports register to register copy and compare */
#define ADRENO_HAS_REG_TO_REG_CMDS BIT(7)
/* The GPU supports content protection */
#define ADRENO_CONTENT_PROTECTION BIT(8)
/* Flags to control command packet settings */
#define KGSL_CMD_FLAGS_NONE 0
#define KGSL_CMD_FLAGS_PMODE BIT(0)
#define KGSL_CMD_FLAGS_INTERNAL_ISSUE BIT(1)
#define KGSL_CMD_FLAGS_WFI BIT(2)
#define KGSL_CMD_FLAGS_PROFILE BIT(3)
#define KGSL_CMD_FLAGS_PWRON_FIXUP BIT(4)
#define KGSL_CMD_FLAGS_MEMLIST BIT(5)
/* Command identifiers */
#define KGSL_CONTEXT_TO_MEM_IDENTIFIER 0x2EADBEEF
#define KGSL_CMD_IDENTIFIER 0x2EEDFACE
#define KGSL_CMD_INTERNAL_IDENTIFIER 0x2EEDD00D
#define KGSL_START_OF_IB_IDENTIFIER 0x2EADEABE
#define KGSL_END_OF_IB_IDENTIFIER 0x2ABEDEAD
#define KGSL_END_OF_FRAME_IDENTIFIER 0x2E0F2E0F
#define KGSL_NOP_IB_IDENTIFIER 0x20F20F20
#define KGSL_START_OF_PROFILE_IDENTIFIER 0x2DEFADE1
#define KGSL_END_OF_PROFILE_IDENTIFIER 0x2DEFADE2
#define KGSL_PWRON_FIXUP_IDENTIFIER 0x2AFAFAFA
#define ADRENO_ISTORE_START 0x5000 /* Istore offset */
#define ADRENO_NUM_CTX_SWITCH_ALLOWED_BEFORE_DRAW 50
/* One cannot wait forever for the core to idle, so set an upper limit to the
* amount of time to wait for the core to go idle
*/
#define ADRENO_IDLE_TIMEOUT (20 * 1000)
enum adreno_gpurev {
ADRENO_REV_UNKNOWN = 0,
ADRENO_REV_A200 = 200,
ADRENO_REV_A203 = 203,
ADRENO_REV_A205 = 205,
ADRENO_REV_A220 = 220,
ADRENO_REV_A225 = 225,
ADRENO_REV_A304 = 304,
ADRENO_REV_A305 = 305,
ADRENO_REV_A305C = 306,
ADRENO_REV_A306 = 307,
ADRENO_REV_A310 = 310,
ADRENO_REV_A320 = 320,
ADRENO_REV_A330 = 330,
ADRENO_REV_A305B = 335,
ADRENO_REV_A405 = 405,
ADRENO_REV_A418 = 418,
ADRENO_REV_A420 = 420,
ADRENO_REV_A430 = 430,
};
#define ADRENO_SOFT_FAULT BIT(0)
#define ADRENO_HARD_FAULT BIT(1)
#define ADRENO_TIMEOUT_FAULT BIT(2)
#define ADRENO_IOMMU_PAGE_FAULT BIT(3)
#define ADRENO_SPTP_PC_CTRL 0
#define ADRENO_PPD_CTRL 1
struct adreno_gpudev;
struct adreno_busy_data {
unsigned int gpu_busy;
unsigned int vbif_ram_cycles;
unsigned int vbif_starved_ram;
};
/**
* struct adreno_gpu_core - A specific GPU core definition
* @gpurev: Unique GPU revision identifier
* @core: Match for the core version of the GPU
* @major: Match for the major version of the GPU
* @minor: Match for the minor version of the GPU
* @patchid: Match for the patch revision of the GPU
* @features: Common adreno features supported by this core
* @pm4fw_name: Filename for th PM4 firmware
* @pfpfw_name: Filename for the PFP firmware
* @gpudev: Pointer to the GPU family specific functions for this core
* @gmem_size: Amount of binning memory (GMEM/OCMEM) to reserve for the core
* @sync_lock_pm4_ver: For IOMMUv0 cores the version of PM4 microcode that
* supports the sync lock mechanism
* @sync_lock_pfp_ver: For IOMMUv0 cores the version of PFP microcode that
* supports the sync lock mechanism
* @pm4_jt_idx: Index of the jump table in the PM4 microcode
* @pm4_jt_addr: Address offset to load the jump table for the PM4 microcode
* @pfp_jt_idx: Index of the jump table in the PFP microcode
* @pfp_jt_addr: Address offset to load the jump table for the PFP microcode
* @pm4_bstrp_size: Size of the bootstrap loader for PM4 microcode
* @pfp_bstrp_size: Size of the bootstrap loader for PFP microcde
* @pfp_bstrp_ver: Version of the PFP microcode that supports bootstraping
* @shader_offset: Offset of shader from gpu reg base
* @shader_size: Shader size
*/
struct adreno_gpu_core {
enum adreno_gpurev gpurev;
unsigned int core, major, minor, patchid;
unsigned long features;
const char *pm4fw_name;
const char *pfpfw_name;
struct adreno_gpudev *gpudev;
size_t gmem_size;
unsigned int sync_lock_pm4_ver;
unsigned int sync_lock_pfp_ver;
unsigned int pm4_jt_idx;
unsigned int pm4_jt_addr;
unsigned int pfp_jt_idx;
unsigned int pfp_jt_addr;
unsigned int pm4_bstrp_size;
unsigned int pfp_bstrp_size;
unsigned int pfp_bstrp_ver;
unsigned long shader_offset;
unsigned int shader_size;
};
struct adreno_device {
struct kgsl_device dev; /* Must be first field in this struct */
unsigned long priv;
unsigned int chipid;
unsigned long gmem_base;
unsigned long gmem_size;
const struct adreno_gpu_core *gpucore;
unsigned int *pfp_fw;
size_t pfp_fw_size;
unsigned int pfp_fw_version;
unsigned int *pm4_fw;
size_t pm4_fw_size;
unsigned int pm4_fw_version;
struct adreno_ringbuffer ringbuffers[ADRENO_PRIORITY_MAX_RB_LEVELS];
int num_ringbuffers;
struct adreno_ringbuffer *cur_rb;
unsigned int wait_timeout;
unsigned int fast_hang_detect;
unsigned int ft_policy;
unsigned int long_ib_detect;
unsigned int ft_pf_policy;
struct ocmem_buf *ocmem_hdl;
struct adreno_profile profile;
struct adreno_dispatcher dispatcher;
struct kgsl_memdesc pwron_fixup;
unsigned int pwron_fixup_dwords;
struct work_struct input_work;
struct adreno_busy_data busy_data;
unsigned int ram_cycles_lo;
unsigned int starved_ram_lo;
atomic_t halt;
struct dentry *ctx_d_debugfs;
unsigned long pwrctrl_flag;
struct kgsl_memdesc cmdbatch_profile_buffer;
unsigned int cmdbatch_profile_index;
};
/**
* enum adreno_device_flags - Private flags for the adreno_device
* @ADRENO_DEVICE_PWRON - Set during init after a power collapse
* @ADRENO_DEVICE_PWRON_FIXUP - Set if the target requires the shader fixup
* after power collapse
* @ADRENO_DEVICE_CORESIGHT - Set if the coresight (trace bus) registers should
* be restored after power collapse
* @ADRENO_DEVICE_HANG_INTR - Set if the hang interrupt should be enabled for
* this target
* @ADRENO_DEVICE_STARTED - Set if the device start sequence is in progress
* @ADRENO_DEVICE_FAULT - Set if the device is currently in fault (and shouldn't
* send any more commands to the ringbuffer)
* @ADRENO_DEVICE_CMDBATCH_PROFILE - Set if the device supports command batch
* profiling via the ALWAYSON counter
*/
enum adreno_device_flags {
ADRENO_DEVICE_PWRON = 0,
ADRENO_DEVICE_PWRON_FIXUP = 1,
ADRENO_DEVICE_INITIALIZED = 2,
ADRENO_DEVICE_CORESIGHT = 3,
ADRENO_DEVICE_HANG_INTR = 4,
ADRENO_DEVICE_STARTED = 5,
ADRENO_DEVICE_FAULT = 6,
ADRENO_DEVICE_CMDBATCH_PROFILE = 7,
ADRENO_DEVICE_GPU_REGULATOR_ENABLED = 8,
};
#define PERFCOUNTER_FLAG_NONE 0x0
#define PERFCOUNTER_FLAG_KERNEL 0x1
/* Structs to maintain the list of active performance counters */
/**
* struct adreno_perfcount_register: register state
* @countable: countable the register holds
* @kernelcount: number of user space users of the register
* @usercount: number of kernel users of the register
* @offset: register hardware offset
* @load_bit: The bit number in LOAD register which corresponds to this counter
* @select: The countable register offset
* @value: The 64 bit countable register value
*/
struct adreno_perfcount_register {
unsigned int countable;
unsigned int kernelcount;
unsigned int usercount;
unsigned int offset;
unsigned int offset_hi;
int load_bit;
unsigned int select;
uint64_t value;
};
/**
* struct adreno_perfcount_group: registers for a hardware group
* @regs: available registers for this group
* @reg_count: total registers for this group
* @name: group name for this group
*/
struct adreno_perfcount_group {
struct adreno_perfcount_register *regs;
unsigned int reg_count;
const char *name;
unsigned long flags;
};
/*
* ADRENO_PERFCOUNTER_GROUP_FIXED indicates that a perfcounter group is fixed -
* instead of having configurable countables like the other groups, registers in
* fixed groups have a hardwired countable. So when the user requests a
* countable in one of these groups, that countable should be used as the
* register offset to return
*/
#define ADRENO_PERFCOUNTER_GROUP_FIXED BIT(0)
/**
* adreno_perfcounts: all available perfcounter groups
* @groups: available groups for this device
* @group_count: total groups for this device
*/
struct adreno_perfcounters {
struct adreno_perfcount_group *groups;
unsigned int group_count;
};
/**
* adreno_invalid_countabless: Invalid countables that do not work properly
* @countables: List of unusable countables
* @num_countables: Number of unusable countables
*/
struct adreno_invalid_countables {
const unsigned int *countables;
int num_countables;
};
#define ADRENO_PERFCOUNTER_GROUP_FLAGS(core, offset, name, flags) \
[KGSL_PERFCOUNTER_GROUP_##offset] = { core##_perfcounters_##name, \
ARRAY_SIZE(core##_perfcounters_##name), __stringify(name), flags }
#define ADRENO_PERFCOUNTER_GROUP(core, offset, name) \
ADRENO_PERFCOUNTER_GROUP_FLAGS(core, offset, name, 0)
#define ADRENO_PERFCOUNTER_INVALID_COUNTABLE(name, off) \
[KGSL_PERFCOUNTER_GROUP_##off] = { name##_invalid_countables, \
ARRAY_SIZE(name##_invalid_countables) }
/**
* struct adreno_cmdbatch_profile_entry - a single command batch entry in the
* kernel profiling buffer
* @started: Number of GPU ticks at start of the command batch
* @retired: Number of GPU ticks at the end of the command batch
*/
struct adreno_cmdbatch_profile_entry {
uint64_t started;
uint64_t retired;
};
#define ADRENO_CMDBATCH_PROFILE_COUNT \
(PAGE_SIZE / sizeof(struct adreno_cmdbatch_profile_entry))
#define ADRENO_CMDBATCH_PROFILE_OFFSET(_index, _member) \
((_index) * sizeof(struct adreno_cmdbatch_profile_entry) \
+ offsetof(struct adreno_cmdbatch_profile_entry, _member))
/**
* adreno_regs: List of registers that are used in kgsl driver for all
* 3D devices. Each device type has different offset value for the same
* register, so an array of register offsets are declared for every device
* and are indexed by the enumeration values defined in this enum
*/
enum adreno_regs {
ADRENO_REG_CP_ME_RAM_WADDR,
ADRENO_REG_CP_ME_RAM_DATA,
ADRENO_REG_CP_PFP_UCODE_DATA,
ADRENO_REG_CP_PFP_UCODE_ADDR,
ADRENO_REG_CP_WFI_PEND_CTR,
ADRENO_REG_CP_RB_BASE,
ADRENO_REG_CP_RB_RPTR,
ADRENO_REG_CP_RB_WPTR,
ADRENO_REG_CP_CNTL,
ADRENO_REG_CP_ME_CNTL,
ADRENO_REG_CP_RB_CNTL,
ADRENO_REG_CP_IB1_BASE,
ADRENO_REG_CP_IB1_BUFSZ,
ADRENO_REG_CP_IB2_BASE,
ADRENO_REG_CP_IB2_BUFSZ,
ADRENO_REG_CP_TIMESTAMP,
ADRENO_REG_CP_SCRATCH_REG6,
ADRENO_REG_CP_SCRATCH_REG7,
ADRENO_REG_CP_ME_RAM_RADDR,
ADRENO_REG_CP_ROQ_ADDR,
ADRENO_REG_CP_ROQ_DATA,
ADRENO_REG_CP_MERCIU_ADDR,
ADRENO_REG_CP_MERCIU_DATA,
ADRENO_REG_CP_MERCIU_DATA2,
ADRENO_REG_CP_MEQ_ADDR,
ADRENO_REG_CP_MEQ_DATA,
ADRENO_REG_CP_HW_FAULT,
ADRENO_REG_CP_PROTECT_STATUS,
ADRENO_REG_RBBM_STATUS,
ADRENO_REG_RBBM_PERFCTR_CTL,
ADRENO_REG_RBBM_PERFCTR_LOAD_CMD0,
ADRENO_REG_RBBM_PERFCTR_LOAD_CMD1,
ADRENO_REG_RBBM_PERFCTR_LOAD_CMD2,
ADRENO_REG_RBBM_PERFCTR_PWR_1_LO,
ADRENO_REG_RBBM_INT_0_MASK,
ADRENO_REG_RBBM_INT_0_STATUS,
ADRENO_REG_RBBM_PM_OVERRIDE2,
ADRENO_REG_RBBM_INT_CLEAR_CMD,
ADRENO_REG_RBBM_SW_RESET_CMD,
ADRENO_REG_RBBM_CLOCK_CTL,
ADRENO_REG_VPC_DEBUG_RAM_SEL,
ADRENO_REG_VPC_DEBUG_RAM_READ,
ADRENO_REG_PA_SC_AA_CONFIG,
ADRENO_REG_SQ_GPR_MANAGEMENT,
ADRENO_REG_SQ_INST_STORE_MANAGMENT,
ADRENO_REG_TP0_CHICKEN,
ADRENO_REG_RBBM_RBBM_CTL,
ADRENO_REG_UCHE_INVALIDATE0,
ADRENO_REG_RBBM_PERFCTR_LOAD_VALUE_LO,
ADRENO_REG_RBBM_PERFCTR_LOAD_VALUE_HI,
ADRENO_REG_RBBM_SECVID_TRUST_CONTROL,
ADRENO_REG_RBBM_ALWAYSON_COUNTER_LO,
ADRENO_REG_VBIF_XIN_HALT_CTRL0,
ADRENO_REG_VBIF_XIN_HALT_CTRL1,
ADRENO_REG_REGISTER_MAX,
};
/**
* adreno_reg_offsets: Holds array of register offsets
* @offsets: Offset array of size defined by enum adreno_regs
* @offset_0: This is the index of the register in offset array whose value
* is 0. 0 is a valid register offset and during initialization of the
* offset array we need to know if an offset value is correctly defined to 0
*/
struct adreno_reg_offsets {
unsigned int *const offsets;
enum adreno_regs offset_0;
};
#define ADRENO_REG_UNUSED 0xFFFFFFFF
#define ADRENO_REG_DEFINE(_offset, _reg) [_offset] = _reg
/*
* struct adreno_vbif_data - Describes vbif register value pair
* @reg: Offset to vbif register
* @val: The value that should be programmed in the register at reg
*/
struct adreno_vbif_data {
unsigned int reg;
unsigned int val;
};
/*
* struct adreno_vbif_platform - Holds an array of vbif reg value pairs
* for a particular core
* @devfunc: Pointer to platform/core identification function
* @vbif: Array of reg value pairs for vbif registers
*/
struct adreno_vbif_platform {
int(*devfunc)(struct adreno_device *);
const struct adreno_vbif_data *vbif;
};
/*
* struct adreno_vbif_snapshot_registers - Holds an array of vbif registers
* listed for snapshot dump for a particular core
* @vbif_version: vbif version
* @vbif_snapshot_registers: vbif registers listed for snapshot dump
* @vbif_snapshot_registers_count: count of vbif registers listed for snapshot
*/
struct adreno_vbif_snapshot_registers {
const unsigned int vbif_version;
const unsigned int *vbif_snapshot_registers;
const int vbif_snapshot_registers_count;
};
/**
* struct adreno_coresight_register - Definition for a coresight (tracebus)
* debug register
* @offset: Offset of the debug register in the KGSL mmio region
* @initial: Default value to write when coresight is enabled
* @value: Current shadow value of the register (to be reprogrammed after power
* collapse)
*/
struct adreno_coresight_register {
unsigned int offset;
unsigned int initial;
unsigned int value;
};
struct adreno_coresight_attr {
struct device_attribute attr;
struct adreno_coresight_register *reg;
};
ssize_t adreno_coresight_show_register(struct device *device,
struct device_attribute *attr, char *buf);
ssize_t adreno_coresight_store_register(struct device *dev,
struct device_attribute *attr, const char *buf, size_t size);
#define ADRENO_CORESIGHT_ATTR(_attrname, _reg) \
struct adreno_coresight_attr coresight_attr_##_attrname = { \
__ATTR(_attrname, S_IRUGO | S_IWUSR, \
adreno_coresight_show_register, \
adreno_coresight_store_register), \
(_reg), }
/**
* struct adreno_coresight - GPU specific coresight definition
* @registers - Array of GPU specific registers to configure trace bus output
* @count - Number of registers in the array
* @groups - Pointer to an attribute list of control files
*/
struct adreno_coresight {
struct adreno_coresight_register *registers;
unsigned int count;
const struct attribute_group **groups;
};
struct adreno_irq_funcs {
void (*func)(struct adreno_device *, int);
};
#define ADRENO_IRQ_CALLBACK(_c) { .func = _c }
struct adreno_irq {
unsigned int mask;
struct adreno_irq_funcs *funcs;
int funcs_count;
};
/*
* struct adreno_debugbus_block - Holds info about debug buses of a chip
* @block_id: Bus identifier
* @dwords: Number of dwords of data that this block holds
*/
struct adreno_debugbus_block {
unsigned int block_id;
unsigned int dwords;
};
/*
* struct adreno_snapshot_section_sizes - Structure holding the size of
* different sections dumped during device snapshot
* @cp_state_deb_size: Debug data section size
* @vpc_mem_size: VPC memory section size
* @cp_meq_size: CP MEQ size
* @shader_mem_size: Size of shader memory of 1 shader section
* @cp_merciu_size: CP MERCIU size
* @roq_size: ROQ size
*/
struct adreno_snapshot_sizes {
int cp_state_deb;
int vpc_mem;
int cp_meq;
int shader_mem;
int cp_merciu;
int roq;
};
/*
* struct adreno_snapshot_data - Holds data used in snapshot
* @sect_sizes: Has sections sizes
*/
struct adreno_snapshot_data {
struct adreno_snapshot_sizes *sect_sizes;
};
struct adreno_gpudev {
/*
* These registers are in a different location on different devices,
* so define them in the structure and use them as variables.
*/
const struct adreno_reg_offsets *reg_offsets;
const struct adreno_ft_perf_counters *ft_perf_counters;
unsigned int ft_perf_counters_count;
struct adreno_perfcounters *perfcounters;
const struct adreno_invalid_countables
*invalid_countables;
struct adreno_snapshot_data *snapshot_data;
struct adreno_coresight *coresight;
struct adreno_irq *irq;
int num_prio_levels;
unsigned int vbif_xin_halt_ctrl0_mask;
/* GPU specific function hooks */
void (*irq_trace)(struct adreno_device *, unsigned int status);
void (*snapshot)(struct adreno_device *, struct kgsl_snapshot *);
void (*gpudev_init)(struct adreno_device *);
int (*rb_init)(struct adreno_device *, struct adreno_ringbuffer *);
int (*perfcounter_init)(struct adreno_device *);
void (*start)(struct adreno_device *);
void (*busy_cycles)(struct adreno_device *, struct adreno_busy_data *);
int (*perfcounter_enable)(struct adreno_device *, unsigned int group,
unsigned int counter, unsigned int countable);
uint64_t (*perfcounter_read)(struct adreno_device *adreno_dev,
unsigned int group, unsigned int counter);
uint64_t (*alwayson_counter_read)(struct adreno_device *adreno_dev);
bool (*is_sptp_idle)(struct adreno_device *);
void (*enable_pc)(struct adreno_device *);
void (*enable_ppd)(struct adreno_device *);
void (*regulator_enable)(struct adreno_device *);
void (*regulator_disable)(struct adreno_device *);
};
struct log_field {
bool show;
const char *display;
};
/* Fault Tolerance policy flags */
#define KGSL_FT_OFF 0
#define KGSL_FT_REPLAY 1
#define KGSL_FT_SKIPIB 2
#define KGSL_FT_SKIPFRAME 3
#define KGSL_FT_DISABLE 4
#define KGSL_FT_TEMP_DISABLE 5
#define KGSL_FT_THROTTLE 6
#define KGSL_FT_SKIPCMD 7
#define KGSL_FT_DEFAULT_POLICY (BIT(KGSL_FT_REPLAY) + \
BIT(KGSL_FT_SKIPCMD) + BIT(KGSL_FT_THROTTLE))
#define KGSL_FT_POLICY_MASK (BIT(KGSL_FT_OFF) + \
BIT(KGSL_FT_REPLAY) + BIT(KGSL_FT_SKIPIB) \
+ BIT(KGSL_FT_SKIPFRAME) + BIT(KGSL_FT_DISABLE) + \
BIT(KGSL_FT_TEMP_DISABLE) + BIT(KGSL_FT_THROTTLE) + \
BIT(KGSL_FT_SKIPCMD))
/* This internal bit is used to skip the PM dump on replayed command batches */
#define KGSL_FT_SKIP_PMDUMP 31
/* Pagefault policy flags */
#define KGSL_FT_PAGEFAULT_INT_ENABLE BIT(0)
#define KGSL_FT_PAGEFAULT_GPUHALT_ENABLE BIT(1)
#define KGSL_FT_PAGEFAULT_LOG_ONE_PER_PAGE BIT(2)
#define KGSL_FT_PAGEFAULT_LOG_ONE_PER_INT BIT(3)
#define KGSL_FT_PAGEFAULT_DEFAULT_POLICY KGSL_FT_PAGEFAULT_INT_ENABLE
#define ADRENO_FT_TYPES \
{ BIT(KGSL_FT_OFF), "off" }, \
{ BIT(KGSL_FT_REPLAY), "replay" }, \
{ BIT(KGSL_FT_SKIPIB), "skipib" }, \
{ BIT(KGSL_FT_SKIPFRAME), "skipframe" }, \
{ BIT(KGSL_FT_DISABLE), "disable" }, \
{ BIT(KGSL_FT_TEMP_DISABLE), "temp" }, \
{ BIT(KGSL_FT_THROTTLE), "throttle"}, \
{ BIT(KGSL_FT_SKIPCMD), "skipcmd" }
#define FOR_EACH_RINGBUFFER(_dev, _rb, _i) \
for ((_i) = 0, (_rb) = &((_dev)->ringbuffers[0]); \
(_i) < (_dev)->num_ringbuffers; \
(_i)++, (_rb)++)
struct adreno_ft_perf_counters {
unsigned int counter;
unsigned int countable;
};
extern unsigned int *adreno_ft_regs;
extern unsigned int adreno_ft_regs_num;
extern unsigned int *adreno_ft_regs_val;
extern struct adreno_gpudev adreno_a3xx_gpudev;
extern struct adreno_gpudev adreno_a4xx_gpudev;
/* A3XX register set defined in adreno_a3xx.c */
extern const unsigned int a3xx_registers[];
extern const unsigned int a3xx_registers_count;
extern const unsigned int a3xx_hlsq_registers[];
extern const unsigned int a3xx_hlsq_registers_count;
extern const unsigned int a330_registers[];
extern const unsigned int a330_registers_count;
/* A4XX register set defined in adreno_a4xx.c */
extern const unsigned int a4xx_registers[];
extern const unsigned int a4xx_registers_count;
extern const unsigned int a4xx_sp_tp_registers[];
extern const unsigned int a4xx_sp_tp_registers_count;
extern const unsigned int a4xx_xpu_registers[];
extern const unsigned int a4xx_xpu_reg_cnt;
extern const struct adreno_vbif_snapshot_registers
a4xx_vbif_snapshot_registers[];
extern const unsigned int a4xx_vbif_snapshot_reg_cnt;
int adreno_spin_idle(struct kgsl_device *device);
int adreno_idle(struct kgsl_device *device);
bool adreno_isidle(struct kgsl_device *device);
int adreno_perfcounter_query_group(struct adreno_device *adreno_dev,
unsigned int groupid, unsigned int __user *countables,
unsigned int count, unsigned int *max_counters);
int adreno_perfcounter_read_group(struct adreno_device *adreno_dev,
struct kgsl_perfcounter_read_group __user *reads, unsigned int count);
int adreno_set_constraint(struct kgsl_device *device,
struct kgsl_context *context,
struct kgsl_device_constraint *constraint);
void adreno_shadermem_regread(struct kgsl_device *device,
unsigned int offsetwords,
unsigned int *value);
unsigned int adreno_a3xx_rbbm_clock_ctl_default(struct adreno_device
*adreno_dev);
void adreno_snapshot(struct kgsl_device *device,
struct kgsl_snapshot *snapshot,
struct kgsl_context *context);
int adreno_reset(struct kgsl_device *device);
void adreno_fault_skipcmd_detached(struct kgsl_device *device,
struct adreno_context *drawctxt,
struct kgsl_cmdbatch *cmdbatch);
void adreno_perfcounter_close(struct adreno_device *adreno_dev);
void adreno_perfcounter_restore(struct adreno_device *adreno_dev);
void adreno_perfcounter_save(struct adreno_device *adreno_dev);
int adreno_perfcounter_start(struct adreno_device *adreno_dev);
int adreno_perfcounter_init(struct adreno_device *adreno_dev);
int adreno_perfcounter_get_groupid(struct adreno_device *adreno_dev,
const char *name);
const char *adreno_perfcounter_get_name(struct adreno_device
*adreno_dev, unsigned int groupid);
int adreno_perfcounter_get(struct adreno_device *adreno_dev,
unsigned int groupid, unsigned int countable, unsigned int *offset,
unsigned int *offset_hi, unsigned int flags);
int adreno_perfcounter_put(struct adreno_device *adreno_dev,
unsigned int groupid, unsigned int countable, unsigned int flags);
int adreno_a3xx_pwron_fixup_init(struct adreno_device *adreno_dev);
int adreno_a4xx_pwron_fixup_init(struct adreno_device *adreno_dev);
int adreno_coresight_init(struct adreno_device *adreno_dev);
void adreno_coresight_start(struct adreno_device *adreno_dev);
void adreno_coresight_stop(struct adreno_device *adreno_dev);
void adreno_coresight_remove(struct adreno_device *adreno_dev);
bool adreno_hw_isidle(struct adreno_device *adreno_dev);
int adreno_iommu_set_pt(struct adreno_ringbuffer *rb,
struct kgsl_pagetable *new_pt);
void adreno_iommu_set_pt_generate_rb_cmds(struct adreno_ringbuffer *rb,
struct kgsl_pagetable *pt);
void adreno_fault_detect_start(struct adreno_device *adreno_dev);
void adreno_fault_detect_stop(struct adreno_device *adreno_dev);
void adreno_hang_int_callback(struct adreno_device *adreno_dev, int bit);
void adreno_cp_callback(struct adreno_device *adreno_dev, int bit);
static inline int adreno_is_a3xx(struct adreno_device *adreno_dev)
{
return ((ADRENO_GPUREV(adreno_dev) >= 300) &&
(ADRENO_GPUREV(adreno_dev) < 400));
}
static inline int adreno_is_a304(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A304);
}
static inline int adreno_is_a305(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A305);
}
static inline int adreno_is_a305b(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A305B);
}
static inline int adreno_is_a305c(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A305C);
}
static inline int adreno_is_a306(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A306);
}
static inline int adreno_is_a310(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A310);
}
static inline int adreno_is_a320(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A320);
}
static inline int adreno_is_a330(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A330);
}
static inline int adreno_is_a330v2(struct adreno_device *adreno_dev)
{
return ((ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A330) &&
(ADRENO_CHIPID_PATCH(adreno_dev->chipid) > 0));
}
static inline int adreno_is_a330v21(struct adreno_device *adreno_dev)
{
return ((ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A330) &&
(ADRENO_CHIPID_PATCH(adreno_dev->chipid) > 0xF));
}
static inline int adreno_is_a4xx(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) >= 400);
}
static inline int adreno_is_a405(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A405);
}
static inline int adreno_is_a420(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A420);
}
static inline int adreno_is_a430(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A430);
}
static inline int adreno_is_a430v2(struct adreno_device *adreno_dev)
{
return ((ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A430) &&
(ADRENO_CHIPID_PATCH(adreno_dev->chipid) == 1));
}
static inline int adreno_is_a418(struct adreno_device *adreno_dev)
{
return (ADRENO_GPUREV(adreno_dev) == ADRENO_REV_A418);
}
static inline int adreno_rb_ctxtswitch(unsigned int *cmd)
{
return (cmd[0] == cp_nop_packet(1) &&
cmd[1] == KGSL_CONTEXT_TO_MEM_IDENTIFIER);
}
/**
* adreno_context_timestamp() - Return the last queued timestamp for the context
* @k_ctxt: Pointer to the KGSL context to query
*
* Return the last queued context for the given context. This is used to verify
* that incoming requests are not using an invalid (unsubmitted) timestamp
*/
static inline int adreno_context_timestamp(struct kgsl_context *k_ctxt)
{
struct adreno_context *drawctxt = ADRENO_CONTEXT(k_ctxt);
return drawctxt->timestamp;
}
static inline int __adreno_add_idle_indirect_cmds(unsigned int *cmds,
unsigned int nop_gpuaddr)
{
/* Adding an indirect buffer ensures that the prefetch stalls until
* the commands in indirect buffer have completed. We need to stall
* prefetch with a nop indirect buffer when updating pagetables
* because it provides stabler synchronization */
*cmds++ = cp_type3_packet(CP_WAIT_FOR_ME, 1);
*cmds++ = 0;
*cmds++ = CP_HDR_INDIRECT_BUFFER_PFE;
*cmds++ = nop_gpuaddr;
*cmds++ = 2;
*cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1);
*cmds++ = 0x00000000;
return 5;
}
static inline int adreno_add_bank_change_cmds(unsigned int *cmds,
int cur_ctx_bank,
unsigned int nop_gpuaddr)
{
unsigned int *start = cmds;
*cmds++ = cp_type0_packet(A3XX_CP_STATE_DEBUG_INDEX, 1);
*cmds++ = (cur_ctx_bank ? 0 : 0x20);
cmds += __adreno_add_idle_indirect_cmds(cmds, nop_gpuaddr);
return cmds - start;
}
/*
* adreno_read_cmds - Add pm4 packets to perform read
* @cmds - Pointer to memory where read commands need to be added
* @addr - gpu address of the read
* @val - The GPU will wait until the data at address addr becomes
* @nop_gpuaddr - NOP GPU address
* equal to value
*/
static inline int adreno_add_read_cmds(unsigned int *cmds, unsigned int addr,
unsigned int val, unsigned int nop_gpuaddr)
{
unsigned int *start = cmds;
*cmds++ = cp_type3_packet(CP_WAIT_REG_MEM, 5);
/* MEM SPACE = memory, FUNCTION = equals */
*cmds++ = 0x13;
*cmds++ = addr;
*cmds++ = val;
*cmds++ = 0xFFFFFFFF;
*cmds++ = 0xFFFFFFFF;
/* WAIT_REG_MEM turns back on protected mode - push it off */
*cmds++ = cp_type3_packet(CP_SET_PROTECTED_MODE, 1);
*cmds++ = 0;
cmds += __adreno_add_idle_indirect_cmds(cmds, nop_gpuaddr);
return cmds - start;
}
/*
* adreno_idle_cmds - Add pm4 packets for GPU idle
* @adreno_dev - Pointer to device structure
* @cmds - Pointer to memory where idle commands need to be added
*/
static inline int adreno_add_idle_cmds(struct adreno_device *adreno_dev,
unsigned int *cmds)
{
unsigned int *start = cmds;
*cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1);
*cmds++ = 0;
if (adreno_is_a3xx(adreno_dev)) {
*cmds++ = cp_type3_packet(CP_WAIT_FOR_ME, 1);
*cmds++ = 0;
}
return cmds - start;
}
/*
* adreno_wait_reg_mem() - Add a CP_WAIT_REG_MEM command
* @cmds: Pointer to memory where commands are to be added
* @addr: Regiater address to poll for
* @val: Value to poll for
* @mask: The value against which register value is masked
* @interval: wait interval
*/
static inline int adreno_wait_reg_mem(unsigned int *cmds, unsigned int addr,
unsigned int val, unsigned int mask,
unsigned int interval)
{
unsigned int *start = cmds;
*cmds++ = cp_type3_packet(CP_WAIT_REG_MEM, 5);
*cmds++ = 0x3; /* Function = Equals */
*cmds++ = addr; /* Poll address */
*cmds++ = val; /* ref val */
*cmds++ = mask;
*cmds++ = interval;
/* WAIT_REG_MEM turns back on protected mode - push it off */
*cmds++ = cp_type3_packet(CP_SET_PROTECTED_MODE, 1);
*cmds++ = 0;
return cmds - start;
}
/*
* adreno_wait_reg_eq() - Add a CP_WAIT_REG_EQ command
* @cmds: Pointer to memory where commands are to be added
* @addr: Regiater address to poll for
* @val: Value to poll for
* @mask: The value against which register value is masked
* @interval: wait interval
*/
static inline int adreno_wait_reg_eq(unsigned int *cmds, unsigned int addr,
unsigned int val, unsigned int mask,
unsigned int interval)
{
unsigned int *start = cmds;
*cmds++ = cp_type3_packet(CP_WAIT_REG_EQ, 4);
*cmds++ = addr;
*cmds++ = val;
*cmds++ = mask;
*cmds++ = interval;
return cmds - start;
}
/*
* adreno_checkreg_off() - Checks the validity of a register enum
* @adreno_dev: Pointer to adreno device
* @offset_name: The register enum that is checked
*/
static inline bool adreno_checkreg_off(struct adreno_device *adreno_dev,
enum adreno_regs offset_name)
{
struct adreno_gpudev *gpudev = ADRENO_GPU_DEVICE(adreno_dev);
if (offset_name >= ADRENO_REG_REGISTER_MAX ||
ADRENO_REG_UNUSED == gpudev->reg_offsets->offsets[offset_name])
BUG();
return true;
}
/*
* adreno_readreg() - Read a register by getting its offset from the
* offset array defined in gpudev node
* @adreno_dev: Pointer to the the adreno device
* @offset_name: The register enum that is to be read
* @val: Register value read is placed here
*/
static inline void adreno_readreg(struct adreno_device *adreno_dev,
enum adreno_regs offset_name, unsigned int *val)
{
struct adreno_gpudev *gpudev = ADRENO_GPU_DEVICE(adreno_dev);
if (adreno_checkreg_off(adreno_dev, offset_name))
kgsl_regread(&adreno_dev->dev,
gpudev->reg_offsets->offsets[offset_name], val);
}
/*
* adreno_writereg() - Write a register by getting its offset from the
* offset array defined in gpudev node
* @adreno_dev: Pointer to the the adreno device
* @offset_name: The register enum that is to be written
* @val: Value to write
*/
static inline void adreno_writereg(struct adreno_device *adreno_dev,
enum adreno_regs offset_name, unsigned int val)
{
struct adreno_gpudev *gpudev = ADRENO_GPU_DEVICE(adreno_dev);
if (adreno_checkreg_off(adreno_dev, offset_name))
kgsl_regwrite(&adreno_dev->dev,
gpudev->reg_offsets->offsets[offset_name], val);
}
/*
* adreno_getreg() - Returns the offset value of a register from the
* register offset array in the gpudev node
* @adreno_dev: Pointer to the the adreno device
* @offset_name: The register enum whore offset is returned
*/
static inline unsigned int adreno_getreg(struct adreno_device *adreno_dev,
enum adreno_regs offset_name)
{
struct adreno_gpudev *gpudev = ADRENO_GPU_DEVICE(adreno_dev);
if (!adreno_checkreg_off(adreno_dev, offset_name))
return ADRENO_REG_REGISTER_MAX;
return gpudev->reg_offsets->offsets[offset_name];
}
/**
* adreno_gpu_fault() - Return the current state of the GPU
* @adreno_dev: A pointer to the adreno_device to query
*
* Return 0 if there is no fault or positive with the last type of fault that
* occurred
*/
static inline unsigned int adreno_gpu_fault(struct adreno_device *adreno_dev)
{
smp_rmb();
return atomic_read(&adreno_dev->dispatcher.fault);
}
/**
* adreno_set_gpu_fault() - Set the current fault status of the GPU
* @adreno_dev: A pointer to the adreno_device to set
* @state: fault state to set
*
*/
static inline void adreno_set_gpu_fault(struct adreno_device *adreno_dev,
int state)
{
/* only set the fault bit w/o overwriting other bits */
atomic_add(state, &adreno_dev->dispatcher.fault);
smp_wmb();
}
/**
* adreno_clear_gpu_fault() - Clear the GPU fault register
* @adreno_dev: A pointer to an adreno_device structure
*
* Clear the GPU fault status for the adreno device
*/
static inline void adreno_clear_gpu_fault(struct adreno_device *adreno_dev)
{
atomic_set(&adreno_dev->dispatcher.fault, 0);
smp_wmb();
}
/**
* adreno_gpu_halt() - Return the GPU halt refcount
* @adreno_dev: A pointer to the adreno_device
*/
static inline int adreno_gpu_halt(struct adreno_device *adreno_dev)
{
smp_rmb();
return atomic_read(&adreno_dev->halt);
}
/**
* adreno_clear_gpu_halt() - Clear the GPU halt refcount
* @adreno_dev: A pointer to the adreno_device
*/
static inline void adreno_clear_gpu_halt(struct adreno_device *adreno_dev)
{
atomic_set(&adreno_dev->halt, 0);
smp_wmb();
}
/**
* adreno_get_gpu_halt() - Increment GPU halt refcount
* @adreno_dev: A pointer to the adreno_device
*/
static inline void adreno_get_gpu_halt(struct adreno_device *adreno_dev)
{
atomic_inc(&adreno_dev->halt);
}
/**
* adreno_put_gpu_halt() - Decrement GPU halt refcount
* @adreno_dev: A pointer to the adreno_device
*/
static inline void adreno_put_gpu_halt(struct adreno_device *adreno_dev)
{
if (atomic_dec_return(&adreno_dev->halt) < 0)
BUG();
}
/*
* adreno_vbif_start() - Program VBIF registers, called in device start
* @adreno_dev: Pointer to device whose vbif data is to be programmed
* @vbif_platforms: list register value pair of vbif for a family
* of adreno cores
* @num_platforms: Number of platforms contained in vbif_platforms
*/
static inline void adreno_vbif_start(struct adreno_device *adreno_dev,
const struct adreno_vbif_platform *vbif_platforms,
int num_platforms)
{
int i;
const struct adreno_vbif_data *vbif = NULL;
for (i = 0; i < num_platforms; i++) {
if (vbif_platforms[i].devfunc(adreno_dev)) {
vbif = vbif_platforms[i].vbif;
break;
}
}
BUG_ON(vbif == NULL);
while (vbif->reg != 0) {
kgsl_regwrite(&adreno_dev->dev, vbif->reg, vbif->val);
vbif++;
}
}
/**
* adreno_set_protected_registers() - Protect the specified range of registers
* from being accessed by the GPU
* @adreno_dev: pointer to the Adreno device
* @index: Pointer to the index of the protect mode register to write to
* @reg: Starting dword register to write
* @mask_len: Size of the mask to protect (# of registers = 2 ** mask_len)
*
* Add the range of registers to the list of protected mode registers that will
* cause an exception if the GPU accesses them. There are 16 available
* protected mode registers. Index is used to specify which register to write
* to - the intent is to call this function multiple times with the same index
* pointer for each range and the registers will be magically programmed in
* incremental fashion
*/
static inline void adreno_set_protected_registers(
struct adreno_device *adreno_dev, unsigned int *index,
unsigned int reg, int mask_len)
{
unsigned int val;
/* A430 has 24 registers (yay!). Everything else has 16 (boo!) */
if (adreno_is_a430(adreno_dev))
BUG_ON(*index >= 24);
else
BUG_ON(*index >= 16);
val = 0x60000000 | ((mask_len & 0x1F) << 24) | ((reg << 2) & 0xFFFFF);
/*
* Write the protection range to the next available protection
* register
*/
if (adreno_is_a4xx(adreno_dev))
kgsl_regwrite(&adreno_dev->dev,
A4XX_CP_PROTECT_REG_0 + *index, val);
else if (adreno_is_a3xx(adreno_dev))
kgsl_regwrite(&adreno_dev->dev,
A3XX_CP_PROTECT_REG_0 + *index, val);
*index = *index + 1;
}
#ifdef CONFIG_DEBUG_FS
void adreno_debugfs_init(struct adreno_device *adreno_dev);
void adreno_context_debugfs_init(struct adreno_device *,
struct adreno_context *);
#else
static inline void adreno_debugfs_init(struct adreno_device *adreno_dev) { }
static inline void adreno_context_debugfs_init(struct adreno_device *device,
struct adreno_context *context)
{ }
#endif
/**
* adreno_compare_pm4_version() - Compare the PM4 microcode version
* @adreno_dev: Pointer to the adreno_device struct
* @version: Version number to compare again
*
* Compare the current version against the specified version and return -1 if
* the current code is older, 0 if equal or 1 if newer.
*/
static inline int adreno_compare_pm4_version(struct adreno_device *adreno_dev,
unsigned int version)
{
if (adreno_dev->pm4_fw_version == version)
return 0;
return (adreno_dev->pm4_fw_version > version) ? 1 : -1;
}
/**
* adreno_compare_pfp_version() - Compare the PFP microcode version
* @adreno_dev: Pointer to the adreno_device struct
* @version: Version number to compare against
*
* Compare the current version against the specified version and return -1 if
* the current code is older, 0 if equal or 1 if newer.
*/
static inline int adreno_compare_pfp_version(struct adreno_device *adreno_dev,
unsigned int version)
{
if (adreno_dev->pfp_fw_version == version)
return 0;
return (adreno_dev->pfp_fw_version > version) ? 1 : -1;
}
/*
* adreno_bootstrap_ucode() - Checks if Ucode bootstrapping is supported
* @adreno_dev: Pointer to the the adreno device
*/
static inline int adreno_bootstrap_ucode(struct adreno_device *adreno_dev)
{
return (ADRENO_FEATURE(adreno_dev, ADRENO_USE_BOOTSTRAP) &&
adreno_compare_pfp_version(adreno_dev,
adreno_dev->gpucore->pfp_bstrp_ver) >= 0) ? 1 : 0;
}
/**
* adreno_get_rptr() - Get the current ringbuffer read pointer
* @rb: Pointer the ringbuffer to query
*
* Get the current read pointer from the GPU register.
*/
static inline unsigned int
adreno_get_rptr(struct adreno_ringbuffer *rb)
{
struct adreno_device *adreno_dev = ADRENO_DEVICE(rb->device);
if (adreno_dev->cur_rb == rb) {
adreno_readreg(adreno_dev, ADRENO_REG_CP_RB_RPTR, &(rb->rptr));
rmb();
}
return rb->rptr;
}
/**
* adreno_ctx_get_rb() - Return the ringbuffer that a context should
* use based on priority
* @adreno_dev: The adreno device that context is using
* @drawctxt: The context pointer
*/
static inline struct adreno_ringbuffer *adreno_ctx_get_rb(
struct adreno_device *adreno_dev,
struct adreno_context *drawctxt)
{
struct kgsl_context *context;
int level;
if (!drawctxt)
return NULL;
context = &(drawctxt->base);
/*
* Math to convert the priority field in context structure to an RB ID.
* Divide up the context priority based on number of ringbuffer levels.
*/
level = context->priority / adreno_dev->num_ringbuffers;
if (level < adreno_dev->num_ringbuffers)
return &(adreno_dev->ringbuffers[level]);
else
return &(adreno_dev->ringbuffers[
adreno_dev->num_ringbuffers - 1]);
}
/*
* adreno_set_active_ctx_null() - Put back reference to any active context
* and set the active context to NULL
* @adreno_dev: The adreno device
*/
static inline void adreno_set_active_ctx_null(struct adreno_device *adreno_dev)
{
int i;
struct adreno_ringbuffer *rb;
FOR_EACH_RINGBUFFER(adreno_dev, rb, i) {
if (rb->drawctxt_active)
kgsl_context_put(&(rb->drawctxt_active->base));
rb->drawctxt_active = NULL;
kgsl_sharedmem_writel(rb->device, &rb->pagetable_desc,
offsetof(struct adreno_ringbuffer_pagetable_info,
current_rb_ptname), 0);
}
}
/**
* adreno_use_cpu_path() - Use CPU instead of the GPU to manage the mmu?
* @adreno_dev: the device
*
* In many cases it is preferable to poke the iommu directly rather
* than using the GPU command stream. If we are idle or trying to go to a low
* power state, using the command stream will be slower and asynchronous, which
* needlessly complicates the power state transitions. Additionally,
* the hardware simulators do not support command stream MMU operations so
* the command stream can never be used if we are capturing CFF data.
*
*/
static inline bool adreno_use_cpu_path(struct adreno_device *adreno_dev)
{
return (adreno_isidle(&adreno_dev->dev) ||
KGSL_STATE_ACTIVE != adreno_dev->dev.state ||
atomic_read(&adreno_dev->dev.active_cnt) == 0 ||
adreno_dev->dev.cff_dump_enable);
}
/**
* adreno_set_apriv() - Generate commands to set/reset the APRIV
* @adreno_dev: Device on which the commands will execute
* @cmds: The memory pointer where commands are generated
* @set: If set then APRIV is set else reset
*
* Returns the number of commands generated
*/
static inline unsigned int adreno_set_apriv(struct adreno_device *adreno_dev,
unsigned int *cmds, int set)
{
unsigned int *cmds_orig = cmds;
*cmds++ = cp_type3_packet(CP_WAIT_FOR_IDLE, 1);
*cmds++ = 0;
*cmds++ = cp_type3_packet(CP_WAIT_FOR_ME, 1);
*cmds++ = 0;
*cmds++ = cp_type0_packet(adreno_getreg(adreno_dev,
ADRENO_REG_CP_CNTL), 1);
if (set)
*cmds++ = 1;
else
*cmds++ = 0;
return cmds - cmds_orig;
}
#endif /*__ADRENO_H */
| 31.438571 | 80 | 0.766642 | [
"3d"
] |
f4f2fa11c3a8669747dce1f427e3dbc7c30393b0 | 2,062 | h | C | projects/samples/robotbenchmark/wall_following/controllers/wall_following_supervisor/vector.h | awesome-archive/webots | 8e74fb8393d1e3a6540749afc492635c43f1b30f | [
"Apache-2.0"
] | 2 | 2019-07-12T13:47:44.000Z | 2019-08-17T02:53:54.000Z | projects/samples/robotbenchmark/wall_following/controllers/wall_following_supervisor/vector.h | golbh/webots | 8e74fb8393d1e3a6540749afc492635c43f1b30f | [
"Apache-2.0"
] | null | null | null | projects/samples/robotbenchmark/wall_following/controllers/wall_following_supervisor/vector.h | golbh/webots | 8e74fb8393d1e3a6540749afc492635c43f1b30f | [
"Apache-2.0"
] | 1 | 2019-07-13T17:58:04.000Z | 2019-07-13T17:58:04.000Z | /*
* Copyright 1996-2018 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 VECTOR_H
#define VECTOR_H
#include <math.h>
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
// Size of a vector, in bytes.
#define VECTOR_SIZE (2 * sizeof(double))
// Computes the distance between 2 points.
static inline double get_distance(const double *a, const double *b) {
if (a && b)
return sqrt(((a[0] - b[0]) * (a[0] - b[0])) + ((a[1] - b[1]) * (a[1] - b[1])));
return INFINITY;
}
// Computes the norm of a vector.
static inline double vector_get_norm(const double *v) {
if (v)
return sqrt((v[0] * v[0]) + (v[1] * v[1]));
return 0;
}
// Computes the difference between 2 vectors.
static inline void vector_substract(double *result, const double *u, const double *v) {
if (u && v && result) {
result[0] = u[0] - v[0];
result[1] = u[1] - v[1];
}
}
// Computes the sum of 2 vectors.
static inline void vector_add(double *result, const double *u, const double *v) {
if (u && v && result) {
result[0] = u[0] + v[0];
result[1] = u[1] + v[1];
}
}
// Computes the product of a vector and a scalar.
static inline void vector_product(double *result, const double *u, double scalar) {
if (u && result) {
result[0] = u[0] * scalar;
result[1] = u[1] * scalar;
}
}
// Computes the dot product between 2 vectors.
static inline double vector_get_dot_product(const double *u, const double *v) {
if (u && v)
return (u[0] * v[0]) + (u[1] * v[1]);
return 0;
}
#endif // VECTOR_H
| 26.435897 | 87 | 0.652279 | [
"vector"
] |
f4f4d6c72de653d6e5f436f5b90bb880968f833f | 47,599 | c | C | netbsd/sys/arch/amiga/dev/amidisplaycc.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 91 | 2015-01-05T15:18:31.000Z | 2022-03-11T16:43:28.000Z | netbsd/sys/arch/amiga/dev/amidisplaycc.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 1 | 2016-02-25T15:57:55.000Z | 2016-02-25T16:01:02.000Z | netbsd/sys/arch/amiga/dev/amidisplaycc.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 21 | 2015-02-07T08:23:07.000Z | 2021-12-14T06:01:49.000Z | /* $NetBSD: amidisplaycc.c,v 1.6.6.1 2002/09/04 14:03:34 lukem Exp $ */
/*-
* Copyright (c) 2000 Jukka Andberg.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: amidisplaycc.c,v 1.6.6.1 2002/09/04 14:03:34 lukem Exp $");
/*
* wscons interface to amiga custom chips. Contains the necessary functions
* to render text on bitmapped screens. Uses the functions defined in
* grfabs_reg.h for display creation/destruction and low level setup.
*
* For each virtual terminal a new screen ('view') is allocated.
* Also one more is allocated for the mapped screen on demand.
*/
#include "amidisplaycc.h"
#include "grfcc.h"
#include "view.h"
#include "opt_amigaccgrf.h"
#if NAMIDISPLAYCC>0
#include <sys/param.h>
#include <sys/types.h>
#include <sys/device.h>
#include <sys/malloc.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <amiga/dev/grfabs_reg.h>
#include <amiga/dev/viewioctl.h>
#include <amiga/amiga/device.h>
#include <dev/wscons/wsconsio.h>
#include <dev/rcons/raster.h>
#include <dev/wscons/wscons_raster.h>
#include <dev/wscons/wsdisplayvar.h>
#include <dev/cons.h>
#include <dev/wsfont/wsfont.h>
#include <machine/stdarg.h>
#define AMIDISPLAYCC_MAXFONTS 8
/* These can be lowered if you are sure you dont need that much colors. */
#define MAXDEPTH 8
#define MAXROWS 128
#define MAXCOLUMNS 80
#define ADJUSTCOLORS
#define MAXCOLORS (1<<MAXDEPTH)
struct amidisplaycc_screen;
struct amidisplaycc_softc
{
struct device dev;
/* runtime-loaded fonts */
struct wsdisplay_font fonts[AMIDISPLAYCC_MAXFONTS];
struct amidisplaycc_screen * currentscreen;
/* display turned on? */
int ison;
/* stuff relating to the mapped screen */
view_t * gfxview;
int gfxwidth;
int gfxheight;
int gfxdepth;
int gfxon;
};
/*
* Configuration stuff.
*/
static int amidisplaycc_match(struct device *, struct cfdata *, void *);
static void amidisplaycc_attach(struct device *, struct device *, void *);
struct cfattach amidisplaycc_ca = {
sizeof(struct amidisplaycc_softc),
amidisplaycc_match,
amidisplaycc_attach
};
cons_decl(amidisplaycc_);
/* end of configuration stuff */
/* private utility functions */
static int amidisplaycc_setvideo(struct amidisplaycc_softc *, int);
static int amidisplaycc_setemulcmap(struct amidisplaycc_screen *,
struct wsdisplay_cmap *);
static int amidisplaycc_cmapioctl(view_t *, u_long, struct wsdisplay_cmap *);
static int amidisplaycc_setcmap(view_t *, struct wsdisplay_cmap *);
static int amidisplaycc_getcmap(view_t *, struct wsdisplay_cmap *);
static int amidisplaycc_gfxscreen(struct amidisplaycc_softc *, int);
static int amidisplaycc_setnamedfont(struct amidisplaycc_screen *, char *);
static void amidisplaycc_setfont(struct amidisplaycc_screen *,
struct wsdisplay_font *, int);
static struct wsdisplay_font *amidisplaycc_findfont(struct amidisplaycc_softc *,
const char *, int, int);
static void dprintf(const char *fmt, ...);
/* end of private utility functions */
/* emulops for wscons */
void amidisplaycc_cursor(void *, int, int, int);
int amidisplaycc_mapchar(void *, int, unsigned int *);
void amidisplaycc_putchar(void *, int, int, u_int, long);
void amidisplaycc_copycols(void *, int, int, int, int);
void amidisplaycc_erasecols(void *, int, int, int, long);
void amidisplaycc_copyrows(void *, int, int, int);
void amidisplaycc_eraserows(void *, int, int, long);
int amidisplaycc_alloc_attr(void *, int, int, int, long *);
/* end of emulops for wscons */
/* accessops for wscons */
int amidisplaycc_ioctl(void *, u_long, caddr_t, int, struct proc *);
paddr_t amidisplaycc_mmap(void *, off_t, int);
int amidisplaycc_alloc_screen(void *, const struct wsscreen_descr *, void **,
int *, int *, long *);
void amidisplaycc_free_screen( void *, void *);
int amidisplaycc_show_screen(void *, void *, int, void (*)(void *, int, int),
void *);
int amidisplaycc_load_font(void *, void *, struct wsdisplay_font *);
void amidisplaycc_pollc(void *, int);
/* end of accessops for wscons */
/*
* These structures are passed to wscons, and they contain the
* display-specific callback functions.
*/
const struct wsdisplay_accessops amidisplaycc_accessops = {
amidisplaycc_ioctl,
amidisplaycc_mmap,
amidisplaycc_alloc_screen,
amidisplaycc_free_screen,
amidisplaycc_show_screen,
amidisplaycc_load_font,
amidisplaycc_pollc
};
const struct wsdisplay_emulops amidisplaycc_emulops = {
amidisplaycc_cursor,
amidisplaycc_mapchar,
amidisplaycc_putchar,
amidisplaycc_copycols,
amidisplaycc_erasecols,
amidisplaycc_copyrows,
amidisplaycc_eraserows,
amidisplaycc_alloc_attr
};
/* add some of our own data to the wsscreen_descr */
struct amidisplaycc_screen_descr {
struct wsscreen_descr wsdescr;
int depth;
char name[16];
};
/*
* List of supported screenmodes. Almost anything can be given here.
*/
#define ADCC_SCREEN(name, width, height, depth, fontwidth, fontheight) \
/* CONSTCOND */ \
{{ \
name, \
width / fontwidth, \
height / fontheight, \
&amidisplaycc_emulops, fontwidth, fontheight, \
(depth > 1 ? WSSCREEN_WSCOLORS : 0) | WSSCREEN_REVERSE | \
WSSCREEN_HILIT | WSSCREEN_UNDERLINE }, \
depth }
struct amidisplaycc_screen_descr amidisplaycc_screentab[] = {
/* name, width, height, depth, fontwidth==8, fontheight */
ADCC_SCREEN("80x50", 640, 400, 3, 8, 8),
ADCC_SCREEN("80x40", 640, 400, 3, 8, 10),
ADCC_SCREEN("80x25", 640, 400, 3, 8, 16),
ADCC_SCREEN("80x24", 640, 384, 3, 8, 16),
ADCC_SCREEN("640x400x1", 640, 400, 1, 8, 8),
ADCC_SCREEN("640x400x2", 640, 400, 2, 8, 8),
ADCC_SCREEN("640x400x3", 640, 400, 3, 8, 8),
ADCC_SCREEN("640x200x1", 640, 200, 1, 8, 8),
ADCC_SCREEN("640x200x1", 640, 200, 2, 8, 8),
ADCC_SCREEN("640x200x1", 640, 200, 3, 8, 8),
};
#define ADCC_SCREENPTR(index) &amidisplaycc_screentab[index].wsdescr
const struct wsscreen_descr *amidisplaycc_screens[] = {
ADCC_SCREENPTR(0),
ADCC_SCREENPTR(1),
ADCC_SCREENPTR(2),
ADCC_SCREENPTR(3),
ADCC_SCREENPTR(4),
ADCC_SCREENPTR(5),
ADCC_SCREENPTR(6),
ADCC_SCREENPTR(7),
ADCC_SCREENPTR(8),
ADCC_SCREENPTR(9),
};
#define NELEMS(arr) (sizeof(arr)/sizeof((arr)[0]))
/*
* This structure also is passed to wscons. It contains pointers
* to the available display modes.
*/
const struct wsscreen_list amidisplaycc_screenlist = {
sizeof(amidisplaycc_screens)/sizeof(amidisplaycc_screens[0]),
amidisplaycc_screens
};
/*
* Our own screen structure. One will be created for each screen.
*/
struct amidisplaycc_screen
{
struct amidisplaycc_softc *device;
int isconsole;
int isvisible;
view_t * view;
int ncols;
int nrows;
int cursorrow;
int cursorcol;
/* Active bitplanes for each character row. */
int rowmasks[MAXROWS];
/* Mapping of colors to screen colors. */
int colormap[MAXCOLORS];
/* Copies of display parameters for convenience */
int width;
int height;
int depth;
int widthbytes; /* bytes_per_row */
int linebytes; /* widthbytes + row_mod */
int rowbytes; /* linebytes * fontheight */
u_char * planes[MAXDEPTH];
u_char * savedscreen;
/*
* The font is either one we loaded ourselves, or
* one gotten using the wsfont system.
*
* wsfontcookie differentiates between them:
* For fonts loaded by ourselves it is -1.
* For wsfonts it contains a cookie for that system.
*/
struct wsdisplay_font * font;
int wsfontcookie;
int fontwidth;
int fontheight;
};
typedef struct amidisplaycc_screen adccscr_t;
/*
* Need one statically allocated screen for early init.
* The rest are mallocated when needed.
*/
adccscr_t amidisplaycc_consolescreen;
/*
* Bring in the one or two builtin fonts.
*/
extern unsigned char kernel_font_8x8[];
extern unsigned char kernel_font_lo_8x8;
extern unsigned char kernel_font_hi_8x8;
/*
* Default palettes for 2, 4 and 8 color emulation displays.
*/
/* black, grey */
static u_char pal2red[] = { 0x00, 0xaa };
static u_char pal2grn[] = { 0x00, 0xaa };
static u_char pal2blu[] = { 0x00, 0xaa };
/* black, red, green, grey */
static u_char pal4red[] = { 0x00, 0xaa, 0x00, 0xaa };
static u_char pal4grn[] = { 0x00, 0x00, 0xaa, 0xaa };
static u_char pal4blu[] = { 0x00, 0x00, 0x00, 0xaa };
/* black, red, green, brown, blue, magenta, cyan, grey */
static u_char pal8red[] = { 0x00, 0xaa, 0x00, 0xaa, 0x00, 0xaa, 0x00, 0xaa};
static u_char pal8grn[] = { 0x00, 0x00, 0xaa, 0xaa, 0x00, 0x00, 0xaa, 0xaa};
static u_char pal8blu[] = { 0x00, 0x00, 0x00, 0x00, 0xaa, 0xaa, 0xaa, 0xaa};
static struct wsdisplay_cmap pal2 = { 0, 2, pal2red, pal2grn, pal2blu };
static struct wsdisplay_cmap pal4 = { 0, 4, pal4red, pal4grn, pal4blu };
static struct wsdisplay_cmap pal8 = { 0, 8, pal8red, pal8grn, pal8blu };
#ifdef GRF_AGA
extern int aga_enable;
#else
static int aga_enable = 0;
#endif
/*
* This gets called at console init to determine the priority of
* this console device.
*
* Of course pointers to this and other functions must present
* in constab[] in conf.c for this to work.
*/
void
amidisplaycc_cnprobe(struct consdev *cd)
{
cd->cn_pri = CN_INTERNAL;
/*
* Yeah, real nice. But if we win the console then the wscons system
* does the proper initialization.
*/
cd->cn_dev = NODEV;
}
/*
* This gets called if this device is used as the console.
*/
void
amidisplaycc_cninit(struct consdev * cd)
{
void * cookie;
long attr;
int x;
int y;
/* Yeah, we got the console! */
/*
* This will do the basic stuff we also need.
*/
config_console();
grfcc_probe();
#if NVIEW>0
viewprobe();
#endif
/*
* Set up wscons to handle the details.
* It will then call us back when it needs something
* display-specific. It will also set up cn_tab properly,
* something which we failed to do at amidisplaycc_cnprobe().
*/
/*
* The alloc_screen knows to allocate the first screen statically.
*/
amidisplaycc_alloc_screen(NULL, &amidisplaycc_screentab[0].wsdescr,
&cookie, &x, &y, &attr);
wsdisplay_cnattach(&amidisplaycc_screentab[0].wsdescr,
cookie, x, y, attr);
}
static int
amidisplaycc_match(struct device *pdp, struct cfdata *cfp, void *auxp)
{
char *name = auxp;
if (matchname("amidisplaycc", name) == 0)
return (0);
/* Allow only one of us now. Not sure about that. */
if (cfp->cf_unit != 0)
return (0);
return 1;
}
/* ARGSUSED */
static void
amidisplaycc_attach(struct device *pdp, struct device *dp, void *auxp)
{
struct wsemuldisplaydev_attach_args waa;
struct amidisplaycc_softc * adp;
adp = (struct amidisplaycc_softc*)dp;
grfcc_probe();
#if NVIEW>0
viewprobe();
#endif
/*
* Attach only at real configuration time. Console init is done at
* the amidisplaycc_cninit function above.
*/
if (adp) {
printf(": Amiga custom chip graphics %s",
aga_enable ? "(AGA)" : "");
if (amidisplaycc_consolescreen.isconsole) {
adp->currentscreen = &amidisplaycc_consolescreen;
printf(" (console)");
} else
adp->currentscreen = NULL;
printf("\n");
adp->ison = 1;
/*
* Mapped screen properties.
* Would need a way to configure.
*/
adp->gfxview = NULL;
adp->gfxon = 0;
adp->gfxwidth = 640;
adp->gfxheight = 480;
if (aga_enable)
adp->gfxdepth = 8;
else
adp->gfxdepth = 4;
if (NELEMS(amidisplaycc_screentab) !=
NELEMS(amidisplaycc_screens))
panic("invalid screen definitions");
waa.scrdata = &amidisplaycc_screenlist;
waa.console = amidisplaycc_consolescreen.isconsole;
waa.accessops = &amidisplaycc_accessops;
waa.accesscookie = dp;
config_found(dp, &waa, wsemuldisplaydevprint);
bzero(adp->fonts, sizeof(adp->fonts));
/* Initialize an alternate system for finding fonts. */
wsfont_init();
}
}
/*
* Color, bgcolor and style are packed into one long attribute.
* These macros are used to create/split the attribute
*/
#define MAKEATTR(fg, bg, mode) (((fg)<<16) | ((bg)<<8) | (mode))
#define ATTRFG(attr) (((attr)>>16) & 255)
#define ATTRBG(attr) (((attr)>>8) & 255)
#define ATTRMO(attr) ((attr) & 255)
/*
* Called by wscons to draw/clear the cursor.
* We do this by xorring the block to the screen.
*
* This simple implementation will break if the screen is modified
* under the cursor before clearing it.
*/
void
amidisplaycc_cursor(void *screen, int on, int row, int col)
{
adccscr_t * scr;
u_char * dst;
int i;
scr = screen;
if (row < 0 || col < 0 || row >= scr->nrows || col >= scr->ncols)
return;
if (!on && scr->cursorrow==-1 && scr->cursorcol==-1)
return;
if (!on) {
row = scr->cursorrow;
col = scr->cursorcol;
}
dst = scr->planes[0];
dst += row * scr->rowbytes;
dst += col;
if (on) {
scr->cursorrow = row;
scr->cursorcol = col;
} else {
scr->cursorrow = -1;
scr->cursorcol = -1;
}
for (i = scr->fontheight ; i > 0 ; i--) {
*dst ^= 255;
dst += scr->linebytes;
}
}
/*
* This obviously does something important, don't ask me what.
*/
int
amidisplaycc_mapchar(void *screen, int ch, unsigned int *chp)
{
if (ch > 0 && ch < 256) {
*chp = ch;
return (5);
}
*chp = ' ';
return (0);
}
/*
* Write a character to screen with color / bgcolor / hilite(bold) /
* underline / reverse.
* Surely could be made faster but I'm not sure if its worth the
* effort as scrolling is at least a magnitude slower.
*/
void
amidisplaycc_putchar(void *screen, int row, int col, u_int ch, long attr)
{
adccscr_t * scr;
u_char * dst;
u_char * font;
int fontheight;
u_int8_t * fontreal;
int fontlow;
int fonthigh;
int bmapoffset;
int linebytes;
int underline;
int fgcolor;
int bgcolor;
int plane;
int depth;
int mode;
int bold;
u_char f;
int j;
scr = screen;
if (row < 0 || col < 0 || row >= scr->nrows || col >= scr->ncols)
return;
/* Extract the colors from the attribute */
fgcolor = ATTRFG(attr);
bgcolor = ATTRBG(attr);
mode = ATTRMO(attr);
/* Translate to screen colors */
fgcolor = scr->colormap[fgcolor];
bgcolor = scr->colormap[bgcolor];
if (mode & WSATTR_REVERSE) {
j = fgcolor;
fgcolor = bgcolor;
bgcolor = j;
}
bold = (mode & WSATTR_HILIT) > 0;
underline = (mode & WSATTR_UNDERLINE) > 0;
/* If we have loaded a font use it otherwise the builtin font */
if (scr->font) {
fontreal = scr->font->data;
fontlow = scr->font->firstchar;
fonthigh = fontlow + scr->font->numchars - 1;
} else {
fontreal = kernel_font_8x8;
fontlow = kernel_font_lo_8x8;
fonthigh = kernel_font_hi_8x8;
}
fontheight = scr->fontheight;
depth = scr->depth;
linebytes = scr->linebytes;
if (ch < fontlow || ch > fonthigh)
ch = fontlow;
/* Find the location where the wanted char is in the font data */
fontreal += scr->fontheight * (ch - fontlow);
bmapoffset = row * scr->rowbytes + col;
scr->rowmasks[row] |= fgcolor | bgcolor;
for (plane = 0 ; plane < depth ; plane++) {
dst = scr->planes[plane] + bmapoffset;
if (fgcolor & 1) {
if (bgcolor & 1) {
/* fg=on bg=on (fill) */
for (j = 0 ; j < fontheight ; j++) {
*dst = 255;
dst += linebytes;
}
} else {
/* fg=on bg=off (normal) */
font = fontreal;
for (j = 0 ; j < fontheight ; j++) {
f = *(font++);
f |= f >> bold;
*dst = f;
dst += linebytes;
}
if (underline)
*(dst - linebytes) = 255;
}
} else {
if (bgcolor & 1) {
/* fg=off bg=on (inverted) */
font = fontreal;
for (j = 0 ; j < fontheight ; j++) {
f = *(font++);
f |= f >> bold;
*dst = ~f;
dst += linebytes;
}
if (underline)
*(dst - linebytes) = 0;
} else {
/* fg=off bg=off (clear) */
for (j = 0 ; j < fontheight ; j++) {
*dst = 0;
dst += linebytes;
}
}
}
fgcolor >>= 1;
bgcolor >>= 1;
}
}
/*
* Copy characters on a row to another position on the same row.
*/
void
amidisplaycc_copycols(void *screen, int row, int srccol, int dstcol, int ncols)
{
adccscr_t * scr;
u_char * src;
u_char * dst;
int bmapoffset;
int linebytes;
int depth;
int plane;
int i;
int j;
scr = screen;
if (srccol < 0 || srccol + ncols > scr->ncols ||
dstcol < 0 || dstcol + ncols > scr->ncols ||
row < 0 || row >= scr->nrows)
return;
depth = scr->depth;
linebytes = scr->linebytes;
bmapoffset = row * scr->rowbytes;
for (plane = 0 ; plane < depth ; plane++) {
src = scr->planes[plane] + bmapoffset;
for (j = 0 ; j < scr->fontheight ; j++) {
dst = src;
if (srccol < dstcol) {
for (i = ncols - 1 ; i >= 0 ; i--)
dst[dstcol + i] = src[srccol + i];
} else {
for (i = 0 ; i < ncols ; i++)
dst[dstcol + i] = src[srccol + i];
}
src += linebytes;
}
}
}
/*
* Erase part of a row.
*/
void
amidisplaycc_erasecols(void *screen, int row, int startcol, int ncols,
long attr)
{
adccscr_t * scr;
u_char * dst;
int bmapoffset;
int linebytes;
int bgcolor;
int depth;
int plane;
int fill;
int j;
scr = screen;
if (row < 0 || row >= scr->nrows ||
startcol < 0 || startcol + ncols > scr->ncols)
return;
depth = scr->depth;
linebytes = scr->linebytes;
bmapoffset = row * scr->rowbytes + startcol;
/* Erase will be done using the set background color. */
bgcolor = ATTRBG(attr);
bgcolor = scr->colormap[bgcolor];
for(plane = 0 ; plane < depth ; plane++) {
fill = (bgcolor & 1) ? 255 : 0;
dst = scr->planes[plane] + bmapoffset;
for (j = 0 ; j < scr->fontheight ; j++) {
memset(dst, fill, ncols);
dst += linebytes;
}
}
}
/*
* Copy a number of rows to another location on the screen.
* Combined with eraserows it can be used to perform operation
* also known as 'scrolling'.
*/
void
amidisplaycc_copyrows(void *screen, int srcrow, int dstrow, int nrows)
{
adccscr_t * scr;
u_char * src;
u_char * dst;
int srcbmapoffset;
int dstbmapoffset;
int widthbytes;
int fontheight;
int linebytes;
u_int copysize;
int rowdelta;
int rowbytes;
int srcmask;
int dstmask;
int bmdelta;
int depth;
int plane;
int i;
int j;
scr = screen;
if (srcrow < 0 || srcrow + nrows > scr->nrows ||
dstrow < 0 || dstrow + nrows > scr->nrows)
return;
depth = scr->depth;
widthbytes = scr->widthbytes;
rowbytes = scr->rowbytes;
linebytes = scr->linebytes;
fontheight = scr->fontheight;
srcbmapoffset = rowbytes * srcrow;
dstbmapoffset = rowbytes * dstrow;
if (srcrow < dstrow) {
/* Move data downwards, need to copy from down to up */
bmdelta = -rowbytes;
rowdelta = -1;
srcbmapoffset += rowbytes * (nrows - 1);
srcrow += nrows - 1;
dstbmapoffset += rowbytes * (nrows - 1);
dstrow += nrows - 1;
} else {
/* Move data upwards, copy up to down */
bmdelta = rowbytes;
rowdelta = 1;
}
if (widthbytes == linebytes)
copysize = rowbytes;
else
copysize = 0;
for (j = 0 ; j < nrows ; j++) {
/* Need to copy only planes that have data on src or dst */
srcmask = scr->rowmasks[srcrow];
dstmask = scr->rowmasks[dstrow];
scr->rowmasks[dstrow] = srcmask;
for (plane = 0 ; plane < depth ; plane++) {
if (srcmask & 1) {
/*
* Source row has data on this
* plane, copy it.
*/
src = scr->planes[plane] + srcbmapoffset;
dst = scr->planes[plane] + dstbmapoffset;
if (copysize > 0) {
memcpy(dst, src, copysize);
} else {
/*
* Data not continuous,
* must do in pieces
*/
for (i=0 ; i < fontheight ; i++) {
memcpy(dst, src, widthbytes);
src += linebytes;
dst += linebytes;
}
}
} else if (dstmask & 1) {
/*
* Source plane is empty, but dest is not.
* so all we need to is clear it.
*/
dst = scr->planes[plane] + dstbmapoffset;
if (copysize > 0) {
/* Do it all */
bzero(dst, copysize);
} else {
for (i = 0 ; i < fontheight ; i++) {
bzero(dst, widthbytes);
dst += linebytes;
}
}
}
srcmask >>= 1;
dstmask >>= 1;
}
srcbmapoffset += bmdelta;
dstbmapoffset += bmdelta;
srcrow += rowdelta;
dstrow += rowdelta;
}
}
/*
* Erase some rows.
*/
void
amidisplaycc_eraserows(void *screen, int row, int nrows, long attr)
{
adccscr_t * scr;
u_char * dst;
int bmapoffset;
int fillsize;
int bgcolor;
int depth;
int plane;
int fill;
int j;
int widthbytes;
int linebytes;
int rowbytes;
scr = screen;
if (row < 0 || row + nrows > scr->nrows)
return;
depth = scr->depth;
widthbytes = scr->widthbytes;
linebytes = scr->linebytes;
rowbytes = scr->rowbytes;
bmapoffset = row * rowbytes;
if (widthbytes == linebytes)
fillsize = rowbytes * nrows;
else
fillsize = 0;
bgcolor = ATTRBG(attr);
bgcolor = scr->colormap[bgcolor];
for (j = 0 ; j < nrows ; j++)
scr->rowmasks[row+j] = bgcolor;
for (plane = 0 ; plane < depth ; plane++) {
dst = scr->planes[plane] + bmapoffset;
fill = (bgcolor & 1) ? 255 : 0;
if (fillsize > 0) {
/* If the rows are continuous, write them all. */
memset(dst, fill, fillsize);
} else {
for (j = 0 ; j < scr->fontheight * nrows ; j++) {
memset(dst, fill, widthbytes);
dst += linebytes;
}
}
bgcolor >>= 1;
}
}
/*
* Compose an attribute value from foreground color,
* background color, and flags.
*/
int
amidisplaycc_alloc_attr(void *screen, int fg, int bg, int flags, long *attrp)
{
adccscr_t * scr;
int maxcolor;
int newfg;
int newbg;
scr = screen;
maxcolor = (1 << scr->view->bitmap->depth) - 1;
/* Ensure the colors are displayable. */
newfg = fg & maxcolor;
newbg = bg & maxcolor;
#ifdef ADJUSTCOLORS
/*
* Hack for low-color screens, if background color is nonzero
* but would be displayed as one, adjust it.
*/
if (bg > 0 && newbg == 0)
newbg = maxcolor;
/*
* If foreground and background colors are different but would
* display the same fix them by modifying the foreground.
*/
if (fg != bg && newfg == newbg) {
if (newbg > 0)
newfg = 0;
else
newfg = maxcolor;
}
#endif
*attrp = MAKEATTR(newfg, newbg, flags);
return (0);
}
int
amidisplaycc_ioctl(void *dp, u_long cmd, caddr_t data, int flag, struct proc *p)
{
struct amidisplaycc_softc *adp;
adp = dp;
if (adp == NULL) {
printf("amidisplaycc_ioctl: adp==NULL\n");
return (EINVAL);
}
#define UINTDATA (*(u_int*)data)
#define INTDATA (*(int*)data)
#define FBINFO (*(struct wsdisplay_fbinfo*)data)
switch (cmd)
{
case WSDISPLAYIO_GTYPE:
UINTDATA = WSDISPLAY_TYPE_AMIGACC;
return (0);
case WSDISPLAYIO_SVIDEO:
dprintf("amidisplaycc: WSDISPLAYIO_SVIDEO %s\n",
UINTDATA ? "On" : "Off");
return (amidisplaycc_setvideo(adp, UINTDATA));
case WSDISPLAYIO_GVIDEO:
dprintf("amidisplaycc: WSDISPLAYIO_GVIDEO\n");
UINTDATA = adp->ison ?
WSDISPLAYIO_VIDEO_ON : WSDISPLAYIO_VIDEO_OFF;
return (0);
case WSDISPLAYIO_SMODE:
if (INTDATA == WSDISPLAYIO_MODE_EMUL)
return amidisplaycc_gfxscreen(adp, 0);
if (INTDATA == WSDISPLAYIO_MODE_MAPPED)
return amidisplaycc_gfxscreen(adp, 1);
return (EINVAL);
case WSDISPLAYIO_GINFO:
FBINFO.width = adp->gfxwidth;
FBINFO.height = adp->gfxheight;
FBINFO.depth = adp->gfxdepth;
FBINFO.cmsize = 1 << FBINFO.depth;
return (0);
case WSDISPLAYIO_PUTCMAP:
case WSDISPLAYIO_GETCMAP:
return (amidisplaycc_cmapioctl(adp->gfxview,
cmd,
(struct wsdisplay_cmap*)data));
}
dprintf("amidisplaycc: unknown ioctl %lx (grp:'%c' num:%d)\n",
(long)cmd,
(char)((cmd&0xff00)>>8),
(int)(cmd&0xff));
return (EPASSTHROUGH);
#undef UINTDATA
#undef INTDATA
#undef FBINFO
}
/*
* Switch to either emulation (text) or mapped (graphics) mode
* We keep an extra screen for mapped mode so it does not
* interfere with emulation screens.
*
* Once the extra screen is created, it never goes away.
*/
static int
amidisplaycc_gfxscreen(struct amidisplaycc_softc *adp, int on)
{
dimen_t dimension;
dprintf("amidisplaycc: switching to %s mode.\n",
on ? "mapped" : "emul");
/* Current mode same as requested mode? */
if ( (on > 0) == (adp->gfxon > 0) )
return (0);
if (!on) {
/*
* Switch away from mapped mode. If there is
* a emulation screen, switch to it, otherwise
* just try to hide the mapped screen.
*/
adp->gfxon = 0;
if (adp->currentscreen)
grf_display_view(adp->currentscreen->view);
else if (adp->gfxview)
grf_remove_view(adp->gfxview);
return (0);
}
/* switch to mapped mode then */
if (adp->gfxview == NULL) {
/* First time here, create the screen */
dimension.width = adp->gfxwidth;
dimension.height = adp->gfxheight;
dprintf("amidisplaycc: preparing mapped screen %dx%dx%d\n",
dimension.width,
dimension.height,
adp->gfxdepth);
adp->gfxview = grf_alloc_view(NULL,
&dimension,
adp->gfxdepth);
}
if (adp->gfxview) {
adp->gfxon = 1;
grf_display_view(adp->gfxview);
} else {
printf("amidisplaycc: failed to make mapped screen\n");
return (ENOMEM);
}
return (0);
}
/*
* Map the graphics screen. It must have been created before
* by switching to mapped mode by using an ioctl.
*/
paddr_t
amidisplaycc_mmap(void *dp, off_t off, int prot)
{
struct amidisplaycc_softc * adp;
bmap_t * bm;
paddr_t rv;
adp = (struct amidisplaycc_softc*)dp;
/* Check we are in mapped mode */
if (adp->gfxon == 0 || adp->gfxview == NULL) {
dprintf("amidisplaycc_mmap: Not in mapped mode\n");
return (paddr_t)(-1);
}
/*
* As we all know by now, we are mapping our special
* screen here so our pretty text consoles are left
* untouched.
*/
bm = adp->gfxview->bitmap;
/* Check that the offset is valid */
if (off < 0 || off >= bm->depth * bm->bytes_per_row * bm->rows) {
dprintf("amidisplaycc_mmap: Offset out of range\n");
return (paddr_t)(-1);
}
rv = (paddr_t)bm->hardware_address;
rv += off;
return (rv >> PGSHIFT);
}
/*
* Create a new screen.
* NULL dp signifies console and then memory is allocated statically
* and the screen is automatically displayed.
*
* A font with suitable size is searched and if not found
* the builtin 8x8 font is used.
*
* There are separate default palettes for 2, 4 and 8+ color
* screens.
*/
int
amidisplaycc_alloc_screen(void *dp, const struct wsscreen_descr *screenp,
void **cookiep, int *curxp, int *curyp,
long *defattrp)
{
const struct amidisplaycc_screen_descr * adccscreenp;
struct amidisplaycc_screen * scr;
struct amidisplaycc_softc * adp;
view_t * view;
dimen_t dimension;
int fontheight;
int fontwidth;
int maxcolor;
int depth;
int i;
int j;
adccscreenp = (const struct amidisplaycc_screen_descr *)screenp;
depth = adccscreenp->depth;
adp = dp;
maxcolor = (1 << depth) - 1;
/* Sanity checks because of fixed buffers */
if (depth > MAXDEPTH || maxcolor >= MAXCOLORS)
return (ENOMEM);
if (screenp->nrows > MAXROWS)
return (ENOMEM);
fontwidth = screenp->fontwidth;
fontheight = screenp->fontheight;
if (fontwidth != 8) {
dprintf("amidisplaycc_alloc_screen: fontwidth %d invalid.\n",
fontwidth);
return (EINVAL);
}
/*
* The screen size is defined in characters.
* Calculate the pixel size using the font size.
*/
dimension.width = screenp->ncols * fontwidth;
dimension.height = screenp->nrows * fontheight;
view = grf_alloc_view(NULL, &dimension, depth);
if (view == NULL)
return (ENOMEM);
/*
* First screen gets the statically allocated console screen.
* Others are allocated dynamically.
*/
if (adp == NULL) {
scr = &amidisplaycc_consolescreen;
if (scr->isconsole)
panic("more than one console?");
scr->isconsole = 1;
} else {
scr = malloc(sizeof(adccscr_t), M_DEVBUF, M_WAITOK);
bzero(scr, sizeof(adccscr_t));
}
scr->view = view;
scr->ncols = screenp->ncols;
scr->nrows = screenp->nrows;
/* Copies of most used values */
scr->width = dimension.width;
scr->height = dimension.height;
scr->depth = depth;
scr->widthbytes = view->bitmap->bytes_per_row;
scr->linebytes = scr->widthbytes + view->bitmap->row_mod;
scr->rowbytes = scr->linebytes * fontheight;
scr->device = adp;
/* --- LOAD FONT --- */
/* these need to be initialized befory trying to set font */
scr->font = NULL;
scr->wsfontcookie = -1;
scr->fontwidth = fontwidth;
scr->fontheight = fontheight;
/*
* Note that dont try to load font for the console (adp==NULL)
*
* Here we dont care which font we get as long as it is the
* right size so pass NULL.
*/
if (adp)
amidisplaycc_setnamedfont(scr, NULL);
/*
* If no font found, use the builtin one.
* It will look stupid if the wanted size was different.
*/
if (scr->font == NULL) {
scr->fontwidth = 8;
scr->fontheight = min(8, fontheight);
}
/* --- LOAD FONT END --- */
for (i = 0 ; i < depth ; i++) {
scr->planes[i] = view->bitmap->plane[i];
}
for (i = 0 ; i < MAXROWS ; i++)
scr->rowmasks[i] = 0;
/* Simple one-to-one mapping for most colors */
for (i = 0 ; i < MAXCOLORS ; i++)
scr->colormap[i] = i;
/*
* Arrange the most used pens to quickest colors.
* The default color for given depth is (1<<depth)-1.
* It is assumed it is used most and it is mapped to
* color that can be drawn by writing data to one bitplane
* only.
* So map colors 3->2, 7->4, 15->8 and so on.
*/
for (i = 2 ; i < MAXCOLORS ; i *= 2) {
j = i * 2 - 1;
if (j < MAXCOLORS) {
scr->colormap[i] = j;
scr->colormap[j] = i;
}
}
/*
* Set the default colormap.
*/
if (depth == 1)
amidisplaycc_setemulcmap(scr, &pal2);
else if (depth == 2)
amidisplaycc_setemulcmap(scr, &pal4);
else
amidisplaycc_setemulcmap(scr, &pal8);
*cookiep = scr;
*curxp = 0;
*curyp = 0;
amidisplaycc_cursor(scr, 1, *curxp, *curyp);
*defattrp = MAKEATTR(maxcolor, 0, 0);
/* Show the console automatically */
if (adp == NULL)
grf_display_view(scr->view);
if (adp) {
dprintf("amidisplaycc: allocated screen; %dx%dx%d\n",
dimension.width,
dimension.height,
depth);
}
return (0);
}
/*
* Destroy a screen.
*/
void
amidisplaycc_free_screen(void *dp, void *screen)
{
struct amidisplaycc_screen * scr;
struct amidisplaycc_softc * adp;
scr = screen;
adp = (struct amidisplaycc_softc*)adp;
if (scr == NULL)
return;
/* Free the used font */
amidisplaycc_setfont(scr, NULL, -1);
if (adp->currentscreen == scr)
adp->currentscreen = NULL;
if (scr->view)
grf_free_view(scr->view);
scr->view = NULL;
/* Take care not to free the statically allocated console screen */
if (scr != &amidisplaycc_consolescreen) {
free(scr, M_DEVBUF);
}
}
/*
* Switch to another vt. Switch is always made immediately.
*/
/* ARGSUSED2 */
int
amidisplaycc_show_screen(void *dp, void *screen, int waitok,
void (*cb) (void *, int, int), void *cbarg)
{
adccscr_t *scr;
struct amidisplaycc_softc *adp;
adp = (struct amidisplaycc_softc*)dp;
scr = screen;
if (adp == NULL) {
dprintf("amidisplaycc_show_screen: adp==NULL\n");
return (EINVAL);
}
if (scr == NULL) {
dprintf("amidisplaycc_show_screen: scr==NULL\n");
return (EINVAL);
}
if (adp->gfxon) {
dprintf("amidisplaycc: Screen shift while in gfx mode?");
adp->gfxon = 0;
}
adp->currentscreen = scr;
adp->ison = 1;
grf_display_view(scr->view);
return (0);
}
/*
* Internal. Finds the font in our softc that has the desired attributes.
* Or, if name is NULL, finds a free location for a new font.
* Returns a pointer to font structure in softc or NULL for failure.
*
* Three possible forms:
* findfont(adp, NULL, 0, 0) -- find first empty location
* findfont(adp, NULL, x, y) -- find last font with given size
* findfont(adp, name, x, y) -- find last font with given name and size
*
* Note that when finding an empty location first one found is returned,
* however when finding an existing font, the last one matching is
* returned. This is because fonts cannot be unloaded and the last
* font on the list is the one added latest and thus probably preferred.
*
* Note also that this is the only function which makes assumptions
* about the storage location for the fonts.
*/
static struct wsdisplay_font *
amidisplaycc_findfont(struct amidisplaycc_softc *adp, const char *name,
int width, int height)
{
struct wsdisplay_font * font;
int findempty;
int f;
if (adp == NULL) {
dprintf("amidisplaycc_findfont: NULL adp\n");
return NULL;
}
findempty = (name == NULL) && (width == 0) && (height == 0);
font = NULL;
for (f = 0 ; f < AMIDISPLAYCC_MAXFONTS ; f++) {
if (findempty && adp->fonts[f].name == NULL)
return &adp->fonts[f];
if (!findempty && name == NULL && adp->fonts[f].name &&
adp->fonts[f].fontwidth == width &&
adp->fonts[f].fontheight == height)
font = &adp->fonts[f];
if (name && adp->fonts[f].name &&
strcmp(name, adp->fonts[f].name) == 0 &&
width == adp->fonts[f].fontwidth &&
height == adp->fonts[f].fontheight)
font = &adp->fonts[f];
}
return (font);
}
/*
* Set the font on a screen and free the old one.
* Can be called with font of NULL to just free the
* old one.
* NULL font cannot be accompanied by valid cookie (!= -1)
*/
static void
amidisplaycc_setfont(struct amidisplaycc_screen *scr,
struct wsdisplay_font *font, int wsfontcookie)
{
if (scr == NULL)
panic("amidisplaycc_setfont: scr==NULL");
if (font == NULL && wsfontcookie != -1)
panic("amidisplaycc_setfont: no font but eat cookie");
if (scr->font == NULL && scr->wsfontcookie != -1)
panic("amidisplaycc_setfont: no font but eat old cookie");
scr->font = font;
if (scr->wsfontcookie != -1)
wsfont_unlock(scr->wsfontcookie);
scr->wsfontcookie = wsfontcookie;
}
/*
* Try to find the named font and set the screen to use it.
* Check both the fonts we have loaded with load_font and
* fonts from wsfont system.
*
* Returns 0 on success.
*/
static int
amidisplaycc_setnamedfont(struct amidisplaycc_screen *scr, char *fontname)
{
struct wsdisplay_font * font;
int wsfontcookie;
wsfontcookie = -1;
if (scr == NULL || scr->device == NULL) {
dprintf("amidisplaycc_setnamedfont: invalid\n");
return (EINVAL);
}
/* Try first our dynamically loaded fonts. */
font = amidisplaycc_findfont(scr->device,
fontname,
scr->fontwidth,
scr->fontheight);
if (font == NULL) {
/*
* Ok, no dynamically loaded font found.
* Try the wsfont system then.
*/
wsfontcookie = wsfont_find(fontname,
scr->fontwidth,
scr->fontheight,
1,
WSDISPLAY_FONTORDER_L2R,
WSDISPLAY_FONTORDER_L2R);
if (wsfontcookie == -1)
return (EINVAL);
/* So, found a suitable font. Now lock it. */
if (wsfont_lock(wsfontcookie,
&font))
return (EINVAL);
/* Ok here we have the font successfully. */
}
amidisplaycc_setfont(scr, font, wsfontcookie);
return (0);
}
/*
* Load a font. This is used both to load a font and set it to screen.
* The function depends on the parameters.
* If the font has no data we must set a previously loaded
* font with the same name. If it has data, then just load
* the font but don't use it.
*/
int
amidisplaycc_load_font(void *dp, void *cookie, struct wsdisplay_font *font)
{
struct amidisplaycc_softc * adp;
struct amidisplaycc_screen * scr;
struct wsdisplay_font * myfont;
u_int8_t * c;
void * olddata;
char * name;
u_int size;
u_int i;
adp = dp;
scr = cookie;
/*
* If font has no data it means we have to find the
* named font and use it.
*/
if (scr && font && font->name && !font->data)
return amidisplaycc_setnamedfont(scr, font->name);
/* Pre-load the font it is */
if (font->stride != 1) {
dprintf("amidisplaycc_load_font: stride %d != 1\n",
font->stride);
return (EINVAL);
}
if (font->fontwidth != 8) {
dprintf("amidisplaycc_load_font: width %d not supported\n",
font->fontwidth);
return (EINVAL);
}
/* Size of the font in bytes... Assuming stride==1 */
size = font->fontheight * font->numchars;
/* Check if the same font was loaded before */
myfont = amidisplaycc_findfont(adp,
font->name,
font->fontwidth,
font->fontheight);
olddata = NULL;
if (myfont) {
/* Old font found, we will replace */
if (myfont->name == NULL || myfont->data == NULL)
panic("replacing NULL font/data");
/*
* Store the old data pointer. We'll free it later
* when the new one is in place. Reallocation is needed
* because the new font may have a different number
* of characters in it than the last time it was loaded.
*/
olddata = myfont->data;
} else {
/* Totally brand new font */
/* Try to find empty slot for the font */
myfont = amidisplaycc_findfont(adp, NULL, 0, 0);
if (myfont == NULL)
return (ENOMEM);
bzero(myfont, sizeof(struct wsdisplay_font));
myfont->fontwidth = font->fontwidth;
myfont->fontheight = font->fontheight;
myfont->stride = font->stride;
name = malloc(strlen(font->name)+1,
M_DEVBUF,
M_WAITOK);
strcpy(name, font->name);
myfont->name = name;
}
myfont->firstchar = font->firstchar;
myfont->numchars = font->numchars;
myfont->data = malloc(size,
M_DEVBUF,
M_WAITOK);
if (olddata)
free(olddata, M_DEVBUF);
memcpy(myfont->data, font->data, size);
if (font->bitorder == WSDISPLAY_FONTORDER_R2L) {
/* Reverse the characters. */
c = myfont->data;
for (i = 0 ; i < size ; i++) {
*c = ((*c & 0x0f) << 4) | ((*c & 0xf0) >> 4);
*c = ((*c & 0x33) << 2) | ((*c & 0xcc) >> 2);
*c = ((*c & 0x55) << 1) | ((*c & 0xaa) >> 1);
c++;
}
}
/* Yeah, we made it */
return (0);
}
/*
* Set display on/off.
*/
static int
amidisplaycc_setvideo(struct amidisplaycc_softc *adp, int mode)
{
view_t * view;
if (adp == NULL) {
dprintf("amidisplaycc_setvideo: adp==NULL\n");
return (EINVAL);
}
if (adp->currentscreen == NULL) {
dprintf("amidisplaycc_setvideo: adp->currentscreen==NULL\n");
return (EINVAL);
}
/* select graphics or emulation screen */
if (adp->gfxon && adp->gfxview)
view = adp->gfxview;
else
view = adp->currentscreen->view;
if (mode) {
/* on */
grf_display_view(view);
dprintf("amidisplaycc: video is now on\n");
adp->ison = 1;
} else {
/* off */
grf_remove_view(view);
dprintf("amidisplaycc: video is now off\n");
adp->ison = 0;
}
return (0);
}
/*
* Handle the WSDISPLAY_[PUT/GET]CMAP ioctls.
* Just handle the copying of data to/from userspace and
* let the functions amidisplaycc_setcmap and amidisplaycc_putcmap
* do the real work.
*/
static int
amidisplaycc_cmapioctl(view_t *view, u_long cmd, struct wsdisplay_cmap *cmap)
{
struct wsdisplay_cmap tmpcmap;
u_char cmred[MAXCOLORS];
u_char cmgrn[MAXCOLORS];
u_char cmblu[MAXCOLORS];
int err;
if (cmap->index >= MAXCOLORS ||
cmap->count > MAXCOLORS ||
cmap->index + cmap->count > MAXCOLORS)
return (EINVAL);
if (cmap->count == 0)
return (0);
tmpcmap.index = cmap->index;
tmpcmap.count = cmap->count;
tmpcmap.red = cmred;
tmpcmap.green = cmgrn;
tmpcmap.blue = cmblu;
if (cmd == WSDISPLAYIO_PUTCMAP) {
/* copy the color data to kernel space */
err = copyin(cmap->red, cmred, cmap->count);
if (err)
return (err);
err = copyin(cmap->green, cmgrn, cmap->count);
if (err)
return (err);
err = copyin(cmap->blue, cmblu, cmap->count);
if (err)
return (err);
return amidisplaycc_setcmap(view, &tmpcmap);
} else if (cmd == WSDISPLAYIO_GETCMAP) {
err = amidisplaycc_getcmap(view, &tmpcmap);
if (err)
return (err);
/* copy data to user space */
err = copyout(cmred, cmap->red, cmap->count);
if (err)
return (err);
err = copyout(cmgrn, cmap->green, cmap->count);
if (err)
return (err);
err = copyout(cmblu, cmap->blue, cmap->count);
if (err)
return (err);
return (0);
} else
return (EPASSTHROUGH);
}
/*
* Set the palette of a emulation screen.
* Here we do only color remapping and then call
* amidisplaycc_setcmap to do the work.
*/
static int
amidisplaycc_setemulcmap(struct amidisplaycc_screen *scr,
struct wsdisplay_cmap *cmap)
{
struct wsdisplay_cmap tmpcmap;
u_char red [MAXCOLORS];
u_char grn [MAXCOLORS];
u_char blu [MAXCOLORS];
int rc;
int i;
/*
* Get old palette first.
* Because of the color mapping going on in the emulation
* screen the color range may not be contiguous in the real
* palette.
* So get the whole palette, insert the new colors
* at the appropriate places and then set the whole
* palette back.
*/
tmpcmap.index = 0;
tmpcmap.count = 1 << scr->depth;
tmpcmap.red = red;
tmpcmap.green = grn;
tmpcmap.blue = blu;
rc = amidisplaycc_getcmap(scr->view, &tmpcmap);
if (rc)
return (rc);
for (i = cmap->index ; i < cmap->index + cmap->count ; i++) {
tmpcmap.red [ scr->colormap[ i ] ] = cmap->red [ i ];
tmpcmap.green [ scr->colormap[ i ] ] = cmap->green [ i ];
tmpcmap.blue [ scr->colormap[ i ] ] = cmap->blue [ i ];
}
rc = amidisplaycc_setcmap(scr->view, &tmpcmap);
if (rc)
return (rc);
return (0);
}
/*
* Set the colormap for the given screen.
*/
static int
amidisplaycc_setcmap(view_t *view, struct wsdisplay_cmap *cmap)
{
u_long cmentries [MAXCOLORS];
int green_div;
int blue_div;
int grey_div;
int red_div;
u_int colors;
int index;
int count;
int err;
colormap_t cm;
int c;
if (view == NULL)
return (EINVAL);
if (!cmap || !cmap->red || !cmap->green || !cmap->blue) {
dprintf("amidisplaycc_setcmap: other==NULL\n");
return (EINVAL);
}
index = cmap->index;
count = cmap->count;
colors = (1 << view->bitmap->depth);
if (count > colors || index >= colors || index + count > colors)
return (EINVAL);
if (count == 0)
return (0);
cm.entry = cmentries;
cm.first = index;
cm.size = count;
/*
* Get the old colormap. We need to do this at least to know
* how many bits to use with the color values.
*/
err = grf_get_colormap(view, &cm);
if (err)
return (err);
/*
* The palette entries from wscons contain 8 bits per gun.
* We need to convert them to the number of bits the view
* expects. That is typically 4 or 8. Here we calculate the
* conversion constants with which we divide the color values.
*/
if (cm.type == CM_COLOR) {
red_div = 256 / (cm.red_mask + 1);
green_div = 256 / (cm.green_mask + 1);
blue_div = 256 / (cm.blue_mask + 1);
} else if (cm.type == CM_GREYSCALE)
grey_div = 256 / (cm.grey_mask + 1);
else
return (EINVAL); /* Hmhh */
/* Copy our new values to the current colormap */
for (c = 0 ; c < count ; c++) {
if (cm.type == CM_COLOR) {
cm.entry[c + index] = MAKE_COLOR_ENTRY(
cmap->red[c] / red_div,
cmap->green[c] / green_div,
cmap->blue[c] / blue_div);
} else if (cm.type == CM_GREYSCALE) {
/* Generate grey from average of r-g-b (?) */
cm.entry[c + index] = MAKE_COLOR_ENTRY(
0,
0,
(cmap->red[c] +
cmap->green[c] +
cmap->blue[c]) / 3 / grey_div);
}
}
/*
* Now we have a new colormap that contains all the entries. Set
* it to the view.
*/
err = grf_use_colormap(view, &cm);
if (err)
return err;
return (0);
}
/*
* Return the colormap of the given screen.
*/
static int
amidisplaycc_getcmap(view_t *view, struct wsdisplay_cmap *cmap)
{
u_long cmentries [MAXCOLORS];
int green_mul;
int blue_mul;
int grey_mul;
int red_mul;
u_int colors;
int index;
int count;
int err;
colormap_t cm;
int c;
if (view == NULL)
return (EINVAL);
if (!cmap || !cmap->red || !cmap->green || !cmap->blue)
return (EINVAL);
index = cmap->index;
count = cmap->count;
colors = (1 << view->bitmap->depth);
if (count > colors || index >= colors || index + count > colors)
return (EINVAL);
if (count == 0)
return (0);
cm.entry = cmentries;
cm.first = index;
cm.size = count;
err = grf_get_colormap(view, &cm);
if (err)
return (err);
if (cm.type == CM_COLOR) {
red_mul = 256 / (cm.red_mask + 1);
green_mul = 256 / (cm.green_mask + 1);
blue_mul = 256 / (cm.blue_mask + 1);
} else if (cm.type == CM_GREYSCALE) {
grey_mul = 256 / (cm.grey_mask + 1);
} else
return (EINVAL);
/*
* Copy color data to wscons-style structure. Translate to
* 8 bits/gun from whatever resolution the color natively is.
*/
for (c = 0 ; c < count ; c++) {
if (cm.type == CM_COLOR) {
cmap->red[c] = CM_GET_RED(cm.entry[index+c]);
cmap->green[c] = CM_GET_GREEN(cm.entry[index+c]);
cmap->blue[c] = CM_GET_BLUE(cm.entry[index+c]);
cmap->red[c] *= red_mul;
cmap->green[c] *= green_mul;
cmap->blue[c] *= blue_mul;
} else if (cm.type == CM_GREYSCALE) {
cmap->red[c] = CM_GET_GREY(cm.entry[index+c]);
cmap->red[c] *= grey_mul;
cmap->green[c] = cmap->red[c];
cmap->blue[c] = cmap->red[c];
}
}
return (0);
}
/* ARGSUSED */
void
amidisplaycc_pollc(void *cookie, int on)
{
}
/*
* These dummy functions are here just so that we can compete of
* the console at init.
* If we win the console then the wscons system will provide the
* real ones which in turn will call the apropriate wskbd device.
* These should never be called.
*/
/* ARGSUSED */
void
amidisplaycc_cnputc(dev_t cd, int ch)
{
}
/* ARGSUSED */
int
amidisplaycc_cngetc(dev_t cd)
{
return (0);
}
/* ARGSUSED */
void
amidisplaycc_cnpollc(dev_t cd, int on)
{
}
/*
* Prints stuff if DEBUG is turned on.
*/
/* ARGSUSED */
static void
dprintf(const char *fmt, ...)
{
#ifdef DEBUG
va_list ap;
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
#endif
}
#endif /* AMIDISPLAYCC */
| 22.462954 | 87 | 0.644068 | [
"render"
] |
f4fe64214e56d702a4134cb0c436d38ed7086393 | 4,112 | h | C | Scripts/Template/Headers/org/apache/xalan/processor/ProcessorPreserveSpace.h | zhouxl/J2ObjC-Framework | ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1 | [
"MIT"
] | null | null | null | Scripts/Template/Headers/org/apache/xalan/processor/ProcessorPreserveSpace.h | zhouxl/J2ObjC-Framework | ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1 | [
"MIT"
] | null | null | null | Scripts/Template/Headers/org/apache/xalan/processor/ProcessorPreserveSpace.h | zhouxl/J2ObjC-Framework | ff83a41f44aaab295dbd4f4b4b02d5e894cdc2e1 | [
"MIT"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: /Users/antoniocortes/j2objcprj/relases/j2objc/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xalan/processor/ProcessorPreserveSpace.java
//
#include "../../../../J2ObjC_header.h"
#pragma push_macro("INCLUDE_ALL_OrgApacheXalanProcessorProcessorPreserveSpace")
#ifdef RESTRICT_OrgApacheXalanProcessorProcessorPreserveSpace
#define INCLUDE_ALL_OrgApacheXalanProcessorProcessorPreserveSpace 0
#else
#define INCLUDE_ALL_OrgApacheXalanProcessorProcessorPreserveSpace 1
#endif
#undef RESTRICT_OrgApacheXalanProcessorProcessorPreserveSpace
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif
#if !defined (OrgApacheXalanProcessorProcessorPreserveSpace_) && (INCLUDE_ALL_OrgApacheXalanProcessorProcessorPreserveSpace || defined(INCLUDE_OrgApacheXalanProcessorProcessorPreserveSpace))
#define OrgApacheXalanProcessorProcessorPreserveSpace_
#define RESTRICT_OrgApacheXalanProcessorXSLTElementProcessor 1
#define INCLUDE_OrgApacheXalanProcessorXSLTElementProcessor 1
#include "../../../../org/apache/xalan/processor/XSLTElementProcessor.h"
@class OrgApacheXalanProcessorStylesheetHandler;
@protocol OrgXmlSaxAttributes;
/*!
@brief TransformerFactory for xsl:preserve-space markup.
@code
<!ELEMENT xsl:preserve-space EMPTY>
<!ATTLIST xsl:preserve-space elements CDATA #REQUIRED>
@endcode
*/
@interface OrgApacheXalanProcessorProcessorPreserveSpace : OrgApacheXalanProcessorXSLTElementProcessor
@property (readonly, class) jlong serialVersionUID NS_SWIFT_NAME(serialVersionUID);
+ (jlong)serialVersionUID;
#pragma mark Public
/*!
@brief Receive notification of the start of an preserve-space element.
@param handler The calling StylesheetHandler/TemplatesBuilder.
@param uri The Namespace URI, or the empty string if the element has no Namespace URI or if Namespace
processing is not being performed.
@param localName The local name (without prefix), or the empty string if Namespace processing is not being
performed.
@param rawName The raw XML 1.0 name (with prefix), or the empty string if raw names are not available.
@param attributes The attributes attached to the element. If there are no attributes, it shall be an empty
Attributes object.
*/
- (void)startElementWithOrgApacheXalanProcessorStylesheetHandler:(OrgApacheXalanProcessorStylesheetHandler *)handler
withNSString:(NSString *)uri
withNSString:(NSString *)localName
withNSString:(NSString *)rawName
withOrgXmlSaxAttributes:(id<OrgXmlSaxAttributes>)attributes;
#pragma mark Package-Private
- (instancetype __nonnull)init;
@end
J2OBJC_EMPTY_STATIC_INIT(OrgApacheXalanProcessorProcessorPreserveSpace)
inline jlong OrgApacheXalanProcessorProcessorPreserveSpace_get_serialVersionUID(void);
#define OrgApacheXalanProcessorProcessorPreserveSpace_serialVersionUID -5552836470051177302LL
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXalanProcessorProcessorPreserveSpace, serialVersionUID, jlong)
FOUNDATION_EXPORT void OrgApacheXalanProcessorProcessorPreserveSpace_init(OrgApacheXalanProcessorProcessorPreserveSpace *self);
FOUNDATION_EXPORT OrgApacheXalanProcessorProcessorPreserveSpace *new_OrgApacheXalanProcessorProcessorPreserveSpace_init(void) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT OrgApacheXalanProcessorProcessorPreserveSpace *create_OrgApacheXalanProcessorProcessorPreserveSpace_init(void);
J2OBJC_TYPE_LITERAL_HEADER(OrgApacheXalanProcessorProcessorPreserveSpace)
#endif
#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma clang diagnostic pop
#pragma pop_macro("INCLUDE_ALL_OrgApacheXalanProcessorProcessorPreserveSpace")
| 42.391753 | 190 | 0.800584 | [
"object"
] |
76026b3757f0976768228c0ea6cec55291d2cebc | 1,986 | h | C | src/cbmc/symex_bmc.h | manasij7479/cbmc | f881e431b88c4134e2f47d3d0faa3e49e1f79d9c | [
"BSD-4-Clause"
] | null | null | null | src/cbmc/symex_bmc.h | manasij7479/cbmc | f881e431b88c4134e2f47d3d0faa3e49e1f79d9c | [
"BSD-4-Clause"
] | null | null | null | src/cbmc/symex_bmc.h | manasij7479/cbmc | f881e431b88c4134e2f47d3d0faa3e49e1f79d9c | [
"BSD-4-Clause"
] | null | null | null | /*******************************************************************\
Module: Bounded Model Checking for ANSI-C
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#ifndef CPROVER_CBMC_SYMEX_BMC_H
#define CPROVER_CBMC_SYMEX_BMC_H
#include <util/hash_cont.h>
#include <util/message.h>
#include <goto-symex/goto_symex.h>
class symex_bmct:
public goto_symext,
public messaget
{
public:
symex_bmct(
const namespacet &_ns,
symbol_tablet &_new_symbol_table,
symex_targett &_target);
// To show progress
source_locationt last_source_location;
// Control unwinding.
void set_unwind_limit(unsigned limit)
{
max_unwind=limit;
max_unwind_is_set=true;
}
void set_unwind_thread_loop_limit(
unsigned thread_nr,
const irep_idt &id,
unsigned limit)
{
thread_loop_limits[thread_nr][id]=limit;
}
void set_unwind_loop_limit(
const irep_idt &id,
unsigned limit)
{
loop_limits[id]=limit;
}
protected:
// We have
// 1) a global limit (max_unwind)
// 2) a limit per loop, all threads
// 3) a limit for a particular thread.
// We use the most specific of the above.
unsigned max_unwind;
bool max_unwind_is_set;
typedef hash_map_cont<irep_idt, unsigned, irep_id_hash> loop_limitst;
loop_limitst loop_limits;
typedef std::map<unsigned, loop_limitst> thread_loop_limitst;
thread_loop_limitst thread_loop_limits;
//
// overloaded from goto_symext
//
virtual void symex_step(
const goto_functionst &goto_functions,
statet &state);
// for loop unwinding
virtual bool get_unwind(
const symex_targett::sourcet &source,
unsigned unwind);
virtual bool get_unwind_recursion(
const irep_idt &identifier,
const unsigned thread_nr,
unsigned unwind);
virtual void no_body(const irep_idt &identifier);
hash_set_cont<irep_idt, irep_id_hash> body_warnings;
};
#endif // CPROVER_CBMC_SYMEX_BMC_H
| 21.586957 | 71 | 0.682779 | [
"model"
] |
7602b210607fd8ed06a8fae41f7abf768b524727 | 1,154 | h | C | src/rotate.h | aleksi-kangas/raytracing | 8aa2ce87ae000a8c2aefb1263e6b0e7e10d84fa4 | [
"CC0-1.0"
] | null | null | null | src/rotate.h | aleksi-kangas/raytracing | 8aa2ce87ae000a8c2aefb1263e6b0e7e10d84fa4 | [
"CC0-1.0"
] | null | null | null | src/rotate.h | aleksi-kangas/raytracing | 8aa2ce87ae000a8c2aefb1263e6b0e7e10d84fa4 | [
"CC0-1.0"
] | null | null | null | #pragma once
#include <memory>
#include "aabb.h"
#include "collidable.h"
#include "material.h"
#include "ray.h"
#include "vector3d.h"
class RotateY : public Collidable {
public:
RotateY(std::shared_ptr<Collidable> object, double angle_degrees);
/**
* Compute collision of a ray and the rotated object.
* @param[in] ray inbound ray
* @param[in] t_min minimum threshold
* @param[in] t_max maximum threshold
* @param[out] collision receives collision information
* @return true if collision happened, false otherwise
*/
bool Collide(const Ray &ray, double t_min, double t_max, Collision &collision) const override;
/**
* Compute a minimum AABB that surrounds the rotated object.
* @param[in] time0 minimum threshold
* @param[in] time1 maximum threshold
* @param[out] bounding_box receives the computed AABB
* @return true if an AABB exists, false otherwise
*/
bool BoundingBox(double time0, double time1, AxisAlignedBoundingBox &bounding_box) const override;
private:
std::shared_ptr<Collidable> object_;
double sin_theta_, cos_theta_;
bool has_box_;
AxisAlignedBoundingBox bounding_box_;
};
| 28.85 | 100 | 0.731369 | [
"object"
] |
7603189db7b7b207d8bb6d738c61618df5f970be | 4,376 | h | C | ns-allinone-3.30/ns-3.30/src/wifi/model/aparf-wifi-manager.h | NEWPLAN/ns3_v3.30 | c931036574ee1efd58dad6df3f6d8365b4948bcd | [
"Apache-2.0"
] | null | null | null | ns-allinone-3.30/ns-3.30/src/wifi/model/aparf-wifi-manager.h | NEWPLAN/ns3_v3.30 | c931036574ee1efd58dad6df3f6d8365b4948bcd | [
"Apache-2.0"
] | null | null | null | ns-allinone-3.30/ns-3.30/src/wifi/model/aparf-wifi-manager.h | NEWPLAN/ns3_v3.30 | c931036574ee1efd58dad6df3f6d8365b4948bcd | [
"Apache-2.0"
] | 1 | 2019-10-23T15:15:27.000Z | 2019-10-23T15:15:27.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2014 Universidad de la República - Uruguay
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Matias Richart <mrichart@fing.edu.uy>
*/
#ifndef APARF_WIFI_MANAGER_H
#define APARF_WIFI_MANAGER_H
#include "wifi-remote-station-manager.h"
namespace ns3
{
struct AparfWifiRemoteStation;
/**
* \ingroup wifi
* APARF Power and rate control algorithm
*
* This class implements the High Performance power and rate control algorithm
* described in <i>Dynamic data rate and transmit power adjustment
* in IEEE 802.11 wireless LANs</i> by Chevillat, P.; Jelitto, J.
* and Truong, H. L. in International Journal of Wireless Information
* Networks, Springer, 2005, 12, 123-145.
* http://www.cs.mun.ca/~yzchen/papers/papers/rate_adaptation/80211_dynamic_rate_power_adjustment_chevillat_j2005.pdf
*
* This RAA does not support HT, VHT nor HE modes and will error
* exit if the user tries to configure this RAA with a Wi-Fi MAC
* that has VhtSupported, HtSupported or HeSupported set.
*/
class AparfWifiManager : public WifiRemoteStationManager
{
public:
/**
* Register this type.
* \return The object TypeId.
*/
static TypeId GetTypeId(void);
AparfWifiManager();
virtual ~AparfWifiManager();
// Inherited from WifiRemoteStationManager
void SetupPhy(const Ptr<WifiPhy> phy);
/**
* Enumeration of the possible states of the channel.
*/
enum State
{
High,
Low,
Spread
};
private:
// Overridden from base class.
void DoInitialize(void);
WifiRemoteStation *DoCreateStation(void) const;
void DoReportRxOk(WifiRemoteStation *station,
double rxSnr, WifiMode txMode);
void DoReportRtsFailed(WifiRemoteStation *station);
void DoReportDataFailed(WifiRemoteStation *station);
void DoReportRtsOk(WifiRemoteStation *station,
double ctsSnr, WifiMode ctsMode, double rtsSnr);
void DoReportDataOk(WifiRemoteStation *station,
double ackSnr, WifiMode ackMode, double dataSnr);
void DoReportFinalRtsFailed(WifiRemoteStation *station);
void DoReportFinalDataFailed(WifiRemoteStation *station);
WifiTxVector DoGetDataTxVector(WifiRemoteStation *station);
WifiTxVector DoGetRtsTxVector(WifiRemoteStation *station);
bool IsLowLatency(void) const;
/** Check for initializations.
*
* \param station The remote station.
*/
void CheckInit(AparfWifiRemoteStation *station);
uint32_t m_succesMax1; //!< The minimum number of successful transmissions in \"High\" state to try a new power or rate.
uint32_t m_succesMax2; //!< The minimum number of successful transmissions in \"Low\" state to try a new power or rate.
uint32_t m_failMax; //!< The minimum number of failed transmissions to try a new power or rate.
uint32_t m_powerMax; //!< The maximum number of power changes.
uint8_t m_powerInc; //!< Step size for increment the power.
uint8_t m_powerDec; //!< Step size for decrement the power.
uint8_t m_rateInc; //!< Step size for increment the rate.
uint8_t m_rateDec; //!< Step size for decrement the rate.
/**
* Minimal power level.
* Differently form rate, power levels do not depend on the remote station.
* The levels depend only on the physical layer of the device.
*/
uint8_t m_minPower;
/**
* Maximal power level.
*/
uint8_t m_maxPower;
/**
* The trace source fired when the transmission power changes.
*/
TracedCallback<double, double, Mac48Address> m_powerChange;
/**
* The trace source fired when the transmission rate changes.
*/
TracedCallback<DataRate, DataRate, Mac48Address> m_rateChange;
};
} //namespace ns3
#endif /* APARF_WIFI_MANAGER_H */
| 34.1875 | 122 | 0.72692 | [
"object"
] |
760407ee2ec6112b9b1985435a67f7a8476749ff | 3,060 | h | C | c11httpd/conn_event_adapter.h | toalexjin/c11httpd | 6774d96c72d60ad8c371a6d846744a9ccc98d7ee | [
"MIT"
] | null | null | null | c11httpd/conn_event_adapter.h | toalexjin/c11httpd | 6774d96c72d60ad8c371a6d846744a9ccc98d7ee | [
"MIT"
] | null | null | null | c11httpd/conn_event_adapter.h | toalexjin/c11httpd | 6774d96c72d60ad8c371a6d846744a9ccc98d7ee | [
"MIT"
] | null | null | null | /**
* Client connection event adapter.
*
* Copyright (c) 2015 Alex Jin (toalexjin@hotmail.com)
*/
#pragma once
#include "c11httpd/pre__.h"
#include "c11httpd/config.h"
#include "c11httpd/conn_event.h"
#include <functional>
#include <vector>
namespace c11httpd {
// Client connection event adapter.
//
// With this class, you could quickly create an event handler by using c++ lambda.
class conn_event_adapter_t : public conn_event_t {
public:
typedef std::function<uint32_t(ctx_setter_t&, const config_t&, conn_session_t&, buf_t&)> on_connected_t;
typedef std::function<void(ctx_setter_t&, const config_t&, conn_session_t&)> on_disconnected_t;
typedef std::function<uint32_t(ctx_setter_t&, const config_t&, conn_session_t&, buf_t&, buf_t&)> on_received_t;
typedef std::function<uint32_t(ctx_setter_t&, const config_t&, conn_session_t&, buf_t&)> get_more_data_t;
typedef std::function<uint32_t(ctx_setter_t&, const config_t&, conn_session_t&,
int, const std::vector<aio_t>&, buf_t&)> on_aio_completed_t;
public:
conn_event_adapter_t() = default;
virtual ~conn_event_adapter_t() = default;
// Getter/Setter for lambda functions.
const on_connected_t& lambda_on_connected() const {
return this->m_on_connected;
}
void lambda_on_connected(const on_connected_t& handler) {
this->m_on_connected = handler;
}
const on_disconnected_t& lambda_on_disconnected() const {
return this->m_on_disconnected;
}
void lambda_on_disconnected(const on_disconnected_t& handler) {
this->m_on_disconnected = handler;
}
const on_received_t& lambda_on_received() const {
return this->m_on_received;
}
void lambda_on_received(const on_received_t& handler) {
this->m_on_received = handler;
}
const get_more_data_t& lambda_get_more_data() const {
return this->m_get_more_data;
}
void lambda_get_more_data(const get_more_data_t& handler) {
this->m_get_more_data = handler;
}
const on_aio_completed_t& lambda_on_aio_completed() const {
return this->m_on_aio_completed;
}
void lambda_on_aio_completed(const on_aio_completed_t& handler) {
this->m_on_aio_completed = handler;
}
// Event callback functions.
virtual uint32_t on_connected(
ctx_setter_t& ctx_setter, const config_t& cfg,
conn_session_t& session, buf_t& send_buf);
virtual void on_disconnected(ctx_setter_t& ctx_setter,
const config_t& cfg, conn_session_t& session);
virtual uint32_t on_received(
ctx_setter_t& ctx_setter, const config_t& cfg,
conn_session_t& session,
buf_t& recv_buf, buf_t& send_buf);
virtual uint32_t get_more_data(
ctx_setter_t& ctx_setter, const config_t& cfg,
conn_session_t& session, buf_t& send_buf);
virtual uint32_t on_aio_completed(
ctx_setter_t& ctx_setter, const config_t& cfg,
conn_session_t& session,
int running_count,
const std::vector<aio_t>& completed,
buf_t& send_buf);
private:
on_connected_t m_on_connected;
on_disconnected_t m_on_disconnected;
on_received_t m_on_received;
get_more_data_t m_get_more_data;
on_aio_completed_t m_on_aio_completed;
};
} // namespace c11httpd.
| 27.567568 | 112 | 0.772549 | [
"vector"
] |
76060e14259be359c1727421daec4ef466977785 | 21,381 | c | C | make_1.4/make/inputs/sdir-cov8a/glob/glob.c | m-zakeri/benchmark | f580057a19f663114a38023f720df057b543c86f | [
"MIT"
] | null | null | null | make_1.4/make/inputs/sdir-cov8a/glob/glob.c | m-zakeri/benchmark | f580057a19f663114a38023f720df057b543c86f | [
"MIT"
] | null | null | null | make_1.4/make/inputs/sdir-cov8a/glob/glob.c | m-zakeri/benchmark | f580057a19f663114a38023f720df057b543c86f | [
"MIT"
] | null | null | null | /* Copyright (C) 1991, 92, 93, 94, 95, 96 Free Software Foundation, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; see the file COPYING.LIB. If
not, write to the Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA. */
/* AIX requires this to be the first thing in the file. */
#if defined (_AIX) && !defined (__GNUC__)
#pragma alloca
#endif
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
/* Enable GNU extensions in glob.h. */
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
/* Comment out all this code if we are using the GNU C Library, and are not
actually compiling the library itself. This code is part of the GNU C
Library, but also included in many other GNU distributions. Compiling
and linking in this code is a waste when using the GNU C library
(especially if it is a shared library). Rather than having every GNU
program understand `configure --with-gnu-libc' and omit the object files,
it is simpler to just do this in the source for each such file. */
#define GLOB_INTERFACE_VERSION 1
#if !defined (_LIBC) && defined (__GNU_LIBRARY__) && __GNU_LIBRARY__ > 1
#include <gnu-versions.h>
#if _GNU_GLOB_INTERFACE_VERSION == GLOB_INTERFACE_VERSION
#define ELIDE_CODE
#endif
#endif
#ifndef ELIDE_CODE
#ifdef STDC_HEADERS
#include <stddef.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#ifndef POSIX
#ifdef _POSIX_VERSION
#define POSIX
#endif
#endif
#endif
#if !defined (_AMIGA) && !defined (VMS) && !defined(WIN32)
#include <pwd.h>
#endif
#if !defined(__GNU_LIBRARY__) && !defined(STDC_HEADERS)
extern int errno;
#endif
#ifndef NULL
#define NULL 0
#endif
#if defined (HAVE_DIRENT_H) || defined (__GNU_LIBRARY__)
# include <dirent.h>
# define NAMLEN(dirent) strlen((dirent)->d_name)
#else
# define dirent direct
# define NAMLEN(dirent) (dirent)->d_namlen
# ifdef HAVE_SYS_NDIR_H
# include <sys/ndir.h>
# endif
# ifdef HAVE_SYS_DIR_H
# include <sys/dir.h>
# endif
# ifdef HAVE_NDIR_H
# include <ndir.h>
# endif
# ifdef HAVE_VMSDIR_H
# include "vmsdir.h"
# endif /* HAVE_VMSDIR_H */
#endif
/* In GNU systems, <dirent.h> defines this macro for us. */
#ifdef _D_NAMLEN
#undef NAMLEN
#define NAMLEN(d) _D_NAMLEN(d)
#endif
#if (defined (POSIX) || defined (WIN32)) && !defined (__GNU_LIBRARY__)
/* Posix does not require that the d_ino field be present, and some
systems do not provide it. */
#define REAL_DIR_ENTRY(dp) 1
#else
#define REAL_DIR_ENTRY(dp) (dp->d_ino != 0)
#endif /* POSIX */
#if (defined (STDC_HEADERS) || defined (__GNU_LIBRARY__))
#include <stdlib.h>
#include <string.h>
#define ANSI_STRING
#else /* No standard headers. */
extern char *getenv ();
#ifdef HAVE_STRING_H
#include <string.h>
#define ANSI_STRING
#else
#include <strings.h>
#endif
#ifdef HAVE_MEMORY_H
#include <memory.h>
#endif
extern char *malloc (), *realloc ();
extern void free ();
extern void qsort ();
extern void abort (), exit ();
#endif /* Standard headers. */
#ifndef ANSI_STRING
#ifndef bzero
extern void bzero ();
#endif
#ifndef bcopy
extern void bcopy ();
#endif
#define memcpy(d, s, n) bcopy ((s), (d), (n))
#define strrchr rindex
/* memset is only used for zero here, but let's be paranoid. */
#define memset(s, better_be_zero, n) \
((void) ((better_be_zero) == 0 ? (bzero((s), (n)), 0) : (abort(), 0)))
#endif /* Not ANSI_STRING. */
#ifndef HAVE_STRCOLL
#define strcoll strcmp
#endif
#ifndef __GNU_LIBRARY__
#ifdef __GNUC__
__inline
#endif
#ifndef __SASC
#ifdef WIN32
static void *
#else
static char *
#endif
my_realloc (p, n)
char *p;
unsigned int n;
{
/* These casts are the for sake of the broken Ultrix compiler,
which warns of illegal pointer combinations otherwise. */
if (p == NULL)
return (char *) malloc (n);
return (char *) realloc (p, n);
}
#define realloc my_realloc
#endif /* __SASC */
#endif /* __GNU_LIBRARY__ */
#if !defined(__alloca) && !defined(__GNU_LIBRARY__)
#ifdef __GNUC__
#undef alloca
#define alloca(n) __builtin_alloca (n)
#else /* Not GCC. */
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#else /* Not HAVE_ALLOCA_H. */
#ifndef _AIX
#ifdef WIN32
#include <malloc.h>
#else
extern char *alloca ();
#endif /* WIN32 */
#endif /* Not _AIX. */
#endif /* sparc or HAVE_ALLOCA_H. */
#endif /* GCC. */
#define __alloca alloca
#endif
#ifndef __GNU_LIBRARY__
#define __stat stat
#ifdef STAT_MACROS_BROKEN
#undef S_ISDIR
#endif
#ifndef S_ISDIR
#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)
#endif
#endif
#ifndef STDC_HEADERS
#undef size_t
#define size_t unsigned int
#endif
/* Some system header files erroneously define these.
We want our own definitions from <fnmatch.h> to take precedence. */
#undef FNM_PATHNAME
#undef FNM_NOESCAPE
#undef FNM_PERIOD
#include <fnmatch.h>
/* Some system header files erroneously define these.
We want our own definitions from <glob.h> to take precedence. */
#undef GLOB_ERR
#undef GLOB_MARK
#undef GLOB_NOSORT
#undef GLOB_DOOFFS
#undef GLOB_NOCHECK
#undef GLOB_APPEND
#undef GLOB_NOESCAPE
#undef GLOB_PERIOD
#include <glob.h>
static int glob_pattern_p __P ((const char *pattern, int quote));
static int glob_in_dir __P ((const char *pattern, const char *directory,
int flags,
int (*errfunc) __P ((const char *, int)),
glob_t *pglob));
static int prefix_array __P ((const char *prefix, char **array, size_t n));
static int collated_compare __P ((const __ptr_t, const __ptr_t));
/* Do glob searching for PATTERN, placing results in PGLOB.
The bits defined above may be set in FLAGS.
If a directory cannot be opened or read and ERRFUNC is not nil,
it is called with the pathname that caused the error, and the
`errno' value from the failing call; if it returns non-zero
`glob' returns GLOB_ABEND; if it returns zero, the error is ignored.
If memory cannot be allocated for PGLOB, GLOB_NOSPACE is returned.
Otherwise, `glob' returns zero. */
int
glob (pattern, flags, errfunc, pglob)
const char *pattern;
int flags;
int (*errfunc) __P ((const char *, int));
glob_t *pglob;
{
const char *filename;
char *dirname;
size_t dirlen;
int status;
int oldcount;
if (pattern == NULL || pglob == NULL || (flags & ~__GLOB_FLAGS) != 0)
{
errno = EINVAL;
return -1;
}
if (flags & GLOB_BRACE)
{
const char *begin = strchr (pattern, '{');
if (begin != NULL)
{
int firstc;
size_t restlen;
const char *p, *end, *next;
unsigned int depth = 0;
/* Find the end of the brace expression, by counting braces.
While we're at it, notice the first comma at top brace level. */
end = begin + 1;
next = NULL;
while (1)
{
switch (*end++)
{
case ',':
if (depth == 0 && next == NULL)
next = end;
continue;
case '{':
++depth;
continue;
case '}':
if (depth-- == 0)
break;
continue;
case '\0':
return glob (pattern, flags &~ GLOB_BRACE, errfunc, pglob);
}
break;
}
restlen = strlen (end) + 1;
if (next == NULL)
next = end;
/* We have a brace expression. BEGIN points to the opening {,
NEXT points past the terminator of the first element, and END
points past the final }. We will accumulate result names from
recursive runs for each brace alternative in the buffer using
GLOB_APPEND. */
if (!(flags & GLOB_APPEND))
{
/* This call is to set a new vector, so clear out the
vector so we can append to it. */
pglob->gl_pathc = 0;
pglob->gl_pathv = NULL;
}
firstc = pglob->gl_pathc;
/* In this loop P points to the beginning of the current element
and NEXT points past its terminator. */
p = begin + 1;
while (1)
{
/* Construct a whole name that is one of the brace
alternatives in a temporary buffer. */
int result;
size_t bufsz = (begin - pattern) + (next - 1 - p) + restlen;
#ifdef __GNUC__
char onealt[bufsz];
#else
char *onealt = malloc (bufsz);
if (onealt == NULL)
{
if (!(flags & GLOB_APPEND))
globfree (pglob);
return GLOB_NOSPACE;
}
#endif
memcpy (onealt, pattern, begin - pattern);
memcpy (&onealt[begin - pattern], p, next - 1 - p);
memcpy (&onealt[(begin - pattern) + (next - 1 - p)],
end, restlen);
result = glob (onealt,
((flags & ~(GLOB_NOCHECK|GLOB_NOMAGIC)) |
GLOB_APPEND), errfunc, pglob);
#ifndef __GNUC__
free (onealt);
#endif
/* If we got an error, return it. */
if (result && result != GLOB_NOMATCH)
{
if (!(flags & GLOB_APPEND))
globfree (pglob);
return result;
}
/* Advance past this alternative and process the next. */
p = next;
depth = 0;
scan:
switch (*p++)
{
case ',':
if (depth == 0)
{
/* Found the next alternative. Loop to glob it. */
next = p;
continue;
}
goto scan;
case '{':
++depth;
goto scan;
case '}':
if (depth-- == 0)
/* End of the brace expression. Break out of the loop. */
break;
goto scan;
}
}
if (pglob->gl_pathc == firstc &&
!(flags & (GLOB_NOCHECK|GLOB_NOMAGIC)))
return GLOB_NOMATCH;
}
}
/* Find the filename. */
filename = strrchr (pattern, '/');
if (filename == NULL)
{
filename = pattern;
#ifdef _AMIGA
dirname = (char *) "";
#else
dirname = (char *) ".";
#endif
dirlen = 0;
}
else if (filename == pattern)
{
/* "/pattern". */
dirname = (char *) "/";
dirlen = 1;
++filename;
}
else
{
dirlen = filename - pattern;
dirname = (char *) __alloca (dirlen + 1);
memcpy (dirname, pattern, dirlen);
dirname[dirlen] = '\0';
++filename;
}
if (filename[0] == '\0' && dirlen > 1)
/* "pattern/". Expand "pattern", appending slashes. */
{
int val = glob (dirname, flags | GLOB_MARK, errfunc, pglob);
if (val == 0)
pglob->gl_flags = (pglob->gl_flags & ~GLOB_MARK) | (flags & GLOB_MARK);
return val;
}
if (!(flags & GLOB_APPEND))
{
pglob->gl_pathc = 0;
pglob->gl_pathv = NULL;
}
oldcount = pglob->gl_pathc;
#ifndef VMS
if ((flags & GLOB_TILDE) && dirname[0] == '~')
{
if (dirname[1] == '\0')
{
/* Look up home directory. */
dirname = getenv ("HOME");
#ifdef _AMIGA
if (dirname == NULL || dirname[0] == '\0')
dirname = "SYS:";
#else
#ifdef WIN32
if (dirname == NULL || dirname[0] == '\0')
dirname = "c:/users/default"; /* poor default */
#else
if (dirname == NULL || dirname[0] == '\0')
{
extern char *getlogin __P ((void));
char *name = getlogin ();
if (name != NULL)
{
struct passwd *p = getpwnam (name);
if (p != NULL)
dirname = p->pw_dir;
}
}
if (dirname == NULL || dirname[0] == '\0')
dirname = (char *) "~"; /* No luck. */
#endif /* WIN32 */
#endif
}
else
{
#ifdef _AMIGA
if (dirname == NULL || dirname[0] == '\0')
dirname = "SYS:";
#else
#ifdef WIN32
if (dirname == NULL || dirname[0] == '\0')
dirname = "c:/users/default"; /* poor default */
#else
/* Look up specific user's home directory. */
struct passwd *p = getpwnam (dirname + 1);
if (p != NULL)
dirname = p->pw_dir;
#endif /* WIN32 */
#endif
}
}
#endif /* Not VMS. */
if (glob_pattern_p (dirname, !(flags & GLOB_NOESCAPE)))
{
/* The directory name contains metacharacters, so we
have to glob for the directory, and then glob for
the pattern in each directory found. */
glob_t dirs;
register int i;
status = glob (dirname,
((flags & (GLOB_ERR | GLOB_NOCHECK | GLOB_NOESCAPE)) |
GLOB_NOSORT),
errfunc, &dirs);
if (status != 0)
return status;
/* We have successfully globbed the preceding directory name.
For each name we found, call glob_in_dir on it and FILENAME,
appending the results to PGLOB. */
for (i = 0; i < dirs.gl_pathc; ++i)
{
int oldcount;
#ifdef SHELL
{
/* Make globbing interruptible in the bash shell. */
extern int interrupt_state;
if (interrupt_state)
{
globfree (&dirs);
globfree (&files);
return GLOB_ABEND;
}
}
#endif /* SHELL. */
oldcount = pglob->gl_pathc;
status = glob_in_dir (filename, dirs.gl_pathv[i],
(flags | GLOB_APPEND) & ~GLOB_NOCHECK,
errfunc, pglob);
if (status == GLOB_NOMATCH)
/* No matches in this directory. Try the next. */
continue;
if (status != 0)
{
globfree (&dirs);
globfree (pglob);
return status;
}
/* Stick the directory on the front of each name. */
if (prefix_array (dirs.gl_pathv[i],
&pglob->gl_pathv[oldcount],
pglob->gl_pathc - oldcount))
{
globfree (&dirs);
globfree (pglob);
return GLOB_NOSPACE;
}
}
flags |= GLOB_MAGCHAR;
if (pglob->gl_pathc == oldcount)
/* No matches. */
if (flags & GLOB_NOCHECK)
{
size_t len = strlen (pattern) + 1;
char *patcopy = (char *) malloc (len);
if (patcopy == NULL)
return GLOB_NOSPACE;
memcpy (patcopy, pattern, len);
pglob->gl_pathv
= (char **) realloc (pglob->gl_pathv,
(pglob->gl_pathc +
((flags & GLOB_DOOFFS) ?
pglob->gl_offs : 0) +
1 + 1) *
sizeof (char *));
if (pglob->gl_pathv == NULL)
{
free (patcopy);
return GLOB_NOSPACE;
}
if (flags & GLOB_DOOFFS)
while (pglob->gl_pathc < pglob->gl_offs)
pglob->gl_pathv[pglob->gl_pathc++] = NULL;
pglob->gl_pathv[pglob->gl_pathc++] = patcopy;
pglob->gl_pathv[pglob->gl_pathc] = NULL;
pglob->gl_flags = flags;
}
else
return GLOB_NOMATCH;
}
else
{
status = glob_in_dir (filename, dirname, flags, errfunc, pglob);
if (status != 0)
return status;
if (dirlen > 0)
{
/* Stick the directory on the front of each name. */
if (prefix_array (dirname,
&pglob->gl_pathv[oldcount],
pglob->gl_pathc - oldcount))
{
globfree (pglob);
return GLOB_NOSPACE;
}
}
}
if (flags & GLOB_MARK)
{
/* Append slashes to directory names. */
int i;
struct stat st;
for (i = oldcount; i < pglob->gl_pathc; ++i)
if (((flags & GLOB_ALTDIRFUNC) ?
(*pglob->gl_stat) (pglob->gl_pathv[i], &st) :
__stat (pglob->gl_pathv[i], &st)) == 0 &&
S_ISDIR (st.st_mode))
{
size_t len = strlen (pglob->gl_pathv[i]) + 2;
char *new = realloc (pglob->gl_pathv[i], len);
if (new == NULL)
{
globfree (pglob);
return GLOB_NOSPACE;
}
strcpy (&new[len - 2], "/");
pglob->gl_pathv[i] = new;
}
}
if (!(flags & GLOB_NOSORT))
/* Sort the vector. */
qsort ((__ptr_t) &pglob->gl_pathv[oldcount],
pglob->gl_pathc - oldcount,
sizeof (char *), collated_compare);
return 0;
}
/* Free storage allocated in PGLOB by a previous `glob' call. */
void
globfree (pglob)
register glob_t *pglob;
{
if (pglob->gl_pathv != NULL)
{
register int i;
for (i = 0; i < pglob->gl_pathc; ++i)
if (pglob->gl_pathv[i] != NULL)
free ((__ptr_t) pglob->gl_pathv[i]);
free ((__ptr_t) pglob->gl_pathv);
}
}
/* Do a collated comparison of A and B. */
static int
collated_compare (a, b)
const __ptr_t a;
const __ptr_t b;
{
const char *const s1 = *(const char *const * const) a;
const char *const s2 = *(const char *const * const) b;
if (s1 == s2)
return 0;
if (s1 == NULL)
return 1;
if (s2 == NULL)
return -1;
return strcoll (s1, s2);
}
/* Prepend DIRNAME to each of N members of ARRAY, replacing ARRAY's
elements in place. Return nonzero if out of memory, zero if successful.
A slash is inserted between DIRNAME and each elt of ARRAY,
unless DIRNAME is just "/". Each old element of ARRAY is freed. */
static int
prefix_array (dirname, array, n)
const char *dirname;
char **array;
size_t n;
{
register size_t i;
size_t dirlen = strlen (dirname);
if (dirlen == 1 && dirname[0] == '/')
/* DIRNAME is just "/", so normal prepending would get us "//foo".
We want "/foo" instead, so don't prepend any chars from DIRNAME. */
dirlen = 0;
for (i = 0; i < n; ++i)
{
size_t eltlen = strlen (array[i]) + 1;
char *new = (char *) malloc (dirlen + 1 + eltlen);
if (new == NULL)
{
while (i > 0)
free ((__ptr_t) array[--i]);
return 1;
}
memcpy (new, dirname, dirlen);
new[dirlen] = '/';
memcpy (&new[dirlen + 1], array[i], eltlen);
free ((__ptr_t) array[i]);
array[i] = new;
}
return 0;
}
/* Return nonzero if PATTERN contains any metacharacters.
Metacharacters can be quoted with backslashes if QUOTE is nonzero. */
static int
glob_pattern_p (pattern, quote)
const char *pattern;
int quote;
{
register const char *p;
int open = 0;
for (p = pattern; *p != '\0'; ++p)
switch (*p)
{
case '?':
case '*':
return 1;
case '\\':
if (quote && p[1] != '\0')
++p;
break;
case '[':
open = 1;
break;
case ']':
if (open)
return 1;
break;
}
return 0;
}
/* Like `glob', but PATTERN is a final pathname component,
and matches are searched for in DIRECTORY.
The GLOB_NOSORT bit in FLAGS is ignored. No sorting is ever done.
The GLOB_APPEND flag is assumed to be set (always appends). */
static int
glob_in_dir (pattern, directory, flags, errfunc, pglob)
const char *pattern;
const char *directory;
int flags;
int (*errfunc) __P ((const char *, int));
glob_t *pglob;
{
__ptr_t stream;
struct globlink
{
struct globlink *next;
char *name;
};
struct globlink *names = NULL;
size_t nfound = 0;
if (!glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE)))
{
stream = NULL;
flags |= GLOB_NOCHECK;
}
else
{
flags |= GLOB_MAGCHAR;
stream = ((flags & GLOB_ALTDIRFUNC) ?
(*pglob->gl_opendir) (directory) :
(__ptr_t) opendir (directory));
if (stream == NULL)
{
if ((errfunc != NULL && (*errfunc) (directory, errno)) ||
(flags & GLOB_ERR))
return GLOB_ABEND;
}
else
while (1)
{
const char *name;
size_t len;
struct dirent *d = ((flags & GLOB_ALTDIRFUNC) ?
(*pglob->gl_readdir) (stream) :
readdir ((DIR *) stream));
if (d == NULL)
break;
if (! REAL_DIR_ENTRY (d))
continue;
name = d->d_name;
if (fnmatch (pattern, name,
(!(flags & GLOB_PERIOD) ? FNM_PERIOD : 0) |
((flags & GLOB_NOESCAPE) ? FNM_NOESCAPE : 0)
#ifdef _AMIGA
| FNM_CASEFOLD
#endif
) == 0)
{
struct globlink *new
= (struct globlink *) __alloca (sizeof (struct globlink));
len = NAMLEN (d);
new->name
= (char *) malloc (len + 1);
if (new->name == NULL)
goto memory_error;
memcpy ((__ptr_t) new->name, name, len);
new->name[len] = '\0';
new->next = names;
names = new;
++nfound;
}
}
}
if (nfound == 0 && (flags & GLOB_NOMAGIC) &&
! glob_pattern_p (pattern, !(flags & GLOB_NOESCAPE)))
flags |= GLOB_NOCHECK;
if (nfound == 0 && (flags & GLOB_NOCHECK))
{
size_t len = strlen (pattern);
nfound = 1;
names = (struct globlink *) __alloca (sizeof (struct globlink));
names->next = NULL;
names->name = (char *) malloc (len + 1);
if (names->name == NULL)
goto memory_error;
memcpy (names->name, pattern, len);
names->name[len] = '\0';
}
pglob->gl_pathv
= (char **) realloc (pglob->gl_pathv,
(pglob->gl_pathc +
((flags & GLOB_DOOFFS) ? pglob->gl_offs : 0) +
nfound + 1) *
sizeof (char *));
if (pglob->gl_pathv == NULL)
goto memory_error;
if (flags & GLOB_DOOFFS)
while (pglob->gl_pathc < pglob->gl_offs)
pglob->gl_pathv[pglob->gl_pathc++] = NULL;
for (; names != NULL; names = names->next)
pglob->gl_pathv[pglob->gl_pathc++] = names->name;
pglob->gl_pathv[pglob->gl_pathc] = NULL;
pglob->gl_flags = flags;
if (stream != NULL)
{
int save = errno;
if (flags & GLOB_ALTDIRFUNC)
(*pglob->gl_closedir) (stream);
else
closedir ((DIR *) stream);
errno = save;
}
return nfound == 0 ? GLOB_NOMATCH : 0;
memory_error:
{
int save = errno;
if (flags & GLOB_ALTDIRFUNC)
(*pglob->gl_closedir) (stream);
else
closedir ((DIR *) stream);
errno = save;
}
while (names != NULL)
{
if (names->name != NULL)
free ((__ptr_t) names->name);
names = names->next;
}
return GLOB_NOSPACE;
}
#endif /* Not ELIDE_CODE. */
| 23.573319 | 76 | 0.608578 | [
"object",
"vector"
] |
7614ad32639cdafe649da9581d9fe380bfe745e0 | 3,239 | h | C | analysis/semantic/input-generation/generators/egret/src/Path.h | SBULeeLab/LinguaFranca-FSE19 | a75bd51713d14aa9b48c32e103a3da500854f518 | [
"MIT"
] | 2 | 2021-08-03T12:15:39.000Z | 2021-09-27T22:03:36.000Z | analysis/semantic/input-generation/generators/egret/src/Path.h | SBULeeLab/LinguaFranca-FSE19 | a75bd51713d14aa9b48c32e103a3da500854f518 | [
"MIT"
] | null | null | null | analysis/semantic/input-generation/generators/egret/src/Path.h | SBULeeLab/LinguaFranca-FSE19 | a75bd51713d14aa9b48c32e103a3da500854f518 | [
"MIT"
] | 2 | 2020-10-15T16:48:20.000Z | 2020-12-30T12:57:45.000Z | /* Path.h: Represents a path through the NFA
Copyright (C) 2016-2018 Eric Larson and Anna Kirk
elarson@seattleu.edu
This file is part of EGRET.
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PATH_H
#define PATH_H
#include <set>
#include <string>
#include <vector>
#include "Edge.h"
using namespace std;
class Path {
public:
Path() {}
Path(unsigned int initial) { states.push_back(initial); }
string get_test_string() { return test_string; }
// PATH CONSTRUCTION FUNCTIONS
// adds an edge and the destination state to the path
void append(Edge *edge, unsigned int state);
// removes the last edge and state
void remove_last();
// marks the states in the path as visited
void mark_path_visited(bool *visited);
// processes path: sets test string and evil edges
void process_path();
// CHECKER FUNCTIONS
// returns true if path has a leading caret
bool has_leading_caret();
// returns true if path has a trailing dollar
bool has_trailing_dollar();
// returns true and emits violation if there is an anchor (^ or $) in the
// middle of the path
bool check_anchor_in_middle();
// emits violation if a path contains a charset error
void check_charsets();
// emits violation if a path contains optional braces
void check_optional_braces();
// emits violation if wildcard is just before/after punctuation mark
void check_wild_punctuation();
// emits violation if punctuation can be repeated in certain situations
void check_repeat_punctuation();
// emits violation if digits are too optional
void check_digit_too_optional();
// STRING GENERATION FUNCTIONS
// generates example string
string gen_example_string(Location loc, char c);
string gen_example_string(Location loc, char c, char except);
string gen_example_string(Location loc, char c, Location omit);
string gen_example_string(Location loc1, char c1, Location loc2, char c2);
string gen_example_string(Location loc, string replace);
// generates string based on location
string gen_backref_string(Location loc);
// generates a string with minimum iterations for repeating constructs
string gen_min_iter_string();
// generates evil strings for the path
vector <string> gen_evil_strings(const set <char> &punct_marks);
// PRINT FUNCTION
// prints the path
void print();
private:
vector <unsigned int> states; // list of states
vector <Edge *> edges; // list of edges
string test_string; // test string associated with path
vector <unsigned int> evil_edges; // list of evil edges that need processing
};
#endif // PATH_H
| 28.663717 | 78 | 0.733251 | [
"vector"
] |
761a7abc0409ee5b574eed4fd6898b0eafefd681 | 144,226 | h | C | Include/10.0.17134.0/cppwinrt/winrt/Windows.ApplicationModel.DataTransfer.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | 5 | 2020-05-29T06:22:17.000Z | 2021-11-28T08:21:38.000Z | Include/10.0.17134.0/cppwinrt/winrt/Windows.ApplicationModel.DataTransfer.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | null | null | null | Include/10.0.17134.0/cppwinrt/winrt/Windows.ApplicationModel.DataTransfer.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | 5 | 2020-05-30T04:15:11.000Z | 2021-11-28T08:48:56.000Z | // C++/WinRT v1.0.180227.3
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "winrt/base.h"
WINRT_WARNING_PUSH
#include "winrt/Windows.Foundation.h"
#include "winrt/Windows.Foundation.Collections.h"
#include "winrt/impl/Windows.Foundation.2.h"
#include "winrt/impl/Windows.Security.EnterpriseData.2.h"
#include "winrt/impl/Windows.Storage.2.h"
#include "winrt/impl/Windows.Storage.Streams.2.h"
#include "winrt/impl/Windows.UI.2.h"
#include "winrt/impl/Windows.Foundation.Collections.2.h"
#include "winrt/impl/Windows.ApplicationModel.DataTransfer.2.h"
#include "winrt/Windows.ApplicationModel.h"
namespace winrt::impl {
template <typename D> Windows::ApplicationModel::DataTransfer::DataPackageView consume_Windows_ApplicationModel_DataTransfer_IClipboardStatics<D>::GetContent() const
{
Windows::ApplicationModel::DataTransfer::DataPackageView content{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IClipboardStatics)->GetContent(put_abi(content)));
return content;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IClipboardStatics<D>::SetContent(Windows::ApplicationModel::DataTransfer::DataPackage const& content) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IClipboardStatics)->SetContent(get_abi(content)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IClipboardStatics<D>::Flush() const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IClipboardStatics)->Flush());
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IClipboardStatics<D>::Clear() const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IClipboardStatics)->Clear());
}
template <typename D> event_token consume_Windows_ApplicationModel_DataTransfer_IClipboardStatics<D>::ContentChanged(Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> const& changeHandler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IClipboardStatics)->add_ContentChanged(get_abi(changeHandler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::ApplicationModel::DataTransfer::IClipboardStatics> consume_Windows_ApplicationModel_DataTransfer_IClipboardStatics<D>::ContentChanged(auto_revoke_t, Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> const& changeHandler) const
{
return impl::make_event_revoker<D, Windows::ApplicationModel::DataTransfer::IClipboardStatics>(this, &abi_t<Windows::ApplicationModel::DataTransfer::IClipboardStatics>::remove_ContentChanged, ContentChanged(changeHandler));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IClipboardStatics<D>::ContentChanged(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IClipboardStatics)->remove_ContentChanged(get_abi(token)));
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataPackageView consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::GetView() const
{
Windows::ApplicationModel::DataTransfer::DataPackageView value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->GetView(put_abi(value)));
return value;
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataPackagePropertySet consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::Properties() const
{
Windows::ApplicationModel::DataTransfer::DataPackagePropertySet value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->get_Properties(put_abi(value)));
return value;
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataPackageOperation consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::RequestedOperation() const
{
Windows::ApplicationModel::DataTransfer::DataPackageOperation value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->get_RequestedOperation(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::RequestedOperation(Windows::ApplicationModel::DataTransfer::DataPackageOperation const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->put_RequestedOperation(get_abi(value)));
}
template <typename D> event_token consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::OperationCompleted(Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataPackage, Windows::ApplicationModel::DataTransfer::OperationCompletedEventArgs> const& handler) const
{
event_token eventCookie{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->add_OperationCompleted(get_abi(handler), put_abi(eventCookie)));
return eventCookie;
}
template <typename D> event_revoker<Windows::ApplicationModel::DataTransfer::IDataPackage> consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::OperationCompleted(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataPackage, Windows::ApplicationModel::DataTransfer::OperationCompletedEventArgs> const& handler) const
{
return impl::make_event_revoker<D, Windows::ApplicationModel::DataTransfer::IDataPackage>(this, &abi_t<Windows::ApplicationModel::DataTransfer::IDataPackage>::remove_OperationCompleted, OperationCompleted(handler));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::OperationCompleted(event_token const& eventCookie) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->remove_OperationCompleted(get_abi(eventCookie)));
}
template <typename D> event_token consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::Destroyed(Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataPackage, Windows::Foundation::IInspectable> const& handler) const
{
event_token eventCookie{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->add_Destroyed(get_abi(handler), put_abi(eventCookie)));
return eventCookie;
}
template <typename D> event_revoker<Windows::ApplicationModel::DataTransfer::IDataPackage> consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::Destroyed(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataPackage, Windows::Foundation::IInspectable> const& handler) const
{
return impl::make_event_revoker<D, Windows::ApplicationModel::DataTransfer::IDataPackage>(this, &abi_t<Windows::ApplicationModel::DataTransfer::IDataPackage>::remove_Destroyed, Destroyed(handler));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::Destroyed(event_token const& eventCookie) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->remove_Destroyed(get_abi(eventCookie)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::SetData(param::hstring const& formatId, Windows::Foundation::IInspectable const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->SetData(get_abi(formatId), get_abi(value)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::SetDataProvider(param::hstring const& formatId, Windows::ApplicationModel::DataTransfer::DataProviderHandler const& delayRenderer) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->SetDataProvider(get_abi(formatId), get_abi(delayRenderer)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::SetText(param::hstring const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->SetText(get_abi(value)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::SetUri(Windows::Foundation::Uri const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->SetUri(get_abi(value)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::SetHtmlFormat(param::hstring const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->SetHtmlFormat(get_abi(value)));
}
template <typename D> Windows::Foundation::Collections::IMap<hstring, Windows::Storage::Streams::RandomAccessStreamReference> consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::ResourceMap() const
{
Windows::Foundation::Collections::IMap<hstring, Windows::Storage::Streams::RandomAccessStreamReference> value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->get_ResourceMap(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::SetRtf(param::hstring const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->SetRtf(get_abi(value)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::SetBitmap(Windows::Storage::Streams::RandomAccessStreamReference const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->SetBitmap(get_abi(value)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::SetStorageItems(param::iterable<Windows::Storage::IStorageItem> const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->SetStorageItemsReadOnly(get_abi(value)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage<D>::SetStorageItems(param::iterable<Windows::Storage::IStorageItem> const& value, bool readOnly) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage)->SetStorageItems(get_abi(value), readOnly));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage2<D>::SetApplicationLink(Windows::Foundation::Uri const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage2)->SetApplicationLink(get_abi(value)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage2<D>::SetWebLink(Windows::Foundation::Uri const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage2)->SetWebLink(get_abi(value)));
}
template <typename D> event_token consume_Windows_ApplicationModel_DataTransfer_IDataPackage3<D>::ShareCompleted(Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataPackage, Windows::ApplicationModel::DataTransfer::ShareCompletedEventArgs> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage3)->add_ShareCompleted(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::ApplicationModel::DataTransfer::IDataPackage3> consume_Windows_ApplicationModel_DataTransfer_IDataPackage3<D>::ShareCompleted(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataPackage, Windows::ApplicationModel::DataTransfer::ShareCompletedEventArgs> const& handler) const
{
return impl::make_event_revoker<D, Windows::ApplicationModel::DataTransfer::IDataPackage3>(this, &abi_t<Windows::ApplicationModel::DataTransfer::IDataPackage3>::remove_ShareCompleted, ShareCompleted(handler));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackage3<D>::ShareCompleted(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackage3)->remove_ShareCompleted(get_abi(token)));
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::Title() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->get_Title(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::Title(param::hstring const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->put_Title(get_abi(value)));
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::Description() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->get_Description(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::Description(param::hstring const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->put_Description(get_abi(value)));
}
template <typename D> Windows::Storage::Streams::IRandomAccessStreamReference consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::Thumbnail() const
{
Windows::Storage::Streams::IRandomAccessStreamReference value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->get_Thumbnail(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::Thumbnail(Windows::Storage::Streams::IRandomAccessStreamReference const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->put_Thumbnail(get_abi(value)));
}
template <typename D> Windows::Foundation::Collections::IVector<hstring> consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::FileTypes() const
{
Windows::Foundation::Collections::IVector<hstring> value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->get_FileTypes(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::ApplicationName() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->get_ApplicationName(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::ApplicationName(param::hstring const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->put_ApplicationName(get_abi(value)));
}
template <typename D> Windows::Foundation::Uri consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::ApplicationListingUri() const
{
Windows::Foundation::Uri value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->get_ApplicationListingUri(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet<D>::ApplicationListingUri(Windows::Foundation::Uri const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet)->put_ApplicationListingUri(get_abi(value)));
}
template <typename D> Windows::Foundation::Uri consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet2<D>::ContentSourceWebLink() const
{
Windows::Foundation::Uri value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2)->get_ContentSourceWebLink(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet2<D>::ContentSourceWebLink(Windows::Foundation::Uri const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2)->put_ContentSourceWebLink(get_abi(value)));
}
template <typename D> Windows::Foundation::Uri consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet2<D>::ContentSourceApplicationLink() const
{
Windows::Foundation::Uri value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2)->get_ContentSourceApplicationLink(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet2<D>::ContentSourceApplicationLink(Windows::Foundation::Uri const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2)->put_ContentSourceApplicationLink(get_abi(value)));
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet2<D>::PackageFamilyName() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2)->get_PackageFamilyName(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet2<D>::PackageFamilyName(param::hstring const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2)->put_PackageFamilyName(get_abi(value)));
}
template <typename D> Windows::Storage::Streams::IRandomAccessStreamReference consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet2<D>::Square30x30Logo() const
{
Windows::Storage::Streams::IRandomAccessStreamReference value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2)->get_Square30x30Logo(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet2<D>::Square30x30Logo(Windows::Storage::Streams::IRandomAccessStreamReference const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2)->put_Square30x30Logo(get_abi(value)));
}
template <typename D> Windows::UI::Color consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet2<D>::LogoBackgroundColor() const
{
Windows::UI::Color value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2)->get_LogoBackgroundColor(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet2<D>::LogoBackgroundColor(Windows::UI::Color const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2)->put_LogoBackgroundColor(get_abi(value)));
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet3<D>::EnterpriseId() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet3)->get_EnterpriseId(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet3<D>::EnterpriseId(param::hstring const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet3)->put_EnterpriseId(get_abi(value)));
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet4<D>::ContentSourceUserActivityJson() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet4)->get_ContentSourceUserActivityJson(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySet4<D>::ContentSourceUserActivityJson(param::hstring const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet4)->put_ContentSourceUserActivityJson(get_abi(value)));
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView<D>::Title() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView)->get_Title(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView<D>::Description() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView)->get_Description(put_abi(value)));
return value;
}
template <typename D> Windows::Storage::Streams::RandomAccessStreamReference consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView<D>::Thumbnail() const
{
Windows::Storage::Streams::RandomAccessStreamReference value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView)->get_Thumbnail(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Collections::IVectorView<hstring> consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView<D>::FileTypes() const
{
Windows::Foundation::Collections::IVectorView<hstring> value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView)->get_FileTypes(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView<D>::ApplicationName() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView)->get_ApplicationName(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Uri consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView<D>::ApplicationListingUri() const
{
Windows::Foundation::Uri value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView)->get_ApplicationListingUri(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView2<D>::PackageFamilyName() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView2)->get_PackageFamilyName(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Uri consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView2<D>::ContentSourceWebLink() const
{
Windows::Foundation::Uri value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView2)->get_ContentSourceWebLink(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Uri consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView2<D>::ContentSourceApplicationLink() const
{
Windows::Foundation::Uri value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView2)->get_ContentSourceApplicationLink(put_abi(value)));
return value;
}
template <typename D> Windows::Storage::Streams::IRandomAccessStreamReference consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView2<D>::Square30x30Logo() const
{
Windows::Storage::Streams::IRandomAccessStreamReference value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView2)->get_Square30x30Logo(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Color consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView2<D>::LogoBackgroundColor() const
{
Windows::UI::Color value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView2)->get_LogoBackgroundColor(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView3<D>::EnterpriseId() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView3)->get_EnterpriseId(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataPackagePropertySetView4<D>::ContentSourceUserActivityJson() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView4)->get_ContentSourceUserActivityJson(put_abi(value)));
return value;
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataPackagePropertySetView consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::Properties() const
{
Windows::ApplicationModel::DataTransfer::DataPackagePropertySetView value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->get_Properties(put_abi(value)));
return value;
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataPackageOperation consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::RequestedOperation() const
{
Windows::ApplicationModel::DataTransfer::DataPackageOperation value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->get_RequestedOperation(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::ReportOperationCompleted(Windows::ApplicationModel::DataTransfer::DataPackageOperation const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->ReportOperationCompleted(get_abi(value)));
}
template <typename D> Windows::Foundation::Collections::IVectorView<hstring> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::AvailableFormats() const
{
Windows::Foundation::Collections::IVectorView<hstring> formatIds{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->get_AvailableFormats(put_abi(formatIds)));
return formatIds;
}
template <typename D> bool consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::Contains(param::hstring const& formatId) const
{
bool value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->Contains(get_abi(formatId), &value));
return value;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::IInspectable> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::GetDataAsync(param::hstring const& formatId) const
{
Windows::Foundation::IAsyncOperation<Windows::Foundation::IInspectable> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->GetDataAsync(get_abi(formatId), put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<hstring> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::GetTextAsync() const
{
Windows::Foundation::IAsyncOperation<hstring> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->GetTextAsync(put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<hstring> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::GetTextAsync(param::hstring const& formatId) const
{
Windows::Foundation::IAsyncOperation<hstring> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->GetCustomTextAsync(get_abi(formatId), put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Uri> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::GetUriAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Foundation::Uri> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->GetUriAsync(put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<hstring> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::GetHtmlFormatAsync() const
{
Windows::Foundation::IAsyncOperation<hstring> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->GetHtmlFormatAsync(put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IMapView<hstring, Windows::Storage::Streams::RandomAccessStreamReference>> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::GetResourceMapAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IMapView<hstring, Windows::Storage::Streams::RandomAccessStreamReference>> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->GetResourceMapAsync(put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<hstring> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::GetRtfAsync() const
{
Windows::Foundation::IAsyncOperation<hstring> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->GetRtfAsync(put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::RandomAccessStreamReference> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::GetBitmapAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::RandomAccessStreamReference> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->GetBitmapAsync(put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::IStorageItem>> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView<D>::GetStorageItemsAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::IStorageItem>> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView)->GetStorageItemsAsync(put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Uri> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView2<D>::GetApplicationLinkAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Foundation::Uri> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView2)->GetApplicationLinkAsync(put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Foundation::Uri> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView2<D>::GetWebLinkAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Foundation::Uri> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView2)->GetWebLinkAsync(put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView3<D>::RequestAccessAsync() const
{
Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView3)->RequestAccessAsync(put_abi(operation)));
return operation;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> consume_Windows_ApplicationModel_DataTransfer_IDataPackageView3<D>::RequestAccessAsync(param::hstring const& enterpriseId) const
{
Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView3)->RequestAccessWithEnterpriseIdAsync(get_abi(enterpriseId), put_abi(operation)));
return operation;
}
template <typename D> Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult consume_Windows_ApplicationModel_DataTransfer_IDataPackageView3<D>::UnlockAndAssumeEnterpriseIdentity() const
{
Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult result{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView3)->UnlockAndAssumeEnterpriseIdentity(put_abi(result)));
return result;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataPackageView4<D>::SetAcceptedFormatId(param::hstring const& formatId) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataPackageView4)->SetAcceptedFormatId(get_abi(formatId)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataProviderDeferral<D>::Complete() const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataProviderDeferral)->Complete());
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IDataProviderRequest<D>::FormatId() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataProviderRequest)->get_FormatId(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::DateTime consume_Windows_ApplicationModel_DataTransfer_IDataProviderRequest<D>::Deadline() const
{
Windows::Foundation::DateTime value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataProviderRequest)->get_Deadline(put_abi(value)));
return value;
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataProviderDeferral consume_Windows_ApplicationModel_DataTransfer_IDataProviderRequest<D>::GetDeferral() const
{
Windows::ApplicationModel::DataTransfer::DataProviderDeferral value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataProviderRequest)->GetDeferral(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataProviderRequest<D>::SetData(Windows::Foundation::IInspectable const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataProviderRequest)->SetData(get_abi(value)));
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataPackage consume_Windows_ApplicationModel_DataTransfer_IDataRequest<D>::Data() const
{
Windows::ApplicationModel::DataTransfer::DataPackage value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataRequest)->get_Data(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataRequest<D>::Data(Windows::ApplicationModel::DataTransfer::DataPackage const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataRequest)->put_Data(get_abi(value)));
}
template <typename D> Windows::Foundation::DateTime consume_Windows_ApplicationModel_DataTransfer_IDataRequest<D>::Deadline() const
{
Windows::Foundation::DateTime value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataRequest)->get_Deadline(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataRequest<D>::FailWithDisplayText(param::hstring const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataRequest)->FailWithDisplayText(get_abi(value)));
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataRequestDeferral consume_Windows_ApplicationModel_DataTransfer_IDataRequest<D>::GetDeferral() const
{
Windows::ApplicationModel::DataTransfer::DataRequestDeferral value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataRequest)->GetDeferral(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataRequestDeferral<D>::Complete() const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataRequestDeferral)->Complete());
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataRequest consume_Windows_ApplicationModel_DataTransfer_IDataRequestedEventArgs<D>::Request() const
{
Windows::ApplicationModel::DataTransfer::DataRequest value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs)->get_Request(put_abi(value)));
return value;
}
template <typename D> event_token consume_Windows_ApplicationModel_DataTransfer_IDataTransferManager<D>::DataRequested(Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager, Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs> const& eventHandler) const
{
event_token eventCookie{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataTransferManager)->add_DataRequested(get_abi(eventHandler), put_abi(eventCookie)));
return eventCookie;
}
template <typename D> event_revoker<Windows::ApplicationModel::DataTransfer::IDataTransferManager> consume_Windows_ApplicationModel_DataTransfer_IDataTransferManager<D>::DataRequested(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager, Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs> const& eventHandler) const
{
return impl::make_event_revoker<D, Windows::ApplicationModel::DataTransfer::IDataTransferManager>(this, &abi_t<Windows::ApplicationModel::DataTransfer::IDataTransferManager>::remove_DataRequested, DataRequested(eventHandler));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataTransferManager<D>::DataRequested(event_token const& eventCookie) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataTransferManager)->remove_DataRequested(get_abi(eventCookie)));
}
template <typename D> event_token consume_Windows_ApplicationModel_DataTransfer_IDataTransferManager<D>::TargetApplicationChosen(Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager, Windows::ApplicationModel::DataTransfer::TargetApplicationChosenEventArgs> const& eventHandler) const
{
event_token eventCookie{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataTransferManager)->add_TargetApplicationChosen(get_abi(eventHandler), put_abi(eventCookie)));
return eventCookie;
}
template <typename D> event_revoker<Windows::ApplicationModel::DataTransfer::IDataTransferManager> consume_Windows_ApplicationModel_DataTransfer_IDataTransferManager<D>::TargetApplicationChosen(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager, Windows::ApplicationModel::DataTransfer::TargetApplicationChosenEventArgs> const& eventHandler) const
{
return impl::make_event_revoker<D, Windows::ApplicationModel::DataTransfer::IDataTransferManager>(this, &abi_t<Windows::ApplicationModel::DataTransfer::IDataTransferManager>::remove_TargetApplicationChosen, TargetApplicationChosen(eventHandler));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataTransferManager<D>::TargetApplicationChosen(event_token const& eventCookie) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataTransferManager)->remove_TargetApplicationChosen(get_abi(eventCookie)));
}
template <typename D> event_token consume_Windows_ApplicationModel_DataTransfer_IDataTransferManager2<D>::ShareProvidersRequested(Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager, Windows::ApplicationModel::DataTransfer::ShareProvidersRequestedEventArgs> const& handler) const
{
event_token token{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataTransferManager2)->add_ShareProvidersRequested(get_abi(handler), put_abi(token)));
return token;
}
template <typename D> event_revoker<Windows::ApplicationModel::DataTransfer::IDataTransferManager2> consume_Windows_ApplicationModel_DataTransfer_IDataTransferManager2<D>::ShareProvidersRequested(auto_revoke_t, Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager, Windows::ApplicationModel::DataTransfer::ShareProvidersRequestedEventArgs> const& handler) const
{
return impl::make_event_revoker<D, Windows::ApplicationModel::DataTransfer::IDataTransferManager2>(this, &abi_t<Windows::ApplicationModel::DataTransfer::IDataTransferManager2>::remove_ShareProvidersRequested, ShareProvidersRequested(handler));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataTransferManager2<D>::ShareProvidersRequested(event_token const& token) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataTransferManager2)->remove_ShareProvidersRequested(get_abi(token)));
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataTransferManagerStatics<D>::ShowShareUI() const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics)->ShowShareUI());
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataTransferManager consume_Windows_ApplicationModel_DataTransfer_IDataTransferManagerStatics<D>::GetForCurrentView() const
{
Windows::ApplicationModel::DataTransfer::DataTransferManager value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics)->GetForCurrentView(put_abi(value)));
return value;
}
template <typename D> bool consume_Windows_ApplicationModel_DataTransfer_IDataTransferManagerStatics2<D>::IsSupported() const
{
bool value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics2)->IsSupported(&value));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IDataTransferManagerStatics3<D>::ShowShareUI(Windows::ApplicationModel::DataTransfer::ShareUIOptions const& options) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics3)->ShowShareUIWithOptions(get_abi(options)));
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IHtmlFormatHelperStatics<D>::GetStaticFragment(param::hstring const& htmlFormat) const
{
hstring htmlFragment{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IHtmlFormatHelperStatics)->GetStaticFragment(get_abi(htmlFormat), put_abi(htmlFragment)));
return htmlFragment;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IHtmlFormatHelperStatics<D>::CreateHtmlFormat(param::hstring const& htmlFragment) const
{
hstring htmlFormat{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IHtmlFormatHelperStatics)->CreateHtmlFormat(get_abi(htmlFragment), put_abi(htmlFormat)));
return htmlFormat;
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataPackageOperation consume_Windows_ApplicationModel_DataTransfer_IOperationCompletedEventArgs<D>::Operation() const
{
Windows::ApplicationModel::DataTransfer::DataPackageOperation value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IOperationCompletedEventArgs)->get_Operation(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IOperationCompletedEventArgs2<D>::AcceptedFormatId() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IOperationCompletedEventArgs2)->get_AcceptedFormatId(put_abi(value)));
return value;
}
template <typename D> Windows::ApplicationModel::DataTransfer::ShareTargetInfo consume_Windows_ApplicationModel_DataTransfer_IShareCompletedEventArgs<D>::ShareTarget() const
{
Windows::ApplicationModel::DataTransfer::ShareTargetInfo value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareCompletedEventArgs)->get_ShareTarget(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IShareProvider<D>::Title() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProvider)->get_Title(put_abi(value)));
return value;
}
template <typename D> Windows::Storage::Streams::RandomAccessStreamReference consume_Windows_ApplicationModel_DataTransfer_IShareProvider<D>::DisplayIcon() const
{
Windows::Storage::Streams::RandomAccessStreamReference value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProvider)->get_DisplayIcon(put_abi(value)));
return value;
}
template <typename D> Windows::UI::Color consume_Windows_ApplicationModel_DataTransfer_IShareProvider<D>::BackgroundColor() const
{
Windows::UI::Color value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProvider)->get_BackgroundColor(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::IInspectable consume_Windows_ApplicationModel_DataTransfer_IShareProvider<D>::Tag() const
{
Windows::Foundation::IInspectable value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProvider)->get_Tag(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IShareProvider<D>::Tag(Windows::Foundation::IInspectable const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProvider)->put_Tag(get_abi(value)));
}
template <typename D> Windows::ApplicationModel::DataTransfer::ShareProvider consume_Windows_ApplicationModel_DataTransfer_IShareProviderFactory<D>::Create(param::hstring const& title, Windows::Storage::Streams::RandomAccessStreamReference const& displayIcon, Windows::UI::Color const& backgroundColor, Windows::ApplicationModel::DataTransfer::ShareProviderHandler const& handler) const
{
Windows::ApplicationModel::DataTransfer::ShareProvider result{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProviderFactory)->Create(get_abi(title), get_abi(displayIcon), get_abi(backgroundColor), get_abi(handler), put_abi(result)));
return result;
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataPackageView consume_Windows_ApplicationModel_DataTransfer_IShareProviderOperation<D>::Data() const
{
Windows::ApplicationModel::DataTransfer::DataPackageView value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProviderOperation)->get_Data(put_abi(value)));
return value;
}
template <typename D> Windows::ApplicationModel::DataTransfer::ShareProvider consume_Windows_ApplicationModel_DataTransfer_IShareProviderOperation<D>::Provider() const
{
Windows::ApplicationModel::DataTransfer::ShareProvider value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProviderOperation)->get_Provider(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IShareProviderOperation<D>::ReportCompleted() const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProviderOperation)->ReportCompleted());
}
template <typename D> Windows::Foundation::Collections::IVector<Windows::ApplicationModel::DataTransfer::ShareProvider> consume_Windows_ApplicationModel_DataTransfer_IShareProvidersRequestedEventArgs<D>::Providers() const
{
Windows::Foundation::Collections::IVector<Windows::ApplicationModel::DataTransfer::ShareProvider> value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProvidersRequestedEventArgs)->get_Providers(put_abi(value)));
return value;
}
template <typename D> Windows::ApplicationModel::DataTransfer::DataPackageView consume_Windows_ApplicationModel_DataTransfer_IShareProvidersRequestedEventArgs<D>::Data() const
{
Windows::ApplicationModel::DataTransfer::DataPackageView value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProvidersRequestedEventArgs)->get_Data(put_abi(value)));
return value;
}
template <typename D> Windows::Foundation::Deferral consume_Windows_ApplicationModel_DataTransfer_IShareProvidersRequestedEventArgs<D>::GetDeferral() const
{
Windows::Foundation::Deferral value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareProvidersRequestedEventArgs)->GetDeferral(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IShareTargetInfo<D>::AppUserModelId() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareTargetInfo)->get_AppUserModelId(put_abi(value)));
return value;
}
template <typename D> Windows::ApplicationModel::DataTransfer::ShareProvider consume_Windows_ApplicationModel_DataTransfer_IShareTargetInfo<D>::ShareProvider() const
{
Windows::ApplicationModel::DataTransfer::ShareProvider value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareTargetInfo)->get_ShareProvider(put_abi(value)));
return value;
}
template <typename D> Windows::ApplicationModel::DataTransfer::ShareUITheme consume_Windows_ApplicationModel_DataTransfer_IShareUIOptions<D>::Theme() const
{
Windows::ApplicationModel::DataTransfer::ShareUITheme value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareUIOptions)->get_Theme(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IShareUIOptions<D>::Theme(Windows::ApplicationModel::DataTransfer::ShareUITheme const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareUIOptions)->put_Theme(get_abi(value)));
}
template <typename D> Windows::Foundation::IReference<Windows::Foundation::Rect> consume_Windows_ApplicationModel_DataTransfer_IShareUIOptions<D>::SelectionRect() const
{
Windows::Foundation::IReference<Windows::Foundation::Rect> value{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareUIOptions)->get_SelectionRect(put_abi(value)));
return value;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_IShareUIOptions<D>::SelectionRect(optional<Windows::Foundation::Rect> const& value) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IShareUIOptions)->put_SelectionRect(get_abi(value)));
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_ISharedStorageAccessManagerStatics<D>::AddFile(Windows::Storage::IStorageFile const& file) const
{
hstring outToken{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::ISharedStorageAccessManagerStatics)->AddFile(get_abi(file), put_abi(outToken)));
return outToken;
}
template <typename D> Windows::Foundation::IAsyncOperation<Windows::Storage::StorageFile> consume_Windows_ApplicationModel_DataTransfer_ISharedStorageAccessManagerStatics<D>::RedeemTokenForFileAsync(param::hstring const& token) const
{
Windows::Foundation::IAsyncOperation<Windows::Storage::StorageFile> operation{ nullptr };
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::ISharedStorageAccessManagerStatics)->RedeemTokenForFileAsync(get_abi(token), put_abi(operation)));
return operation;
}
template <typename D> void consume_Windows_ApplicationModel_DataTransfer_ISharedStorageAccessManagerStatics<D>::RemoveFile(param::hstring const& token) const
{
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::ISharedStorageAccessManagerStatics)->RemoveFile(get_abi(token)));
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IStandardDataFormatsStatics<D>::Text() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics)->get_Text(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IStandardDataFormatsStatics<D>::Uri() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics)->get_Uri(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IStandardDataFormatsStatics<D>::Html() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics)->get_Html(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IStandardDataFormatsStatics<D>::Rtf() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics)->get_Rtf(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IStandardDataFormatsStatics<D>::Bitmap() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics)->get_Bitmap(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IStandardDataFormatsStatics<D>::StorageItems() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics)->get_StorageItems(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IStandardDataFormatsStatics2<D>::WebLink() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics2)->get_WebLink(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IStandardDataFormatsStatics2<D>::ApplicationLink() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics2)->get_ApplicationLink(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_IStandardDataFormatsStatics3<D>::UserActivityJsonArray() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics3)->get_UserActivityJsonArray(put_abi(value)));
return value;
}
template <typename D> hstring consume_Windows_ApplicationModel_DataTransfer_ITargetApplicationChosenEventArgs<D>::ApplicationName() const
{
hstring value{};
check_hresult(WINRT_SHIM(Windows::ApplicationModel::DataTransfer::ITargetApplicationChosenEventArgs)->get_ApplicationName(put_abi(value)));
return value;
}
template <> struct delegate<Windows::ApplicationModel::DataTransfer::DataProviderHandler>
{
template <typename H>
struct type : implements_delegate<Windows::ApplicationModel::DataTransfer::DataProviderHandler, H>
{
type(H&& handler) : implements_delegate<Windows::ApplicationModel::DataTransfer::DataProviderHandler, H>(std::forward<H>(handler)) {}
HRESULT __stdcall Invoke(void* request) noexcept final
{
try
{
(*this)(*reinterpret_cast<Windows::ApplicationModel::DataTransfer::DataProviderRequest const*>(&request));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
};
template <> struct delegate<Windows::ApplicationModel::DataTransfer::ShareProviderHandler>
{
template <typename H>
struct type : implements_delegate<Windows::ApplicationModel::DataTransfer::ShareProviderHandler, H>
{
type(H&& handler) : implements_delegate<Windows::ApplicationModel::DataTransfer::ShareProviderHandler, H>(std::forward<H>(handler)) {}
HRESULT __stdcall Invoke(void* operation) noexcept final
{
try
{
(*this)(*reinterpret_cast<Windows::ApplicationModel::DataTransfer::ShareProviderOperation const*>(&operation));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IClipboardStatics> : produce_base<D, Windows::ApplicationModel::DataTransfer::IClipboardStatics>
{
HRESULT __stdcall GetContent(void** content) noexcept final
{
try
{
*content = nullptr;
typename D::abi_guard guard(this->shim());
*content = detach_from<Windows::ApplicationModel::DataTransfer::DataPackageView>(this->shim().GetContent());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetContent(void* content) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetContent(*reinterpret_cast<Windows::ApplicationModel::DataTransfer::DataPackage const*>(&content));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall Flush() noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Flush();
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall Clear() noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Clear();
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_ContentChanged(void* changeHandler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().ContentChanged(*reinterpret_cast<Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> const*>(&changeHandler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_ContentChanged(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ContentChanged(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackage> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackage>
{
HRESULT __stdcall GetView(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataPackageView>(this->shim().GetView());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Properties(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataPackagePropertySet>(this->shim().Properties());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_RequestedOperation(Windows::ApplicationModel::DataTransfer::DataPackageOperation* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataPackageOperation>(this->shim().RequestedOperation());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_RequestedOperation(Windows::ApplicationModel::DataTransfer::DataPackageOperation value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RequestedOperation(*reinterpret_cast<Windows::ApplicationModel::DataTransfer::DataPackageOperation const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_OperationCompleted(void* handler, event_token* eventCookie) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*eventCookie = detach_from<event_token>(this->shim().OperationCompleted(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataPackage, Windows::ApplicationModel::DataTransfer::OperationCompletedEventArgs> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_OperationCompleted(event_token eventCookie) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().OperationCompleted(*reinterpret_cast<event_token const*>(&eventCookie));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_Destroyed(void* handler, event_token* eventCookie) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*eventCookie = detach_from<event_token>(this->shim().Destroyed(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataPackage, Windows::Foundation::IInspectable> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_Destroyed(event_token eventCookie) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Destroyed(*reinterpret_cast<event_token const*>(&eventCookie));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetData(HSTRING formatId, void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetData(*reinterpret_cast<hstring const*>(&formatId), *reinterpret_cast<Windows::Foundation::IInspectable const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetDataProvider(HSTRING formatId, void* delayRenderer) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetDataProvider(*reinterpret_cast<hstring const*>(&formatId), *reinterpret_cast<Windows::ApplicationModel::DataTransfer::DataProviderHandler const*>(&delayRenderer));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetText(HSTRING value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetText(*reinterpret_cast<hstring const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetUri(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetUri(*reinterpret_cast<Windows::Foundation::Uri const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetHtmlFormat(HSTRING value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetHtmlFormat(*reinterpret_cast<hstring const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ResourceMap(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Collections::IMap<hstring, Windows::Storage::Streams::RandomAccessStreamReference>>(this->shim().ResourceMap());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetRtf(HSTRING value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetRtf(*reinterpret_cast<hstring const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetBitmap(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetBitmap(*reinterpret_cast<Windows::Storage::Streams::RandomAccessStreamReference const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetStorageItemsReadOnly(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetStorageItems(*reinterpret_cast<Windows::Foundation::Collections::IIterable<Windows::Storage::IStorageItem> const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetStorageItems(void* value, bool readOnly) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetStorageItems(*reinterpret_cast<Windows::Foundation::Collections::IIterable<Windows::Storage::IStorageItem> const*>(&value), readOnly);
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackage2> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackage2>
{
HRESULT __stdcall SetApplicationLink(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetApplicationLink(*reinterpret_cast<Windows::Foundation::Uri const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetWebLink(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetWebLink(*reinterpret_cast<Windows::Foundation::Uri const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackage3> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackage3>
{
HRESULT __stdcall add_ShareCompleted(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().ShareCompleted(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataPackage, Windows::ApplicationModel::DataTransfer::ShareCompletedEventArgs> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_ShareCompleted(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ShareCompleted(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet>
{
HRESULT __stdcall get_Title(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().Title());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_Title(HSTRING value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Title(*reinterpret_cast<hstring const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Description(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().Description());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_Description(HSTRING value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Description(*reinterpret_cast<hstring const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Thumbnail(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Storage::Streams::IRandomAccessStreamReference>(this->shim().Thumbnail());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_Thumbnail(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Thumbnail(*reinterpret_cast<Windows::Storage::Streams::IRandomAccessStreamReference const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_FileTypes(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Collections::IVector<hstring>>(this->shim().FileTypes());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ApplicationName(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().ApplicationName());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_ApplicationName(HSTRING value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ApplicationName(*reinterpret_cast<hstring const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ApplicationListingUri(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Uri>(this->shim().ApplicationListingUri());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_ApplicationListingUri(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ApplicationListingUri(*reinterpret_cast<Windows::Foundation::Uri const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2>
{
HRESULT __stdcall get_ContentSourceWebLink(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Uri>(this->shim().ContentSourceWebLink());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_ContentSourceWebLink(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ContentSourceWebLink(*reinterpret_cast<Windows::Foundation::Uri const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ContentSourceApplicationLink(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Uri>(this->shim().ContentSourceApplicationLink());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_ContentSourceApplicationLink(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ContentSourceApplicationLink(*reinterpret_cast<Windows::Foundation::Uri const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_PackageFamilyName(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().PackageFamilyName());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_PackageFamilyName(HSTRING value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().PackageFamilyName(*reinterpret_cast<hstring const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Square30x30Logo(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Storage::Streams::IRandomAccessStreamReference>(this->shim().Square30x30Logo());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_Square30x30Logo(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Square30x30Logo(*reinterpret_cast<Windows::Storage::Streams::IRandomAccessStreamReference const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_LogoBackgroundColor(struct struct_Windows_UI_Color* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::UI::Color>(this->shim().LogoBackgroundColor());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_LogoBackgroundColor(struct struct_Windows_UI_Color value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().LogoBackgroundColor(*reinterpret_cast<Windows::UI::Color const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet3> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet3>
{
HRESULT __stdcall get_EnterpriseId(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().EnterpriseId());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_EnterpriseId(HSTRING value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().EnterpriseId(*reinterpret_cast<hstring const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet4> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet4>
{
HRESULT __stdcall get_ContentSourceUserActivityJson(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().ContentSourceUserActivityJson());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_ContentSourceUserActivityJson(HSTRING value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ContentSourceUserActivityJson(*reinterpret_cast<hstring const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView>
{
HRESULT __stdcall get_Title(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().Title());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Description(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().Description());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Thumbnail(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Storage::Streams::RandomAccessStreamReference>(this->shim().Thumbnail());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_FileTypes(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Collections::IVectorView<hstring>>(this->shim().FileTypes());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ApplicationName(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().ApplicationName());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ApplicationListingUri(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Uri>(this->shim().ApplicationListingUri());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView2> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView2>
{
HRESULT __stdcall get_PackageFamilyName(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().PackageFamilyName());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ContentSourceWebLink(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Uri>(this->shim().ContentSourceWebLink());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ContentSourceApplicationLink(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Uri>(this->shim().ContentSourceApplicationLink());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Square30x30Logo(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Storage::Streams::IRandomAccessStreamReference>(this->shim().Square30x30Logo());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_LogoBackgroundColor(struct struct_Windows_UI_Color* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::UI::Color>(this->shim().LogoBackgroundColor());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView3> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView3>
{
HRESULT __stdcall get_EnterpriseId(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().EnterpriseId());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView4> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView4>
{
HRESULT __stdcall get_ContentSourceUserActivityJson(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().ContentSourceUserActivityJson());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackageView> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackageView>
{
HRESULT __stdcall get_Properties(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataPackagePropertySetView>(this->shim().Properties());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_RequestedOperation(Windows::ApplicationModel::DataTransfer::DataPackageOperation* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataPackageOperation>(this->shim().RequestedOperation());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall ReportOperationCompleted(Windows::ApplicationModel::DataTransfer::DataPackageOperation value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ReportOperationCompleted(*reinterpret_cast<Windows::ApplicationModel::DataTransfer::DataPackageOperation const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_AvailableFormats(void** formatIds) noexcept final
{
try
{
*formatIds = nullptr;
typename D::abi_guard guard(this->shim());
*formatIds = detach_from<Windows::Foundation::Collections::IVectorView<hstring>>(this->shim().AvailableFormats());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall Contains(HSTRING formatId, bool* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<bool>(this->shim().Contains(*reinterpret_cast<hstring const*>(&formatId)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetDataAsync(HSTRING formatId, void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<Windows::Foundation::IInspectable>>(this->shim().GetDataAsync(*reinterpret_cast<hstring const*>(&formatId)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetTextAsync(void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<hstring>>(this->shim().GetTextAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetCustomTextAsync(HSTRING formatId, void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<hstring>>(this->shim().GetTextAsync(*reinterpret_cast<hstring const*>(&formatId)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetUriAsync(void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<Windows::Foundation::Uri>>(this->shim().GetUriAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetHtmlFormatAsync(void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<hstring>>(this->shim().GetHtmlFormatAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetResourceMapAsync(void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IMapView<hstring, Windows::Storage::Streams::RandomAccessStreamReference>>>(this->shim().GetResourceMapAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetRtfAsync(void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<hstring>>(this->shim().GetRtfAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetBitmapAsync(void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<Windows::Storage::Streams::RandomAccessStreamReference>>(this->shim().GetBitmapAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetStorageItemsAsync(void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<Windows::Foundation::Collections::IVectorView<Windows::Storage::IStorageItem>>>(this->shim().GetStorageItemsAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackageView2> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackageView2>
{
HRESULT __stdcall GetApplicationLinkAsync(void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<Windows::Foundation::Uri>>(this->shim().GetApplicationLinkAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetWebLinkAsync(void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<Windows::Foundation::Uri>>(this->shim().GetWebLinkAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackageView3> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackageView3>
{
HRESULT __stdcall RequestAccessAsync(void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>>(this->shim().RequestAccessAsync());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall RequestAccessWithEnterpriseIdAsync(HSTRING enterpriseId, void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>>(this->shim().RequestAccessAsync(*reinterpret_cast<hstring const*>(&enterpriseId)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall UnlockAndAssumeEnterpriseIdentity(Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult* result) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*result = detach_from<Windows::Security::EnterpriseData::ProtectionPolicyEvaluationResult>(this->shim().UnlockAndAssumeEnterpriseIdentity());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataPackageView4> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataPackageView4>
{
HRESULT __stdcall SetAcceptedFormatId(HSTRING formatId) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetAcceptedFormatId(*reinterpret_cast<hstring const*>(&formatId));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataProviderDeferral> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataProviderDeferral>
{
HRESULT __stdcall Complete() noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Complete();
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataProviderRequest> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataProviderRequest>
{
HRESULT __stdcall get_FormatId(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().FormatId());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Deadline(Windows::Foundation::DateTime* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::DateTime>(this->shim().Deadline());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetDeferral(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataProviderDeferral>(this->shim().GetDeferral());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall SetData(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SetData(*reinterpret_cast<Windows::Foundation::IInspectable const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataRequest> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataRequest>
{
HRESULT __stdcall get_Data(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataPackage>(this->shim().Data());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_Data(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Data(*reinterpret_cast<Windows::ApplicationModel::DataTransfer::DataPackage const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Deadline(Windows::Foundation::DateTime* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::DateTime>(this->shim().Deadline());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall FailWithDisplayText(HSTRING value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().FailWithDisplayText(*reinterpret_cast<hstring const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetDeferral(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataRequestDeferral>(this->shim().GetDeferral());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataRequestDeferral> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataRequestDeferral>
{
HRESULT __stdcall Complete() noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Complete();
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs>
{
HRESULT __stdcall get_Request(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataRequest>(this->shim().Request());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataTransferManager> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataTransferManager>
{
HRESULT __stdcall add_DataRequested(void* eventHandler, event_token* eventCookie) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*eventCookie = detach_from<event_token>(this->shim().DataRequested(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager, Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs> const*>(&eventHandler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_DataRequested(event_token eventCookie) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().DataRequested(*reinterpret_cast<event_token const*>(&eventCookie));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall add_TargetApplicationChosen(void* eventHandler, event_token* eventCookie) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*eventCookie = detach_from<event_token>(this->shim().TargetApplicationChosen(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager, Windows::ApplicationModel::DataTransfer::TargetApplicationChosenEventArgs> const*>(&eventHandler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_TargetApplicationChosen(event_token eventCookie) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().TargetApplicationChosen(*reinterpret_cast<event_token const*>(&eventCookie));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataTransferManager2> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataTransferManager2>
{
HRESULT __stdcall add_ShareProvidersRequested(void* handler, event_token* token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*token = detach_from<event_token>(this->shim().ShareProvidersRequested(*reinterpret_cast<Windows::Foundation::TypedEventHandler<Windows::ApplicationModel::DataTransfer::DataTransferManager, Windows::ApplicationModel::DataTransfer::ShareProvidersRequestedEventArgs> const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall remove_ShareProvidersRequested(event_token token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ShareProvidersRequested(*reinterpret_cast<event_token const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics>
{
HRESULT __stdcall ShowShareUI() noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ShowShareUI();
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetForCurrentView(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataTransferManager>(this->shim().GetForCurrentView());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics2> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics2>
{
HRESULT __stdcall IsSupported(bool* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<bool>(this->shim().IsSupported());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics3> : produce_base<D, Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics3>
{
HRESULT __stdcall ShowShareUIWithOptions(void* options) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ShowShareUI(*reinterpret_cast<Windows::ApplicationModel::DataTransfer::ShareUIOptions const*>(&options));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IHtmlFormatHelperStatics> : produce_base<D, Windows::ApplicationModel::DataTransfer::IHtmlFormatHelperStatics>
{
HRESULT __stdcall GetStaticFragment(HSTRING htmlFormat, HSTRING* htmlFragment) noexcept final
{
try
{
*htmlFragment = nullptr;
typename D::abi_guard guard(this->shim());
*htmlFragment = detach_from<hstring>(this->shim().GetStaticFragment(*reinterpret_cast<hstring const*>(&htmlFormat)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall CreateHtmlFormat(HSTRING htmlFragment, HSTRING* htmlFormat) noexcept final
{
try
{
*htmlFormat = nullptr;
typename D::abi_guard guard(this->shim());
*htmlFormat = detach_from<hstring>(this->shim().CreateHtmlFormat(*reinterpret_cast<hstring const*>(&htmlFragment)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IOperationCompletedEventArgs> : produce_base<D, Windows::ApplicationModel::DataTransfer::IOperationCompletedEventArgs>
{
HRESULT __stdcall get_Operation(Windows::ApplicationModel::DataTransfer::DataPackageOperation* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataPackageOperation>(this->shim().Operation());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IOperationCompletedEventArgs2> : produce_base<D, Windows::ApplicationModel::DataTransfer::IOperationCompletedEventArgs2>
{
HRESULT __stdcall get_AcceptedFormatId(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().AcceptedFormatId());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IShareCompletedEventArgs> : produce_base<D, Windows::ApplicationModel::DataTransfer::IShareCompletedEventArgs>
{
HRESULT __stdcall get_ShareTarget(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::ShareTargetInfo>(this->shim().ShareTarget());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IShareProvider> : produce_base<D, Windows::ApplicationModel::DataTransfer::IShareProvider>
{
HRESULT __stdcall get_Title(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().Title());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_DisplayIcon(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Storage::Streams::RandomAccessStreamReference>(this->shim().DisplayIcon());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_BackgroundColor(struct struct_Windows_UI_Color* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::UI::Color>(this->shim().BackgroundColor());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Tag(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::IInspectable>(this->shim().Tag());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_Tag(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Tag(*reinterpret_cast<Windows::Foundation::IInspectable const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IShareProviderFactory> : produce_base<D, Windows::ApplicationModel::DataTransfer::IShareProviderFactory>
{
HRESULT __stdcall Create(HSTRING title, void* displayIcon, struct struct_Windows_UI_Color backgroundColor, void* handler, void** result) noexcept final
{
try
{
*result = nullptr;
typename D::abi_guard guard(this->shim());
*result = detach_from<Windows::ApplicationModel::DataTransfer::ShareProvider>(this->shim().Create(*reinterpret_cast<hstring const*>(&title), *reinterpret_cast<Windows::Storage::Streams::RandomAccessStreamReference const*>(&displayIcon), *reinterpret_cast<Windows::UI::Color const*>(&backgroundColor), *reinterpret_cast<Windows::ApplicationModel::DataTransfer::ShareProviderHandler const*>(&handler)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IShareProviderOperation> : produce_base<D, Windows::ApplicationModel::DataTransfer::IShareProviderOperation>
{
HRESULT __stdcall get_Data(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataPackageView>(this->shim().Data());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Provider(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::ShareProvider>(this->shim().Provider());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall ReportCompleted() noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().ReportCompleted();
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IShareProvidersRequestedEventArgs> : produce_base<D, Windows::ApplicationModel::DataTransfer::IShareProvidersRequestedEventArgs>
{
HRESULT __stdcall get_Providers(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Collections::IVector<Windows::ApplicationModel::DataTransfer::ShareProvider>>(this->shim().Providers());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Data(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::DataPackageView>(this->shim().Data());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall GetDeferral(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::Deferral>(this->shim().GetDeferral());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IShareTargetInfo> : produce_base<D, Windows::ApplicationModel::DataTransfer::IShareTargetInfo>
{
HRESULT __stdcall get_AppUserModelId(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().AppUserModelId());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ShareProvider(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::ShareProvider>(this->shim().ShareProvider());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IShareUIOptions> : produce_base<D, Windows::ApplicationModel::DataTransfer::IShareUIOptions>
{
HRESULT __stdcall get_Theme(Windows::ApplicationModel::DataTransfer::ShareUITheme* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::ApplicationModel::DataTransfer::ShareUITheme>(this->shim().Theme());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_Theme(Windows::ApplicationModel::DataTransfer::ShareUITheme value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().Theme(*reinterpret_cast<Windows::ApplicationModel::DataTransfer::ShareUITheme const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_SelectionRect(void** value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<Windows::Foundation::IReference<Windows::Foundation::Rect>>(this->shim().SelectionRect());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall put_SelectionRect(void* value) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().SelectionRect(*reinterpret_cast<Windows::Foundation::IReference<Windows::Foundation::Rect> const*>(&value));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::ISharedStorageAccessManagerStatics> : produce_base<D, Windows::ApplicationModel::DataTransfer::ISharedStorageAccessManagerStatics>
{
HRESULT __stdcall AddFile(void* file, HSTRING* outToken) noexcept final
{
try
{
*outToken = nullptr;
typename D::abi_guard guard(this->shim());
*outToken = detach_from<hstring>(this->shim().AddFile(*reinterpret_cast<Windows::Storage::IStorageFile const*>(&file)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall RedeemTokenForFileAsync(HSTRING token, void** operation) noexcept final
{
try
{
*operation = nullptr;
typename D::abi_guard guard(this->shim());
*operation = detach_from<Windows::Foundation::IAsyncOperation<Windows::Storage::StorageFile>>(this->shim().RedeemTokenForFileAsync(*reinterpret_cast<hstring const*>(&token)));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall RemoveFile(HSTRING token) noexcept final
{
try
{
typename D::abi_guard guard(this->shim());
this->shim().RemoveFile(*reinterpret_cast<hstring const*>(&token));
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics> : produce_base<D, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics>
{
HRESULT __stdcall get_Text(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().Text());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Uri(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().Uri());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Html(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().Html());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Rtf(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().Rtf());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_Bitmap(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().Bitmap());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_StorageItems(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().StorageItems());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics2> : produce_base<D, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics2>
{
HRESULT __stdcall get_WebLink(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().WebLink());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
HRESULT __stdcall get_ApplicationLink(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().ApplicationLink());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics3> : produce_base<D, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics3>
{
HRESULT __stdcall get_UserActivityJsonArray(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().UserActivityJsonArray());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
template <typename D>
struct produce<D, Windows::ApplicationModel::DataTransfer::ITargetApplicationChosenEventArgs> : produce_base<D, Windows::ApplicationModel::DataTransfer::ITargetApplicationChosenEventArgs>
{
HRESULT __stdcall get_ApplicationName(HSTRING* value) noexcept final
{
try
{
*value = nullptr;
typename D::abi_guard guard(this->shim());
*value = detach_from<hstring>(this->shim().ApplicationName());
return S_OK;
}
catch (...)
{
return to_hresult();
}
}
};
}
WINRT_EXPORT namespace winrt::Windows::ApplicationModel::DataTransfer {
inline Windows::ApplicationModel::DataTransfer::DataPackageView Clipboard::GetContent()
{
return get_activation_factory<Clipboard, Windows::ApplicationModel::DataTransfer::IClipboardStatics>().GetContent();
}
inline void Clipboard::SetContent(Windows::ApplicationModel::DataTransfer::DataPackage const& content)
{
get_activation_factory<Clipboard, Windows::ApplicationModel::DataTransfer::IClipboardStatics>().SetContent(content);
}
inline void Clipboard::Flush()
{
get_activation_factory<Clipboard, Windows::ApplicationModel::DataTransfer::IClipboardStatics>().Flush();
}
inline void Clipboard::Clear()
{
get_activation_factory<Clipboard, Windows::ApplicationModel::DataTransfer::IClipboardStatics>().Clear();
}
inline event_token Clipboard::ContentChanged(Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> const& changeHandler)
{
return get_activation_factory<Clipboard, Windows::ApplicationModel::DataTransfer::IClipboardStatics>().ContentChanged(changeHandler);
}
inline factory_event_revoker<Windows::ApplicationModel::DataTransfer::IClipboardStatics> Clipboard::ContentChanged(auto_revoke_t, Windows::Foundation::EventHandler<Windows::Foundation::IInspectable> const& changeHandler)
{
auto factory = get_activation_factory<Clipboard, Windows::ApplicationModel::DataTransfer::IClipboardStatics>();
return { factory, &impl::abi_t<Windows::ApplicationModel::DataTransfer::IClipboardStatics>::remove_ContentChanged, factory.ContentChanged(changeHandler) };
}
inline void Clipboard::ContentChanged(event_token const& token)
{
get_activation_factory<Clipboard, Windows::ApplicationModel::DataTransfer::IClipboardStatics>().ContentChanged(token);
}
inline DataPackage::DataPackage() :
DataPackage(get_activation_factory<DataPackage>().ActivateInstance<DataPackage>())
{}
inline void DataTransferManager::ShowShareUI()
{
get_activation_factory<DataTransferManager, Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics>().ShowShareUI();
}
inline Windows::ApplicationModel::DataTransfer::DataTransferManager DataTransferManager::GetForCurrentView()
{
return get_activation_factory<DataTransferManager, Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics>().GetForCurrentView();
}
inline bool DataTransferManager::IsSupported()
{
return get_activation_factory<DataTransferManager, Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics2>().IsSupported();
}
inline void DataTransferManager::ShowShareUI(Windows::ApplicationModel::DataTransfer::ShareUIOptions const& options)
{
get_activation_factory<DataTransferManager, Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics3>().ShowShareUI(options);
}
inline hstring HtmlFormatHelper::GetStaticFragment(param::hstring const& htmlFormat)
{
return get_activation_factory<HtmlFormatHelper, Windows::ApplicationModel::DataTransfer::IHtmlFormatHelperStatics>().GetStaticFragment(htmlFormat);
}
inline hstring HtmlFormatHelper::CreateHtmlFormat(param::hstring const& htmlFragment)
{
return get_activation_factory<HtmlFormatHelper, Windows::ApplicationModel::DataTransfer::IHtmlFormatHelperStatics>().CreateHtmlFormat(htmlFragment);
}
inline ShareProvider::ShareProvider(param::hstring const& title, Windows::Storage::Streams::RandomAccessStreamReference const& displayIcon, Windows::UI::Color const& backgroundColor, Windows::ApplicationModel::DataTransfer::ShareProviderHandler const& handler) :
ShareProvider(get_activation_factory<ShareProvider, Windows::ApplicationModel::DataTransfer::IShareProviderFactory>().Create(title, displayIcon, backgroundColor, handler))
{}
inline ShareUIOptions::ShareUIOptions() :
ShareUIOptions(get_activation_factory<ShareUIOptions>().ActivateInstance<ShareUIOptions>())
{}
inline hstring SharedStorageAccessManager::AddFile(Windows::Storage::IStorageFile const& file)
{
return get_activation_factory<SharedStorageAccessManager, Windows::ApplicationModel::DataTransfer::ISharedStorageAccessManagerStatics>().AddFile(file);
}
inline Windows::Foundation::IAsyncOperation<Windows::Storage::StorageFile> SharedStorageAccessManager::RedeemTokenForFileAsync(param::hstring const& token)
{
return get_activation_factory<SharedStorageAccessManager, Windows::ApplicationModel::DataTransfer::ISharedStorageAccessManagerStatics>().RedeemTokenForFileAsync(token);
}
inline void SharedStorageAccessManager::RemoveFile(param::hstring const& token)
{
get_activation_factory<SharedStorageAccessManager, Windows::ApplicationModel::DataTransfer::ISharedStorageAccessManagerStatics>().RemoveFile(token);
}
inline hstring StandardDataFormats::Text()
{
return get_activation_factory<StandardDataFormats, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics>().Text();
}
inline hstring StandardDataFormats::Uri()
{
return get_activation_factory<StandardDataFormats, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics>().Uri();
}
inline hstring StandardDataFormats::Html()
{
return get_activation_factory<StandardDataFormats, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics>().Html();
}
inline hstring StandardDataFormats::Rtf()
{
return get_activation_factory<StandardDataFormats, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics>().Rtf();
}
inline hstring StandardDataFormats::Bitmap()
{
return get_activation_factory<StandardDataFormats, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics>().Bitmap();
}
inline hstring StandardDataFormats::StorageItems()
{
return get_activation_factory<StandardDataFormats, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics>().StorageItems();
}
inline hstring StandardDataFormats::WebLink()
{
return get_activation_factory<StandardDataFormats, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics2>().WebLink();
}
inline hstring StandardDataFormats::ApplicationLink()
{
return get_activation_factory<StandardDataFormats, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics2>().ApplicationLink();
}
inline hstring StandardDataFormats::UserActivityJsonArray()
{
return get_activation_factory<StandardDataFormats, Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics3>().UserActivityJsonArray();
}
template <typename L> DataProviderHandler::DataProviderHandler(L handler) :
DataProviderHandler(impl::make_delegate<DataProviderHandler>(std::forward<L>(handler)))
{}
template <typename F> DataProviderHandler::DataProviderHandler(F* handler) :
DataProviderHandler([=](auto&&... args) { handler(args...); })
{}
template <typename O, typename M> DataProviderHandler::DataProviderHandler(O* object, M method) :
DataProviderHandler([=](auto&&... args) { ((*object).*(method))(args...); })
{}
inline void DataProviderHandler::operator()(Windows::ApplicationModel::DataTransfer::DataProviderRequest const& request) const
{
check_hresult((*(impl::abi_t<DataProviderHandler>**)this)->Invoke(get_abi(request)));
}
template <typename L> ShareProviderHandler::ShareProviderHandler(L handler) :
ShareProviderHandler(impl::make_delegate<ShareProviderHandler>(std::forward<L>(handler)))
{}
template <typename F> ShareProviderHandler::ShareProviderHandler(F* handler) :
ShareProviderHandler([=](auto&&... args) { handler(args...); })
{}
template <typename O, typename M> ShareProviderHandler::ShareProviderHandler(O* object, M method) :
ShareProviderHandler([=](auto&&... args) { ((*object).*(method))(args...); })
{}
inline void ShareProviderHandler::operator()(Windows::ApplicationModel::DataTransfer::ShareProviderOperation const& operation) const
{
check_hresult((*(impl::abi_t<ShareProviderHandler>**)this)->Invoke(get_abi(operation)));
}
}
WINRT_EXPORT namespace std {
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IClipboardStatics> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IClipboardStatics> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackage> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackage> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackage2> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackage2> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackage3> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackage3> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet2> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet3> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet3> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet4> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySet4> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView2> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView2> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView3> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView3> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView4> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackagePropertySetView4> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackageView> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackageView> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackageView2> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackageView2> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackageView3> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackageView3> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataPackageView4> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataPackageView4> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataProviderDeferral> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataProviderDeferral> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataProviderRequest> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataProviderRequest> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataRequest> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataRequest> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataRequestDeferral> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataRequestDeferral> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataRequestedEventArgs> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataTransferManager> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataTransferManager> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataTransferManager2> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataTransferManager2> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics2> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics2> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics3> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IDataTransferManagerStatics3> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IHtmlFormatHelperStatics> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IHtmlFormatHelperStatics> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IOperationCompletedEventArgs> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IOperationCompletedEventArgs> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IOperationCompletedEventArgs2> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IOperationCompletedEventArgs2> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IShareCompletedEventArgs> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IShareCompletedEventArgs> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IShareProvider> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IShareProvider> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IShareProviderFactory> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IShareProviderFactory> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IShareProviderOperation> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IShareProviderOperation> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IShareProvidersRequestedEventArgs> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IShareProvidersRequestedEventArgs> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IShareTargetInfo> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IShareTargetInfo> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IShareUIOptions> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IShareUIOptions> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::ISharedStorageAccessManagerStatics> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::ISharedStorageAccessManagerStatics> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics2> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics2> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics3> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::IStandardDataFormatsStatics3> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::ITargetApplicationChosenEventArgs> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::ITargetApplicationChosenEventArgs> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::Clipboard> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::Clipboard> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::DataPackage> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::DataPackage> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::DataPackagePropertySet> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::DataPackagePropertySet> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::DataPackagePropertySetView> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::DataPackagePropertySetView> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::DataPackageView> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::DataPackageView> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::DataProviderDeferral> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::DataProviderDeferral> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::DataProviderRequest> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::DataProviderRequest> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::DataRequest> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::DataRequest> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::DataRequestDeferral> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::DataRequestDeferral> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::DataRequestedEventArgs> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::DataTransferManager> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::DataTransferManager> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::HtmlFormatHelper> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::HtmlFormatHelper> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::OperationCompletedEventArgs> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::OperationCompletedEventArgs> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::ShareCompletedEventArgs> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::ShareCompletedEventArgs> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::ShareProvider> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::ShareProvider> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::ShareProviderOperation> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::ShareProviderOperation> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::ShareProvidersRequestedEventArgs> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::ShareProvidersRequestedEventArgs> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::ShareTargetInfo> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::ShareTargetInfo> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::ShareUIOptions> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::ShareUIOptions> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::SharedStorageAccessManager> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::SharedStorageAccessManager> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::StandardDataFormats> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::StandardDataFormats> {};
template<> struct hash<winrt::Windows::ApplicationModel::DataTransfer::TargetApplicationChosenEventArgs> : winrt::impl::hash_base<winrt::Windows::ApplicationModel::DataTransfer::TargetApplicationChosenEventArgs> {};
}
WINRT_WARNING_POP
| 40.996589 | 413 | 0.700942 | [
"object"
] |
762a859e3d2f33d077404e494a28e541cce82dbc | 5,332 | h | C | src/symmetry/symmetrization.h | LinjianMa/ctf | 06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e | [
"BSD-2-Clause"
] | 108 | 2018-01-01T21:29:15.000Z | 2022-02-24T17:51:15.000Z | src/symmetry/symmetrization.h | LinjianMa/ctf | 06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e | [
"BSD-2-Clause"
] | 91 | 2017-12-27T04:28:09.000Z | 2022-03-10T09:14:43.000Z | src/symmetry/symmetrization.h | LinjianMa/ctf | 06a50b6ea4be2eeb7f3d6c43f05a0befae94f08e | [
"BSD-2-Clause"
] | 45 | 2017-12-26T21:15:21.000Z | 2022-02-10T11:16:40.000Z | #ifndef __INT_SYMMETRIZATION_H__
#define __INT_SYMMETRIZATION_H__
#include <assert.h>
#include "../tensor/untyped_tensor.h"
#include "../summation/summation.h"
#include "../contraction/contraction.h"
namespace CTF_int {
/**
* \brief unfolds the data of a tensor
* \param[in] sym_tsr starting symmetric tensor (where data starts)
* \param[in] nonsym_tsr new tensor with a potentially unfolded symmetry
* \param[in] is_C whether the tensor is an output of the operation
*/
void desymmetrize(tensor * sym_tsr,
tensor * nonsym_tsr,
bool is_C);
/**
* \brief folds the data of a tensor
* \param[in] sym_tsr starting symmetric tensor (where data ends)
* \param[in] nonsym_tsr new tensor with a potentially unfolded symmetry
*/
void symmetrize(tensor * sym_tsr,
tensor * nonsym_tsr);
/**
* \brief finds all permutations of a tensor according to a symmetry
*
* \param[in] ndim dimension of tensor
* \param[in] sym symmetry specification of tensor
* \param[out] nperm number of symmeitrc permutations to do
* \param[out] perm the permutation
* \param[out] sign sign of each permutation
*/
void cmp_sym_perms(int ndim,
int const * sym,
int * nperm,
int ** perm,
double * sign);
/**
* \brief orders the summation indices of one tensor
* that don't break summation symmetries
*
* \param[in] A
* \param[in] B
* \param[in] idx_arr inverted summation index map
* \param[in] off_A offset of A in inverted index map
* \param[in] off_B offset of B in inverted index map
* \param[in] idx_A index map of A
* \param[in] idx_B index map of B
* \param[in,out] add_sign sign of contraction
* \param[in,out] mod 1 if sum is permuted
*/
void order_perm(tensor const * A,
tensor const * B,
int * idx_arr,
int off_A,
int off_B,
int * idx_A,
int * idx_B,
int & add_sign,
int & mod);
/**
* \brief orders the contraction indices of one tensor
* that don't break contraction symmetries
*
* \param[in] A
* \param[in] B
* \param[in] C
* \param[in] idx_arr inverted contraction index map
* \param[in] off_A offset of A in inverted index map
* \param[in] off_B offset of B in inverted index map
* \param[in] off_C offset of C in inverted index map
* \param[in] idx_A index map of A
* \param[in] idx_B index map of B
* \param[in] idx_C index map of C
* \param[in,out] add_sign sign of contraction
* \param[in,out] mod 1 if permutation done
*/
void order_perm(tensor const * A,
tensor const * B,
tensor const * C,
int * idx_arr,
int off_A,
int off_B,
int off_C,
int * idx_A,
int * idx_B,
int * idx_C,
int & add_sign,
int & mod);
/**
* \brief puts a summation map into a nice ordering according to preserved
* symmetries, and adds it if it is distinct
*
* \param[in,out] perms the permuted summation specifications
* \param[in,out] signs sign of each summation
* \param[in] new_perm summation signature
* \param[in] new_sign alpha
*/
void add_sym_perm(std::vector<summation>& perms,
std::vector<int>& signs,
summation const & new_perm,
int new_sign);
/**
* \brief puts a contraction map into a nice ordering according to preserved
* symmetries, and adds it if it is distinct
*
* \param[in,out] perms the permuted contraction specifications
* \param[in,out] signs sign of each contraction
* \param[in] new_perm contraction signature
* \param[in] new_sign alpha
*/
void add_sym_perm(std::vector<contraction>& perms,
std::vector<int>& signs,
contraction const & new_perm,
int new_sign);
/**
* \brief finds all permutations of a summation
* that must be done for a broken symmetry
*
* \param[in] sum summation specification
* \param[out] perms the permuted summation specifications
* \param[out] signs sign of each summation
*/
void get_sym_perms(summation const & sum,
std::vector<summation>& perms,
std::vector<int>& signs);
/**
* \brief finds all permutations of a contraction
* that must be done for a broken symmetry
*
* \param[in] ctr contraction specification
* \param[out] perms the permuted contraction specifications
* \param[out] signs sign of each contraction
*/
void get_sym_perms(contraction const & ctr,
std::vector<contraction>& perms,
std::vector<int>& signs);
}
#endif
| 33.961783 | 78 | 0.559265 | [
"vector"
] |
762c368c4a0f8670674ce7d8b25b16405f98afd4 | 671 | h | C | sdl2/SpaceInvader/Header_Files/GameStateMachine.h | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | sdl2/SpaceInvader/Header_Files/GameStateMachine.h | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | sdl2/SpaceInvader/Header_Files/GameStateMachine.h | pdpdds/SDLGameProgramming | 3af68e2133296f3e7bc3d7454d9301141bca2d5a | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <vector>
#include "GameState.h"
class GameStateMachine
{
private:
std::vector<GameState*> m_gameStates;
public:
//Change current state without calling previous state's exit
void pushState(GameState* state);
//Change current state. Call exit on current state and enter on new state
void changeState(GameState* state);
//Remove current state and resume to previous state
void popState();
//Called each frame. Updates current GameState's active gameobjects
void update();
//Called each frame. Perform render on current GameState's active gameobjects
void render();
//Get reference to current state
GameState* getCurrentState();
};
| 22.366667 | 78 | 0.76304 | [
"render",
"vector"
] |
7630e37572ebda4bc609d3666d180fedf8952f0e | 4,028 | h | C | src/extern/inventor/lib/database/include/Inventor/details/SoTextDetail.h | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 2 | 2020-05-21T07:06:07.000Z | 2021-06-28T02:14:34.000Z | src/extern/inventor/lib/database/include/Inventor/details/SoTextDetail.h | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | null | null | null | src/extern/inventor/lib/database/include/Inventor/details/SoTextDetail.h | OpenXIP/xip-libraries | 9f0fef66038b20ff0c81c089d7dd0038e3126e40 | [
"Apache-2.0"
] | 6 | 2016-03-21T19:53:18.000Z | 2021-06-08T18:06:03.000Z | /*
*
* Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Further, this software is distributed without any warranty that it is
* free of the rightful claim of any third person regarding infringement
* or the like. Any license provided herein, whether implied or
* otherwise, applies only to this software file. Patent licenses, if
* any, provided herein do not apply to combinations of this program with
* other software, or any other product whatsoever.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
* Mountain View, CA 94043, or:
*
* http://www.sgi.com
*
* For further information regarding this notice, see:
*
* http://oss.sgi.com/projects/GenInfo/NoticeExplan/
*
*/
// -*- C++ -*-
/*
* Copyright (C) 1990,91 Silicon Graphics, Inc.
*
_______________________________________________________________________
______________ S I L I C O N G R A P H I C S I N C . ____________
|
| $Revision: 1.1.1.1 $
|
| Description:
| This file defines the SoTextDetail class.
|
| Author(s) : Thaddeus Beier, Dave Immel, Howard Look
|
______________ S I L I C O N G R A P H I C S I N C . ____________
_______________________________________________________________________
*/
#ifndef _SO_TEXT_DETAIL_
#define _SO_TEXT_DETAIL_
#include <Inventor/SbBox.h>
#include <Inventor/details/SoSubDetail.h>
#include <Inventor/nodes/SoText3.h>
//////////////////////////////////////////////////////////////////////////////
//
// Class: SoTextDetail
//
// Detail about a shape representing text.
//
//////////////////////////////////////////////////////////////////////////////
// C-api: prefix=SoTxtDtl
class INVENTOR_API SoTextDetail : public SoDetail {
SO_DETAIL_HEADER(SoTextDetail);
public:
// Constructor and destructor
SoTextDetail();
virtual ~SoTextDetail();
// Returns the index of the string within a multiple-value string
// fields of a text node
// C-api: name=getStrInd
int32_t getStringIndex() const { return stringIndex; }
// Returns the index of the character within the string. For
// example, if the character of detail was the "u" within
// "Splurmph", the character index would be 3.
// C-api: name=getCharInd
int32_t getCharacterIndex() const { return charIndex; }
// For Text3, this returns which part was picked:
SoText3::Part getPart() const { return part; }
// Returns an instance that is a copy of this instance. The caller
// is responsible for deleting the copy when done.
virtual SoDetail * copy() const;
SoEXTENDER public:
// For Text3, this sets which part is picked:
void setPart(SoText3::Part p) { part = p; }
// These set the string and character indices:
void setStringIndex(int32_t i) { stringIndex = i; }
void setCharacterIndex(int32_t i) { charIndex = i; }
#ifndef IV_STRICT
void setStringIndex(long i) // System long
{ setStringIndex((int32_t) i); }
void setCharacterIndex(long i) // System long
{ setCharacterIndex((int32_t) i); }
#endif
SoINTERNAL public:
static void initClass();
private:
int32_t stringIndex, charIndex;
SoText3::Part part;
};
#endif /* _SO_TEXT_DETAIL_ */
| 32.747967 | 78 | 0.673784 | [
"shape"
] |
76414c8bb1cf35dff53afd32f3c00df9d936aab7 | 5,216 | h | C | hphp/util/stack-trace.h | sathvikl/hiphop-php | 34fa1033968d6ef243dcdb46eca2289d6ad674d2 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/util/stack-trace.h | sathvikl/hiphop-php | 34fa1033968d6ef243dcdb46eca2289d6ad674d2 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/util/stack-trace.h | sathvikl/hiphop-php | 34fa1033968d6ef243dcdb46eca2289d6ad674d2 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2016 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#ifndef incl_HPHP_STACKTRACE_H_
#define incl_HPHP_STACKTRACE_H_
#include <map>
#include <memory>
#include <string>
#include <vector>
#include <folly/Range.h>
#include "hphp/util/compatibility.h"
#include "hphp/util/portability.h"
#ifndef _MSC_VER
#include <dlfcn.h>
#endif
namespace HPHP {
////////////////////////////////////////////////////////////////////////////////
/*
* An unsymbolized stack frame.
*/
struct StackFrame {
explicit StackFrame(void* addr) : addr{addr} {}
void* addr{nullptr};
int lineno{0};
int offset{0};
};
/*
* A StackFrame that has been symbolized with a filename and function name.
*/
struct StackFrameExtra : StackFrame {
explicit StackFrameExtra(void* addr) : StackFrame(addr) {}
std::string toString() const;
std::string filename;
std::string funcname;
};
////////////////////////////////////////////////////////////////////////////////
/*
* Taking a stacktrace at current execution location. Do not use directly, use
* StackTrace or StackTraceNoHeap instead.
*/
struct StackTraceBase {
static constexpr unsigned kMaxFrame = 175;
static bool Enabled;
static const char** FunctionBlacklist;
static unsigned FunctionBlacklistCount;
protected:
StackTraceBase();
};
////////////////////////////////////////////////////////////////////////////////
struct StackTrace : StackTraceBase {
struct PerfMap {
void rebuild();
bool translate(StackFrameExtra*) const;
struct Range {
uintptr_t base;
uintptr_t past;
struct Cmp {
bool operator() (const Range& a, const Range& b) const {
return a.past <= b.base;
}
};
};
bool m_built = false;
std::map<Range,std::string,Range::Cmp> m_map;
};
//////////////////////////////////////////////////////////////////////////////
explicit StackTrace(bool trace = true);
/*
* Translate a frame pointer to file name and line number pair.
*/
static std::shared_ptr<StackFrameExtra> Translate(void* addr,
PerfMap* pm = nullptr);
/*
* Translate the frame pointer of a PHP function using the perf map.
*/
static void TranslateFromPerfMap(StackFrameExtra*);
/*
* Constructing from hexEncode() results.
*/
explicit StackTrace(folly::StringPiece);
/*
* Generate an output of the written stack trace.
*/
const std::string& toString(int skip = 0, int limit = -1) const;
/*
* Get frames in raw pointers or translated frames.
*/
void get(std::vector<void*>&) const;
void get(std::vector<std::shared_ptr<StackFrameExtra>>&) const;
std::string hexEncode(int minLevel = 0, int maxLevel = 999) const;
private:
/* Record frame pointers. */
void create();
/* Init by hex string. */
void initFromHex(folly::StringPiece);
std::vector<void*> m_frames;
/* Cached backtrace string. */
mutable std::string m_trace;
};
////////////////////////////////////////////////////////////////////////////////
/*
* Computing a stack trace without using the heap. Ideally this should be safe
* to use within a signal handler.
*/
struct StackTraceNoHeap : StackTraceBase {
/*
* Constructor, and this will save current stack trace if trace is true. It
* can be false for an empty stacktrace.
*/
explicit StackTraceNoHeap(bool trace = true);
/*
* Log stacktrace into the given file.
*/
void log(const char* errorType, int fd, const char* buildId,
int debuggerCount) const;
/*
* Add extra information to log together with a crash stacktrace log.
*/
static void AddExtraLogging(const char* name, const std::string& value);
static void ClearAllExtraLogging();
struct ExtraLoggingClearer {
ExtraLoggingClearer() {}
~ExtraLoggingClearer() {
StackTraceNoHeap::ClearAllExtraLogging();
}
};
private:
/* Generate an output of the written stack trace. */
void printStackTrace(int fd) const;
/* Record bt pointers. */
void create();
//////////////////////////////////////////////////////////////////////////////
void* m_frames[kMaxFrame];
unsigned m_frame_count;
};
////////////////////////////////////////////////////////////////////////////////
}
#endif
| 27.166667 | 80 | 0.543328 | [
"vector"
] |
7643d107b648019d332f6aa2c6efdcb951bbfdb4 | 496 | h | C | Simulator/src/data.h | zpervan/GameOfLife | 5de94ef837ada33e700b5e9e5b14b9371c00fe43 | [
"MIT"
] | 3 | 2020-12-12T15:49:03.000Z | 2021-05-22T02:04:02.000Z | Simulator/src/data.h | zpervan/GameOfLife | 5de94ef837ada33e700b5e9e5b14b9371c00fe43 | [
"MIT"
] | null | null | null | Simulator/src/data.h | zpervan/GameOfLife | 5de94ef837ada33e700b5e9e5b14b9371c00fe43 | [
"MIT"
] | null | null | null | #ifndef GAMEOFLIFE_SIMULATOR_SRC_DATA_H_
#define GAMEOFLIFE_SIMULATOR_SRC_DATA_H_
#include <array>
#include <bitset>
#include <vector>
#include <string>
using Rule = std::pair<std::string, std::bitset<8>>;
using Rules = std::vector<Rule>;
using CellNeighborhoodStates = std::array<bool, 3>;
enum class SimulationMode {
FINITE = 0,
ETERNAL
};
enum class SimulatorState {
INITIALIZATION = 0,
RUN,
PAUSE,
STOP,
NO_CHANGE
};
#endif //GAMEOFLIFE_SIMULATOR_SRC_DATA_H_
| 18.37037 | 52 | 0.721774 | [
"vector"
] |
764acc11757506a72f68d419ef7693c203aaa96d | 1,247 | h | C | Gems/GradientSignal/Code/Include/GradientSignal/Ebuses/GradientPreviewRequestBus.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/GradientSignal/Code/Include/GradientSignal/Ebuses/GradientPreviewRequestBus.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/GradientSignal/Code/Include/GradientSignal/Ebuses/GradientPreviewRequestBus.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#include <AzCore/EBus/EBus.h>
#include <AzCore/Component/EntityId.h>
#include <AzCore/Math/Vector3.h>
namespace GradientSignal
{
/**
* Bus enabling gradient previewer to be refreshed remotely via event bus
*/
class GradientPreviewRequests
: public AZ::EBusTraits
{
public:
////////////////////////////////////////////////////////////////////////
// EBusTraits
static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple;
static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::ById;
using BusIdType = AZ::EntityId;
using MutexType = AZStd::recursive_mutex;
////////////////////////////////////////////////////////////////////////
virtual ~GradientPreviewRequests() = default;
virtual void Refresh() = 0;
virtual AZ::EntityId CancelRefresh() = 0;
};
using GradientPreviewRequestBus = AZ::EBus<GradientPreviewRequests>;
} // namespace GradientSignal
| 31.974359 | 158 | 0.607057 | [
"3d"
] |
632d315aa42fe41caf75684ea046aa3af698a71d | 1,240 | h | C | include/raiGraphics/imp/transform.h | Wistral/raigraphics | 6234976256fcb34f419ef5a5523846b7791e6752 | [
"MIT"
] | null | null | null | include/raiGraphics/imp/transform.h | Wistral/raigraphics | 6234976256fcb34f419ef5a5523846b7791e6752 | [
"MIT"
] | null | null | null | include/raiGraphics/imp/transform.h | Wistral/raigraphics | 6234976256fcb34f419ef5a5523846b7791e6752 | [
"MIT"
] | null | null | null | #ifndef TRANSFORM_INCLUDED_H
#define TRANSFORM_INCLUDED_H
#ifndef GLM_ENABLE_EXPERIMENTAL
#define GLM_ENABLE_EXPERIMENTAL
#endif
#include <glm/glm.hpp>
#include "glm/gtx/quaternion.hpp"
#include <glm/gtx/transform.hpp>
namespace rai_graphics {
struct Transform {
public:
Transform(const glm::vec3 &pos = glm::vec3(),
const glm::quat &rot = glm::quat(),
const glm::vec3 &scale = glm::vec3(1.0f, 1.0f, 1.0f)) {
this->pos = pos;
this->rot = rot;
this->scale = scale;
}
glm::mat4 GetModel() const {
glm::mat4 rotMat = glm::toMat4(rot);
glm::mat4 posMat = glm::translate(pos);
return posMat * rotMat;
}
inline glm::mat4 GetM() const {
glm::mat4 M = GetModel();
return M;//camera.GetViewProjection() * GetModel(); VPM
}
inline glm::vec3 *GetPos() { return &pos; }
inline glm::quat *GetRot() { return &rot; }
inline glm::vec3 *GetScale() { return &scale; }
inline void SetPos(glm::vec3 &posL) { pos = posL; }
inline void SetRot(glm::quat &rotL) { rot = rotL; }
inline void SetScale(glm::vec3 &scaleL) { scale = scaleL; }
protected:
private:
glm::vec3 pos = {0,0,0};
glm::quat rot = {1,0,0,0};
glm::vec3 scale = {1,1,1};
};
} // rai_graphics
#endif
| 23.846154 | 67 | 0.634677 | [
"transform"
] |
632e35a542ab99e1159592aaff3014f282684cc5 | 3,826 | h | C | c_packetprocessing-master/microc/lib/std/synch.h | earthcomputing/Netronome | 9f5132ecea3c134322305c9524da7189374881ec | [
"MIT"
] | null | null | null | c_packetprocessing-master/microc/lib/std/synch.h | earthcomputing/Netronome | 9f5132ecea3c134322305c9524da7189374881ec | [
"MIT"
] | null | null | null | c_packetprocessing-master/microc/lib/std/synch.h | earthcomputing/Netronome | 9f5132ecea3c134322305c9524da7189374881ec | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2012-2015, Netronome Systems, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @file lib/std/synch.h
* @brief Synchronization primitives
*/
#ifndef _STD__SYNCH_H_
#define _STD__SYNCH_H_
#include <nfp.h>
#include <stdint.h>
struct synch_cnt {
uint32_t value;
};
/**
* Semaphore object required for each call
*/
struct sem {
int32_t next_credit; /* Number of credits claimed */
int32_t last_complete; /* Number of returned credits*/
};
#define SYNCH_SEM_NAME(_name) _name##_sem
#define SYNCH_CRED_NAME(_name) _name##_max_credits
/**
* Number of cycles to wait if no credits are available
*/
#define SYNCH_SEM_DEFAULT_POLL 1000
/**
* Declare and initialize a CLS semaphore.
* @param _name Name of the semaphore
* @param _cnt Max number of credits
*
* @note CLS based semaphore should only be used for synchronization within
* an island.
*/
#define SEM_CLS_DECLARE(_name, _cnt) \
__export __shared __cls struct sem SYNCH_SEM_NAME(_name); \
static const uint32_t SYNCH_CRED_NAME(_name) = _cnt;
/**
* Wrapper to take a semaphore.
* @param _name Name of the semaphore
* @param _poll_interval Cycles to wait if no credits are available
*
* @note poll_interval must be less than 0x00100000 (1<<20), see sleep().
* Start with SYNCH_SEM_DEFAULT_POLL. Increase if there is high
* contention for credits.
*/
#define SEM_WAIT(_name, _poll_interval) \
sem_cls_wait(&SYNCH_SEM_NAME(_name), SYNCH_CRED_NAME(_name), \
_poll_interval);
/**
* Wrapper to give a semaphore.
* @param _name Name of the semaphore
*/
#define SEM_POST(_name) \
sem_cls_post(&SYNCH_SEM_NAME(_name));
/**
* Reset DRAM synch counter.
* @param s Synch counter
* @param cnt Reset value
*/
__intrinsic void synch_cnt_dram_reset(__dram struct synch_cnt *s, uint32_t cnt);
/**
* Ack DRAM synch counter.
* @param s Synch counter
*/
__intrinsic void synch_cnt_dram_ack(__dram struct synch_cnt *s);
/**
* Poll DRAM synch counter.
* @param s Synch counter
*
* Poll synch counter and return non-nil if not zero.
*/
__intrinsic int synch_cnt_dram_poll(__dram struct synch_cnt *s);
/**
* Wait for DRAM synch counter to reach zero.
* @param s Synch counter
*/
__intrinsic void synch_cnt_dram_wait(__dram struct synch_cnt *s);
/**
* Take a semaphore. Users should use the SEM_WAIT() macro.
* @param sem Semaphore handle
* @param max_credits Max number of credits available
* @param poll_interval Cycles to wait if no credits are available
*
* @note poll_interval must be less than 0x00100000 (1<<20), see sleep().
* Start with SYNCH_SEM_DEFAULT_POLL. Increase if there is high
* contention for credits.
* @note This function will handle credit claims in order.
*/
__intrinsic void sem_cls_wait(__cls struct sem *sem, const uint32_t max_credits,
uint32_t poll_interval);
/**
* Give a semaphore. Users should use the SEM_POST() macro.
* @param sem Semaphore handle
*
* @note Users must call sem_cls_wait() before sem_cls_post().
*/
__intrinsic void sem_cls_post(__cls struct sem *sem);
#endif /* !_STD__SYNCH_H_ */
| 29.890625 | 80 | 0.692629 | [
"object"
] |
632e6ffdb56ff3164c5d4dcd8cddb159dc5611f5 | 1,629 | h | C | src/seed_searcher_common.h | metaVariable/ghostz | 273cc1efe6278f8012fa9232d854e392b467477f | [
"BSD-2-Clause"
] | null | null | null | src/seed_searcher_common.h | metaVariable/ghostz | 273cc1efe6278f8012fa9232d854e392b467477f | [
"BSD-2-Clause"
] | null | null | null | src/seed_searcher_common.h | metaVariable/ghostz | 273cc1efe6278f8012fa9232d854e392b467477f | [
"BSD-2-Clause"
] | null | null | null | /*
* seed_searcher_common.h
*
* Created on: 2014/05/13
* Author: shu
*/
#ifndef SEED_SEARCHER_COMMON_H_
#define SEED_SEARCHER_COMMON_H_
#include "reduced_alphabet_variable_hash_function.h"
class SeedSearcherCommon {
public:
typedef int Distance;
typedef ReducedAlphabetVariableHashFunction HashFunction;
typedef HashFunction::Hash Hash;
static SeedSearcherCommon::Distance CalculateDistance(
const AlphabetCoder::Code *subsequence0_center,
const AlphabetCoder::Code *subsequence1_center,
const uint32_t sequence_length,
const std::vector<AlphabetCoder::Code> &redueced_code_map);
static uint32_t CalculateSeedPosition(uint32_t hashed_sequence_start,
uint32_t hashed_sequence_length);
private:
};
inline SeedSearcherCommon::Distance SeedSearcherCommon::CalculateDistance(
const AlphabetCoder::Code *subsequence0_center,
const AlphabetCoder::Code *subsequence1_center,
const uint32_t sequence_length,
const std::vector<AlphabetCoder::Code> &redueced_code_map) {
const uint32_t foward_direction = sequence_length / 2;
uint32_t mismatch_count = 0;
const AlphabetCoder::Code *subsequence0 = subsequence0_center
- foward_direction;
const AlphabetCoder::Code *subsequence1 = subsequence1_center
- foward_direction;
for (uint32_t i = 0; i < sequence_length; ++i) {
#if 0
std::cout << int(redueced_code_map[subsequence0[i]]) << ","
<< int(redueced_code_map[subsequence1[i]]) << std::endl;
#endif
mismatch_count +=
(redueced_code_map[subsequence0[i]]
!= redueced_code_map[subsequence1[i]]) ? 1 : 0;
}
return mismatch_count;
}
#endif /* SEED_SEARCHER_COMMON_H_ */
| 29.618182 | 74 | 0.774095 | [
"vector"
] |
632f6809c27a4fd83af6885e8f925b0e724bdec8 | 643 | h | C | src/ip_address.h | chistopat/otus_cpp_ipfilter | 492da4756b43fc31325436a9680928fa7d52374d | [
"MIT"
] | null | null | null | src/ip_address.h | chistopat/otus_cpp_ipfilter | 492da4756b43fc31325436a9680928fa7d52374d | [
"MIT"
] | null | null | null | src/ip_address.h | chistopat/otus_cpp_ipfilter | 492da4756b43fc31325436a9680928fa7d52374d | [
"MIT"
] | null | null | null | //
// "Copyright [2020] <Copyright chistopat>
//
#pragma once
#include <array>
#include <algorithm>
#include <cinttypes>
#include <sstream>
#include <string>
#include "./helper.h"
class IpAddress {
public:
explicit IpAddress(const std::string &data);
std::string AsString() const;
const std::array<uint8_t, 4> &AsOctets() const;
uint32_t AsDec() const;
private:
union {
std::array<uint8_t, 4> octets;
uint32_t inet_addr;
} ip_address;
};
std::vector<int> ParseAddress(const std::string& data);
bool operator<(const IpAddress &lhs, const IpAddress &rhs);
bool operator>(const IpAddress &lhs, const IpAddress &rhs);
| 19.484848 | 59 | 0.699844 | [
"vector"
] |
6335327b6baf75168a778353cf4576c7c7866df6 | 4,831 | c | C | llvm/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/OrcV2CBindingsIRTransforms.c | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | llvm/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/OrcV2CBindingsIRTransforms.c | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | llvm/examples/OrcV2Examples/OrcV2CBindingsIRTransforms/OrcV2CBindingsIRTransforms.c | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | //===- OrcV2CBindingsDumpObjects.c - Dump JIT'd objects to disk via C API -===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// To run the demo build 'OrcV2CBindingsDumpObjects', then run the built
// program. It will execute as for OrcV2CBindingsBasicUsage, but will write
// a single JIT'd object out to the working directory.
//
// Try experimenting with the DumpDir and IdentifierOverride arguments to
// LLVMOrcCreateDumpObjects.
//
//===----------------------------------------------------------------------===//
#include "llvm-c/Core.h"
#include "llvm-c/Error.h"
#include "llvm-c/Initialization.h"
#include "llvm-c/LLJIT.h"
#include "llvm-c/Support.h"
#include "llvm-c/Target.h"
#include "llvm-c/Transforms/Scalar.h"
#include <stdio.h>
int handleError(LLVMErrorRef Err) {
char *ErrMsg = LLVMGetErrorMessage(Err);
fprintf(stderr, "Error: %s\n", ErrMsg);
LLVMDisposeErrorMessage(ErrMsg);
return 1;
}
LLVMOrcThreadSafeModuleRef createDemoModule() {
LLVMOrcThreadSafeContextRef TSCtx = LLVMOrcCreateNewThreadSafeContext();
LLVMContextRef Ctx = LLVMOrcThreadSafeContextGetContext(TSCtx);
LLVMModuleRef M = LLVMModuleCreateWithNameInContext("demo", Ctx);
LLVMTypeRef ParamTypes[] = {LLVMInt32Type(), LLVMInt32Type()};
LLVMTypeRef SumFunctionType =
LLVMFunctionType(LLVMInt32Type(), ParamTypes, 2, 0);
LLVMValueRef SumFunction = LLVMAddFunction(M, "sum", SumFunctionType);
LLVMBasicBlockRef EntryBB = LLVMAppendBasicBlock(SumFunction, "entry");
LLVMBuilderRef Builder = LLVMCreateBuilder();
LLVMPositionBuilderAtEnd(Builder, EntryBB);
LLVMValueRef SumArg0 = LLVMGetParam(SumFunction, 0);
LLVMValueRef SumArg1 = LLVMGetParam(SumFunction, 1);
LLVMValueRef Result = LLVMBuildAdd(Builder, SumArg0, SumArg1, "result");
LLVMBuildRet(Builder, Result);
LLVMOrcThreadSafeModuleRef TSM = LLVMOrcCreateNewThreadSafeModule(M, TSCtx);
LLVMOrcDisposeThreadSafeContext(TSCtx);
return TSM;
}
LLVMErrorRef myModuleTransform(void *Ctx, LLVMModuleRef Mod) {
LLVMPassManagerRef PM = LLVMCreatePassManager();
LLVMAddInstructionCombiningPass(PM);
LLVMRunPassManager(PM, Mod);
LLVMDisposePassManager(PM);
return LLVMErrorSuccess;
}
LLVMErrorRef transform(void *Ctx, LLVMOrcThreadSafeModuleRef *ModInOut,
LLVMOrcMaterializationResponsibilityRef MR) {
return LLVMOrcThreadSafeModuleWithModuleDo(*ModInOut, myModuleTransform, Ctx);
}
int main(int argc, char *argv[]) {
int MainResult = 0;
LLVMParseCommandLineOptions(argc, (const char **)argv, "");
LLVMInitializeCore(LLVMGetGlobalPassRegistry());
LLVMInitializeNativeTarget();
LLVMInitializeNativeAsmPrinter();
// Create a DumpObjects instance to use when dumping objects to disk.
LLVMOrcDumpObjectsRef DumpObjects = LLVMOrcCreateDumpObjects("", "");
// Create the JIT instance.
LLVMOrcLLJITRef J;
{
LLVMErrorRef Err;
if ((Err = LLVMOrcCreateLLJIT(&J, 0))) {
MainResult = handleError(Err);
goto llvm_shutdown;
}
}
// Use TransformLayer to set IR transform.
{
LLVMOrcIRTransformLayerRef TL = LLVMOrcLLJITGetIRTransformLayer(J);
LLVMOrcIRTransformLayerSetTransform(TL, *transform, NULL);
}
// Create our demo module.
LLVMOrcThreadSafeModuleRef TSM = createDemoModule();
// Add our demo module to the JIT.
{
LLVMOrcJITDylibRef MainJD = LLVMOrcLLJITGetMainJITDylib(J);
LLVMErrorRef Err;
if ((Err = LLVMOrcLLJITAddLLVMIRModule(J, MainJD, TSM))) {
// If adding the ThreadSafeModule fails then we need to clean it up
// ourselves. If adding it succeeds the JIT will manage the memory.
LLVMOrcDisposeThreadSafeModule(TSM);
MainResult = handleError(Err);
goto jit_cleanup;
}
}
// Look up the address of our demo entry point.
LLVMOrcJITTargetAddress SumAddr;
{
LLVMErrorRef Err;
if ((Err = LLVMOrcLLJITLookup(J, &SumAddr, "sum"))) {
MainResult = handleError(Err);
goto jit_cleanup;
}
}
// If we made it here then everything succeeded. Execute our JIT'd code.
int32_t (*Sum)(int32_t, int32_t) = (int32_t(*)(int32_t, int32_t))SumAddr;
int32_t Result = Sum(1, 2);
// Print the result.
printf("1 + 2 = %i\n", Result);
jit_cleanup:
// Destroy our JIT instance.
{
LLVMErrorRef Err;
if ((Err = LLVMOrcDisposeLLJIT(J))) {
int NewFailureResult = handleError(Err);
if (MainResult == 0)
MainResult = NewFailureResult;
}
}
llvm_shutdown:
// Destroy our DumpObjects instance.
LLVMOrcDisposeDumpObjects(DumpObjects);
// Shut down LLVM.
LLVMShutdown();
return MainResult;
}
| 31.993377 | 80 | 0.704202 | [
"object",
"transform"
] |
63427ff3cb656ab8408d0e2eb931a7f1dcb991c7 | 3,947 | h | C | iraf.v2161/vendor/x11iraf/obm/ObmW/Xraw/SmeBSBP.h | ysBach/irafdocgen | b11fcd75cc44b01ae69c9c399e650ec100167a54 | [
"MIT"
] | 2 | 2019-12-01T15:19:09.000Z | 2019-12-02T16:48:42.000Z | obm/ObmW/Xraw/SmeBSBP.h | olebole/irafterm | e87478d848c051a1b181ac949078bea223eac225 | [
"MIT"
] | 1 | 2019-11-30T13:48:50.000Z | 2019-12-02T19:40:25.000Z | iraf.v2161/vendor/x11iraf/obm/ObmW/Xraw/SmeBSBP.h | ysBach/irafdocgen | b11fcd75cc44b01ae69c9c399e650ec100167a54 | [
"MIT"
] | null | null | null | /*
* $XConsortium: SmeBSBP.h,v 1.6 89/12/11 15:20:15 kit Exp $
*
* Copyright 1989 Massachusetts Institute of Technology
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of M.I.T. not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. M.I.T. makes no representations about the
* suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*
* M.I.T. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL M.I.T.
* BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Author: Chris D. Peterson, MIT X Consortium
*/
/*
* SmeP.h - Private definitions for Sme object
*
*/
#ifndef _XawSmeBSBP_h
#define _XawSmeBSBP_h
/***********************************************************************
*
* Sme Object Private Data
*
***********************************************************************/
#include <X11/Xraw/SmeP.h>
#include <X11/Xraw/SmeBSB.h>
/************************************************************
*
* New fields for the Sme Object class record.
*
************************************************************/
typedef struct _SmeBSBClassPart {
XtPointer extension;
} SmeBSBClassPart;
/* Full class record declaration */
typedef struct _SmeBSBClassRec {
RectObjClassPart rect_class;
SmeClassPart sme_class;
SmeBSBClassPart sme_bsb_class;
} SmeBSBClassRec;
extern SmeBSBClassRec smeBSBClassRec;
/* New fields for the Sme Object record */
typedef struct {
/* resources */
String label; /* The entry label. */
int vert_space; /* Extra vert space to leave, */
/* as a percentage of the font height */
/* of the label. */
Pixmap left_bitmap;
Pixmap right_bitmap; /* Bitmaps to show. */
Dimension left_margin;
Dimension right_margin; /* Left and right margins. */
Pixel foreground; /* Foreground color. */
Pixel mfore;
XFontStruct * font; /* The font to show label in. */
XtJustify justify; /* Justification for the label. */
Boolean state;
Boolean switched;
XtPointer user_data;
/* private resources. */
Boolean set_values_area_cleared; /* Remember if we need to unhighlight. */
GC norm_gc; /* noral color gc. */
GC rev_gc; /* reverse color gc. */
GC norm_gray_gc; /* Normal color (grayed out) gc. */
GC invert_gc; /* gc for flipping colors. */
GC mfore_gc;
Dimension left_bitmap_width; /* size of each bitmap. */
Dimension left_bitmap_height;
Dimension right_bitmap_width;
Dimension right_bitmap_height;
} SmeBSBPart;
/****************************************************************
*
* Full instance record declaration
*
****************************************************************/
typedef struct _SmeBSBRec {
ObjectPart object;
RectObjPart rectangle;
SmePart sme;
SmeBSBPart sme_bsb;
} SmeBSBRec;
/************************************************************
*
* Private declarations.
*
************************************************************/
#endif /* _XawSmeBSBP_h */
| 32.352459 | 79 | 0.576387 | [
"object"
] |
63443c0c3ab148637743471ea36cb8e2b8be6ca2 | 2,970 | h | C | arbitrary_format/xml_formatters/declaration_formatter.h | Zbyl/ArbitraryFormatSerializer | cd4844f43d9bbf039bb19c1f9e931e99c4571368 | [
"Apache-2.0"
] | 8 | 2016-02-23T01:22:13.000Z | 2021-08-11T21:21:54.000Z | arbitrary_format/xml_formatters/declaration_formatter.h | Zbyl/ArbitraryFormatSerializer | cd4844f43d9bbf039bb19c1f9e931e99c4571368 | [
"Apache-2.0"
] | null | null | null | arbitrary_format/xml_formatters/declaration_formatter.h | Zbyl/ArbitraryFormatSerializer | cd4844f43d9bbf039bb19c1f9e931e99c4571368 | [
"Apache-2.0"
] | 3 | 2016-03-24T14:30:58.000Z | 2018-04-29T17:53:25.000Z | /////////////////////////////////////////////////////////////////////////////
/// ArbitraryFormatSerializer
/// Library for serializing data in arbitrary formats.
///
/// declaration_formatter.h
///
/// This file contains declaration_formatter that formats xml declaration.
///
/// Distributed under Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
/// (c) 2016 Zbigniew Skowron, zbychs@gmail.com
///
/////////////////////////////////////////////////////////////////////////////
#ifndef ArbitraryFormatSerializer_declaration_formatter_H
#define ArbitraryFormatSerializer_declaration_formatter_H
#include <arbitrary_format/xml_formatters/lexical_stringizer.h>
#include <arbitrary_format/serialization_exceptions.h>
#include <string>
#include <vector>
#include <type_traits>
#include <boost/optional.hpp>
#include <boost/algorithm/string.hpp>
namespace arbitrary_format
{
namespace xml
{
template<typename ValueStringizer = lexical_stringizer>
class declaration_formatter
{
private:
ValueStringizer value_stringizer;
public:
explicit declaration_formatter(ValueStringizer value_stringizer = ValueStringizer())
: value_stringizer(value_stringizer)
{
}
template<typename T, typename XmlDocument>
void save(XmlDocument& xmlDocument, const T& encoding) const
{
auto docElement = xmlDocument.getDocumentElement();
if (!docElement.isEmpty())
{
BOOST_THROW_EXCEPTION(serialization_exception() << errinfo_description("xml declaration must be the first node of the document."));
}
std::string value;
value_stringizer.save(value, encoding);
auto xmlDeclaration = docElement.addElement(boost::none, true);
auto version = xmlDeclaration.addAttribute("version");
auto encodingAttrib = xmlDeclaration.addAttribute("encoding");
version.setTextContent("1.0");
encodingAttrib.setTextContent(value);
}
template<typename T, typename XmlDocument>
void load(XmlDocument& xmlDocument, T& encoding) const
{
auto docElement = xmlDocument.getDocumentElement();
auto xmlDeclaration = docElement.eatElement(boost::none, true);
if (!xmlDeclaration.isDeclaration())
{
BOOST_THROW_EXCEPTION(serialization_exception() << errinfo_description("Document should start with an xml declaration."));
}
auto encodingAttr = xmlDeclaration.eatAttribute("encoding", false);
auto encodingText = encodingAttr.eatTextContent();
value_stringizer.load(encodingText, encoding);
}
};
template<typename ValueStringizer = lexical_stringizer>
declaration_formatter<ValueStringizer> create_declaration_formatter(ValueStringizer value_stringizer = ValueStringizer())
{
return declaration_formatter<ValueStringizer>(value_stringizer);
}
} // namespace xml
} // namespace arbitrary_format
#endif // ArbitraryFormatSerializer_declaration_formatter_H
| 33 | 143 | 0.702357 | [
"vector"
] |
63477b58433ecd7a525bed9805bf0fa127899f7f | 949 | h | C | EngineLayer/PrecursorSearchModes/DotMassDiffAcceptor.h | edgargabriel/HPCMetaMorpheus | 160cc269464b8e563fa2f62f6843690b6a2533ee | [
"MIT"
] | 2 | 2020-09-10T19:14:20.000Z | 2021-09-11T16:36:56.000Z | EngineLayer/PrecursorSearchModes/DotMassDiffAcceptor.h | edgargabriel/HPCMetaMorpheus | 160cc269464b8e563fa2f62f6843690b6a2533ee | [
"MIT"
] | null | null | null | EngineLayer/PrecursorSearchModes/DotMassDiffAcceptor.h | edgargabriel/HPCMetaMorpheus | 160cc269464b8e563fa2f62f6843690b6a2533ee | [
"MIT"
] | 3 | 2020-09-11T01:19:47.000Z | 2021-09-02T02:05:01.000Z | #pragma once
#include "MassDiffAcceptor.h"
#include <string>
#include <vector>
#include "MzLibUtil.h"
#include "AllowedIntervalWithNotch.h"
using namespace MzLibUtil;
namespace EngineLayer
{
class DotMassDiffAcceptor : public MassDiffAcceptor
{
private:
std::vector<double> AcceptableSortedMassShifts;
Tolerance * const tolerance;
public:
virtual ~DotMassDiffAcceptor()
{
delete tolerance;
}
DotMassDiffAcceptor(const std::string &FileNameAddition, std::vector<double> &acceptableMassShifts, Tolerance *tol);
int Accepts(double scanPrecursorMass, double peptideMass) override;
std::vector<AllowedIntervalWithNotch*> GetAllowedPrecursorMassIntervalsFromTheoreticalMass(double peptideMonoisotopicMass) override;
std::vector<AllowedIntervalWithNotch*> GetAllowedPrecursorMassIntervalsFromObservedMass(double peptideMonoisotopicMass) override;
std::string ToString();
std::string ToProseString() override;
};
}
| 24.333333 | 134 | 0.796628 | [
"vector"
] |
63513c85f33ac7f96a54e6895519314efa5e8ac3 | 1,570 | h | C | modules/v2x/fusion/apps/common/ft_definitions.h | jzjonah/apollo | bc534789dc0548bf2d27f8d72fe255d5c5e4f951 | [
"Apache-2.0"
] | 22,688 | 2017-07-04T23:17:19.000Z | 2022-03-31T18:56:48.000Z | modules/v2x/fusion/apps/common/ft_definitions.h | Songjiarui3313/apollo | df9113ae656e28e5374db32529d68e59455058a0 | [
"Apache-2.0"
] | 4,804 | 2017-07-04T22:30:12.000Z | 2022-03-31T12:58:21.000Z | modules/v2x/fusion/apps/common/ft_definitions.h | Songjiarui3313/apollo | df9113ae656e28e5374db32529d68e59455058a0 | [
"Apache-2.0"
] | 9,985 | 2017-07-04T22:01:17.000Z | 2022-03-31T14:18:16.000Z | /******************************************************************************
* Copyright 2020 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#pragma once
#include <memory>
#include "modules/localization/proto/localization.pb.h"
#include "modules/perception/proto/perception_obstacle.pb.h"
#include "modules/v2x/proto/v2x_obstacles.pb.h"
#include "modules/v2x/fusion/libs/common/v2x_object.h"
namespace apollo {
namespace v2x {
namespace ft {
using apollo::localization::LocalizationEstimate;
using apollo::perception::PerceptionObstacle;
using apollo::perception::PerceptionObstacles;
using apollo::v2x::V2XObstacle;
using apollo::v2x::V2XObstacles;
using apollo::v2x::ft::base::Object;
using PerceptionObstaclesPtr = std::shared_ptr<PerceptionObstacles>;
using V2XObstaclesPtr = std::shared_ptr<V2XObstacles>;
using StatusPtr = std::shared_ptr<LocalizationEstimate>;
} // namespace ft
} // namespace v2x
} // namespace apollo
| 34.888889 | 79 | 0.694268 | [
"object"
] |
63524b18809bfe2f35ab97f6f87bac4e3ba09397 | 1,617 | h | C | Classes/FastEasyMapping/Core/Deserializer/FEMManagedObjectDeserializer.h | hthoang88/hbutils | 09f302ff5f0bdae3120673ebbb64d4bc2cc36120 | [
"MIT"
] | null | null | null | Classes/FastEasyMapping/Core/Deserializer/FEMManagedObjectDeserializer.h | hthoang88/hbutils | 09f302ff5f0bdae3120673ebbb64d4bc2cc36120 | [
"MIT"
] | null | null | null | Classes/FastEasyMapping/Core/Deserializer/FEMManagedObjectDeserializer.h | hthoang88/hbutils | 09f302ff5f0bdae3120673ebbb64d4bc2cc36120 | [
"MIT"
] | null | null | null | // For License please refer to LICENSE file in the root of FastEasyMapping project
#import <Foundation/Foundation.h>
@class FEMManagedObjectMapping, NSManagedObject, NSFetchRequest, NSManagedObjectContext;
@interface FEMManagedObjectDeserializer : NSObject
+ (id)deserializeObjectExternalRepresentation:(NSDictionary *)externalRepresentation
usingMapping:(FEMManagedObjectMapping *)mapping
context:(NSManagedObjectContext *)context;
+ (id)fillObject:(NSManagedObject *)object fromExternalRepresentation:(NSDictionary *)externalRepresentation usingMapping:(FEMManagedObjectMapping *)mapping;
/** Get an array of managed objects from an external representation. If the objectMapping has
a primary key existing objects will be updated. This method is slow and it doesn't
delete obsolete objects, use
syncArrayOfObjectsFromExternalRepresentation:withMapping:fetchRequest:inManagedObjectContext:
instead.
*/
+ (NSArray *)deserializeCollectionExternalRepresentation:(NSArray *)externalRepresentation
usingMapping:(FEMManagedObjectMapping *)mapping
context:(NSManagedObjectContext *)context;
+ (NSArray *)synchronizeCollectionExternalRepresentation:(NSArray *)externalRepresentation
usingMapping:(FEMManagedObjectMapping *)mapping
predicate:(NSPredicate *)predicate
context:(NSManagedObjectContext *)context;
@end | 53.9 | 157 | 0.688312 | [
"object"
] |
63549f244c0bee2047c2f4cb69e483701795424d | 662 | h | C | net/DiskCache.h | wenfeifei/miniblink49 | 2ed562ff70130485148d94b0e5f4c343da0c2ba4 | [
"Apache-2.0"
] | 5,964 | 2016-09-27T03:46:29.000Z | 2022-03-31T16:25:27.000Z | net/DiskCache.h | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 459 | 2016-09-29T00:51:38.000Z | 2022-03-07T14:37:46.000Z | net/DiskCache.h | w4454962/miniblink49 | b294b6eacb3333659bf7b94d670d96edeeba14c0 | [
"Apache-2.0"
] | 1,006 | 2016-09-27T05:17:27.000Z | 2022-03-30T02:46:51.000Z |
#ifndef net_DiskCache_h
#define net_DiskCache_h
#include "third_party/WebKit/Source/wtf/Vector.h"
#include "third_party/WebKit/Source/wtf/text/WTFString.h"
#include "net/FileSystem.h"
#include <vector>
namespace blink {
class KURL;
}
namespace base {
class ListValue;
}
namespace net {
struct DiskCacheItem {
std::vector<char> content;
String mime;
};
class DiskCache {
public:
DiskCache();
~DiskCache();
void saveMemoryCache();
void initFromJsonFile();
DiskCacheItem* getCacheUrlItem(const blink::KURL& kurl);
private:
base::ListValue* m_cacheList;
};
}
#endif // net_DiskCache_h | 16.55 | 61 | 0.676737 | [
"vector"
] |
63580db42e5ca3ea4a2b176da8d7523cce7078b0 | 10,507 | c | C | src/idl/grids/call_grids.c | chris-torrence/ms2gt | 4553106ad11a25328fc3dcdf8ad1a8c446f4a234 | [
"MIT"
] | 2 | 2021-09-29T15:19:00.000Z | 2022-02-16T12:06:26.000Z | src/idl/grids/call_grids.c | chris-torrence/ms2gt | 4553106ad11a25328fc3dcdf8ad1a8c446f4a234 | [
"MIT"
] | null | null | null | src/idl/grids/call_grids.c | chris-torrence/ms2gt | 4553106ad11a25328fc3dcdf8ad1a8c446f4a234 | [
"MIT"
] | 4 | 2020-04-14T20:42:02.000Z | 2021-05-24T16:50:25.000Z | /*========================================================================
* call_grids - IDL call_external interface to mapx library routines
*
* Functions in this file serve as an interface between IDL and mapx library
* functions.
* The functions contained here are:
* call_init_grid
* call_forward_grid
* call_inverse_grid
* call_close_grid
* 14-Mar-2001 Terry Haran tharan@colorado.edu 303-492-1847
* National Snow & Ice Data Center, University of Colorado, Boulder
*========================================================================*/
static const char call_grids_c_rcsid[] = "$Header: /export/data/ms2gth/src/idl/grids/call_grids.c,v 1.7 2003/04/28 22:08:35 haran Exp $";
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include "export.h"
#include "define.h"
#include "mapx.h"
#include "grids.h"
#include "call_grids.h"
char *id_call_grids(void)
{
return((char *)call_grids_c_rcsid);
}
/*------------------------------------------------------------------------
* call_init_grid - call init_grid()
*
* This function is called from an IDL program with the following statement:
*
* ERROR = call_external('call_grids.so', 'call_init_grid', $
* gpd_filename, gcs)
*
* input : gpd_filename - string containing the name of gpd filename
* to be opened.
*
* output: gcs - grid_class_struct structure to be initialized.
*
* result: 1 if success.
* 0 if error opening or initializing grid_class structure.
*
*------------------------------------------------------------------------*/
long call_init_grid(short argc, void *argv[])
{
/*
* parameters passed in from IDL
*/
IDL_STRING *gpd_filename;
grid_class_struct *gcs;
/*
* local parameters
*/
grid_class *grid;
mapx_class *mapx;
/*
* Check that correct number of parameters was passed
*/
if (argc != 2)
return 0;
/*
* Cast passed parameters to local vars
*/
gpd_filename = (IDL_STRING *)argv[0];
gcs = (grid_class_struct *)argv[1];
/*
* Call the function
*/
grid = init_grid(gpd_filename->s);
/*
* Check that the grid was initialized successfully
*/
if (grid == NULL)
return 0;
/*
* Copy data from grid_class instance to grid_class_struct instance
*/
gcs->grid_class_ptr = (IDL_LONG)grid;
gcs->map_origin_col = grid->map_origin_col;
gcs->map_origin_row = grid->map_origin_row;
gcs->cols_per_map_unit = grid->cols_per_map_unit;
gcs->rows_per_map_unit = grid->rows_per_map_unit;
gcs->cols = grid->cols;
gcs->rows = grid->rows;
gcs->gpd_filename.s = grid->gpd_filename;
gcs->gpd_filename.slen = strlen(grid->gpd_filename);
mapx = grid->mapx;
gcs->lat0 = mapx->lat0;
gcs->lon0 = mapx->lon0;
gcs->lat1 = mapx->lat1;
gcs->lon1 = mapx->lon1;
gcs->rotation = mapx->rotation;
gcs->scale = mapx->scale;
gcs->south = mapx->south;
gcs->north = mapx->north;
gcs->west = mapx->west;
gcs->east = mapx->east;
gcs->center_lat = mapx->center_lat;
gcs->center_lon = mapx->center_lon;
gcs->label_lat = mapx->label_lat;
gcs->label_lon = mapx->label_lon;
gcs->lat_interval = mapx->lat_interval;
gcs->lon_interval = mapx->lon_interval;
gcs->cil_detail = mapx->cil_detail;
gcs->bdy_detail = mapx->bdy_detail;
gcs->riv_detail = mapx->riv_detail;
gcs->equatorial_radius = mapx->equatorial_radius;
gcs->polar_radius = mapx->polar_radius;
gcs->eccentricity = mapx->eccentricity;
gcs->eccentricity_squared = mapx->e2;
gcs->x0 = mapx->x0;
gcs->y0 = mapx->y0;
gcs->false_easting = mapx->false_easting;
gcs->false_northing = mapx->false_northing;
gcs->center_scale = mapx->center_scale;
gcs->utm_zone = mapx->utm_zone;
gcs->isin_nzone = mapx->isin_nzone;
gcs->isin_justify = mapx->isin_justify;
gcs->projection_name.s = mapx->projection_name;
gcs->projection_name.slen = strlen(mapx->projection_name);
return 1;
}
/*------------------------------------------------------------------------
* call_forward_grid - call forward_grid()
*
* This function is called from an IDL program with the following statement:
*
* ERROR = call_external('call_grids.so', 'call_forward_grid', $
* gcs, n, lat, lon, col, row, status)
*
* input: gcs - grid_class_struct structure to be initialized.
*
* n - long integer number of elements in each input and output
* array.
* lat - double array of latitude values.
* lon - double array of longitude values.
*
* output:col - double array of column numbers.
* row - double array of row numbers.
* status - byte array of status values:
* 1 if corresponding col and row are in the grid.
* 0 otherwise.
* NOTE: all input and output arrays must have been allocated prior to
* calling call_forward_grid.
*
* result: 1 if success.
* 0 otherwise.
*
*------------------------------------------------------------------------*/
long call_forward_grid(short argc, void *argv[])
{
/*
* parameters passed in from IDL
*/
grid_class_struct *gcs;
IDL_LONG n;
double *lat;
double *lon;
double *col;
double *row;
byte1 *status;
/*
* local variables
*/
int i;
grid_class *grid;
/*
* Check that correct number of parameters was passed
*/
if (argc != 7)
return 0;
/*
* Cast passed parameters to local vars
*/
gcs = (grid_class_struct *)argv[0];
n = *((IDL_LONG *)argv[1]);
lat = (double *)argv[2];
lon = (double *)argv[3];
col = (double *)argv[4];
row = (double *)argv[5];
status = (byte1 *)argv[6];
/*
* Get pointer to grid object instance
*/
grid = (grid_class *)(gcs->grid_class_ptr);
/*
* Loop through for each array element
*/
for (i = 0; i < n; i++) {
/*
* Call the function
*/
status[i] = (byte1)forward_grid(grid, lat[i], lon[i], &col[i], &row[i]);
}
return 1;
}
/*------------------------------------------------------------------------
* call_inverse_grid - call inverse_grid()
*
* This function is called from an IDL program with the following statement:
*
* ERROR = call_external('call_grids.so', 'call_inverse_grid', $
* gcs, n, lcol, row, lat, lon, status)
*
* input: gcs - grid_class_struct structure to be initialized.
*
* n - long integer number of elements in each input and output
* array.
* col - double array of column numbers.
* row - double array of row numbers.
*
* output:lat - double array of latitude values.
* lon - double array of longitude values.
* status - byte array of status values:
* 1 if corresponding lat and lon are within the map
* boundaries.
* 0 otherwise.
* NOTE: all input and output arrays must have been allocated prior to
* calling call_inverse_grid.
*
* result: 1 if success.
* 0 otherwise.
*
*------------------------------------------------------------------------*/
long call_inverse_grid(short argc, void *argv[])
{
/*
* parameters passed in from IDL
*/
grid_class_struct *gcs;
IDL_LONG n;
double *col;
double *row;
double *lat;
double *lon;
byte1 *status;
/*
* local variables
*/
int i;
grid_class *grid;
/*
* Check that correct number of parameters was passed
*/
if (argc != 7)
return 0;
/*
* Cast passed parameters to local vars
*/
gcs = (grid_class_struct *)argv[0];
n = *((IDL_LONG *)argv[1]);
col = (double *)argv[2];
row = (double *)argv[3];
lat = (double *)argv[4];
lon = (double *)argv[5];
status = (byte1 *)argv[6];
/*
* Get pointer to grid object instance
*/
grid = (grid_class *)(gcs->grid_class_ptr);
/*
* Loop through for each array element
*/
for (i = 0; i < n; i++) {
/*
* Call the function
*/
status[i] = (byte1)inverse_grid(grid, col[i], row[i], &lat[i], &lon[i]);
}
return 1;
}
/*------------------------------------------------------------------------
* call_close_grid - call close_grid()
*
* This function is called from an IDL program with the following statement:
*
* ERROR = call_external('call_grids.so', 'call_close_grid', $
* gcs)
*
* input: gcs - grid_class_struct structure to be closed.
*
* output: gcs - grid_class_struct structure after being closed.
*
* result: 1 if success.
* 0 if error closing grid_class structure.
*
*------------------------------------------------------------------------*/
long call_close_grid(short argc, void *argv[])
{
/*
* parameters passed in from IDL
*/
grid_class_struct *gcs;
/*
* Check that correct number of parameters was passed
*/
if (argc != 1)
return 0;
/*
* Cast passed parameters to local vars
*/
gcs = (grid_class_struct *)argv[0];
/*
* Call the function
*/
close_grid((grid_class *)(gcs->grid_class_ptr));
/*
* Copy data from grid_class instance to grid_class_struct instance
*/
gcs->grid_class_ptr = (IDL_LONG)0;
gcs->map_origin_col = 0.0;
gcs->map_origin_row = 0.0;
gcs->cols_per_map_unit = 0.0;
gcs->rows_per_map_unit = 0.0;
gcs->cols = (IDL_LONG)0;
gcs->rows = (IDL_LONG)0;
gcs->gpd_filename.s = NULL;
gcs->gpd_filename.slen = 0;
gcs->lat0 = 0.0;
gcs->lon0 = 0.0;
gcs->lat1 = 0.0;
gcs->lon1 = 0.0;
gcs->rotation = 0.0;
gcs->scale = 0.0;
gcs->south = 0.0;
gcs->north = 0.0;
gcs->west = 0.0;
gcs->east = 0.0;
gcs->center_lat = 0.0;
gcs->center_lon = 0.0;
gcs->label_lat = 0.0;
gcs->label_lon = 0.0;
gcs->lat_interval = 0.0;
gcs->lon_interval = 0.0;
gcs->cil_detail = (IDL_LONG)0;
gcs->bdy_detail = (IDL_LONG)0;
gcs->riv_detail = (IDL_LONG)0;
gcs->equatorial_radius = (double)0.0;
gcs->polar_radius = (double)0.0;
gcs->eccentricity = (double)0.0;
gcs->eccentricity_squared = (double)0.0;
gcs->x0 = 0.0;
gcs->y0 = 0.0;
gcs->false_easting = 0.0;
gcs->false_northing = 0.0;
gcs->center_scale = 0.0;
gcs->utm_zone = (IDL_LONG)0;
gcs->isin_nzone = (IDL_LONG)0;
gcs->isin_justify = (IDL_LONG)0;
gcs->projection_name.s = NULL;
gcs->projection_name.slen = 0;
return 1;
}
| 24.549065 | 137 | 0.573142 | [
"object"
] |
635c6952e6ccf97ec53e2035a484a7bcd65c0c8a | 823 | h | C | Lumos/src/AI/PathNodePriorityQueue.h | rzvxa/Lumos | d1d94a8461cdfb4d52c45120c3327c772982bf2e | [
"MIT"
] | 2 | 2020-10-21T06:52:11.000Z | 2020-11-16T01:21:00.000Z | Lumos/src/AI/PathNodePriorityQueue.h | rzvxa/Lumos | d1d94a8461cdfb4d52c45120c3327c772982bf2e | [
"MIT"
] | null | null | null | Lumos/src/AI/PathNodePriorityQueue.h | rzvxa/Lumos | d1d94a8461cdfb4d52c45120c3327c772982bf2e | [
"MIT"
] | null | null | null | #pragma once
#include "QueueablePathNode.h"
#include <vector>
namespace Lumos
{
class PathNodePriorityQueue : public std::vector<QueueablePathNode *>
{
public:
PathNodePriorityQueue()
: std::vector<QueueablePathNode *>()
//, m_comp()
{
//std::make_heap(begin(), end(), m_comp);
}
void Push(QueueablePathNode *item)
{
push_back(item);
//std::push_heap(begin(), end(), m_comp);
}
void Pop()
{
//std::pop_heap(begin(), end(), m_comp);
pop_back();
}
QueueablePathNode *Top() const
{
return front();
}
std::vector<QueueablePathNode *>::const_iterator Find(QueueablePathNode *item) const
{
return std::find(cbegin(), cend(), item);
}
void Update()
{
//std::make_heap(begin(), end(), m_comp);
}
private:
//greater_ptr<QueueablePathNode> m_comp;
};
} | 17.145833 | 86 | 0.63548 | [
"vector"
] |
635d1982f2f8413ec8d5d2c839f721d88e6031d1 | 4,209 | h | C | Pods/Headers/Public/FirebaseDatabase/FirebaseDatabase/FIRDataSnapshot.h | krgauravjha78/FirebaseSwift | e933f0de3f92ea1ac467bc88001818718652860e | [
"MIT"
] | 17 | 2016-09-30T14:56:32.000Z | 2022-01-13T07:50:06.000Z | Pods/Headers/Public/FirebaseDatabase/FirebaseDatabase/FIRDataSnapshot.h | krgauravjha78/FirebaseSwift | e933f0de3f92ea1ac467bc88001818718652860e | [
"MIT"
] | 26 | 2016-10-18T19:11:22.000Z | 2018-01-22T16:26:12.000Z | AppRR/ios/Pods/Headers/Public/FirebaseDatabase/FirebaseDatabase/FIRDataSnapshot.h | Hug0Albert0/Restaurant-Roulette | cca5466ce5dbd04418e106974a40bbbaa41fc4fc | [
"MIT"
] | 10 | 2016-10-19T00:47:37.000Z | 2020-03-09T17:58:54.000Z | /*
* Copyright 2017 Google
*
* 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.
*/
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class FIRDatabaseReference;
/**
* A FIRDataSnapshot contains data from a Firebase Database location. Any time you read
* Firebase data, you receive the data as a FIRDataSnapshot.
*
* FIRDataSnapshots are passed to the blocks you attach with observeEventType:withBlock: or observeSingleEvent:withBlock:.
* They are efficiently-generated immutable copies of the data at a Firebase Database location.
* They can't be modified and will never change. To modify data at a location,
* use a FIRDatabaseReference (e.g. with setValue:).
*/
NS_SWIFT_NAME(DataSnapshot)
@interface FIRDataSnapshot : NSObject
#pragma mark - Navigating and inspecting a snapshot
/**
* Gets a FIRDataSnapshot for the location at the specified relative path.
* The relative path can either be a simple child key (e.g. 'fred')
* or a deeper slash-separated path (e.g. 'fred/name/first'). If the child
* location has no data, an empty FIRDataSnapshot is returned.
*
* @param childPathString A relative path to the location of child data.
* @return The FIRDataSnapshot for the child location.
*/
- (FIRDataSnapshot *)childSnapshotForPath:(NSString *)childPathString;
/**
* Return YES if the specified child exists.
*
* @param childPathString A relative path to the location of a potential child.
* @return YES if data exists at the specified childPathString, else NO.
*/
- (BOOL) hasChild:(NSString *)childPathString;
/**
* Return YES if the DataSnapshot has any children.
*
* @return YES if this snapshot has any children, else NO.
*/
- (BOOL) hasChildren;
/**
* Return YES if the DataSnapshot contains a non-null value.
*
* @return YES if this snapshot contains a non-null value, else NO.
*/
- (BOOL) exists;
#pragma mark - Data export
/**
* Returns the raw value at this location, coupled with any metadata, such as priority.
*
* Priorities, where they exist, are accessible under the ".priority" key in instances of NSDictionary.
* For leaf locations with priorities, the value will be under the ".value" key.
*/
- (id __nullable) valueInExportFormat;
#pragma mark - Properties
/**
* Returns the contents of this data snapshot as native types.
*
* Data types returned:
* + NSDictionary
* + NSArray
* + NSNumber (also includes booleans)
* + NSString
*
* @return The data as a native object.
*/
@property (strong, readonly, nonatomic, nullable) id value;
/**
* Gets the number of children for this DataSnapshot.
*
* @return An integer indicating the number of children.
*/
@property (readonly, nonatomic) NSUInteger childrenCount;
/**
* Gets a FIRDatabaseReference for the location that this data came from.
*
* @return A FIRDatabaseReference instance for the location of this data.
*/
@property (nonatomic, readonly, strong) FIRDatabaseReference * ref;
/**
* The key of the location that generated this FIRDataSnapshot.
*
* @return An NSString containing the key for the location of this FIRDataSnapshot.
*/
@property (strong, readonly, nonatomic) NSString* key;
/**
* An iterator for snapshots of the child nodes in this snapshot.
* You can use the native for..in syntax:
*
* for (FIRDataSnapshot* child in snapshot.children) {
* ...
* }
*
* @return An NSEnumerator of the children.
*/
@property (strong, readonly, nonatomic) NSEnumerator<FIRDataSnapshot *>* children;
/**
* The priority of the data in this FIRDataSnapshot.
*
* @return The priority as a string, or nil if no priority was set.
*/
@property (strong, readonly, nonatomic, nullable) id priority;
@end
NS_ASSUME_NONNULL_END
| 28.439189 | 122 | 0.733666 | [
"object"
] |
6362ef90b3bfcbcb91e6a6745949a408da1b1d77 | 961 | h | C | structural/src/facade/expression_node.h | rachwal/DesignPatterns | 0645544706c915a69e1ca64addba5cc14453f64c | [
"MIT"
] | 9 | 2016-08-03T16:15:57.000Z | 2021-11-08T13:15:46.000Z | structural/src/facade/expression_node.h | rachwal/DesignPatterns | 0645544706c915a69e1ca64addba5cc14453f64c | [
"MIT"
] | null | null | null | structural/src/facade/expression_node.h | rachwal/DesignPatterns | 0645544706c915a69e1ca64addba5cc14453f64c | [
"MIT"
] | 4 | 2016-08-03T16:16:01.000Z | 2017-12-27T05:14:55.000Z | // Based on "Design Patterns: Elements of Reusable Object-Oriented Software"
// book by Erich Gamma, John Vlissides, Ralph Johnson, and Richard Helm
//
// Created by Bartosz Rachwal. The National Institute of Advanced Industrial Science and Technology, Japan.
#ifndef STRUCTURAL_FACADE_EXPRESSION_NODE_H_
#define STRUCTURAL_FACADE_EXPRESSION_NODE_H_
#include "program_node_interface.h"
#include "expression_node_interface.h"
#include "../../../operational/src/iterator/list.h"
namespace structural
{
namespace facade
{
class ExpressionNode : public ProgramNodeInterface, public ExpressionNodeInterface
{
public:
ExpressionNode();
virtual void GetSourcePosition(int& line, int& index) override;
virtual void Add(ProgramNodeInterface*) override;
virtual void Remove(ProgramNodeInterface*) override;
virtual void Traverse(CodeGeneratorInterface&) override;
protected:
operational::iterator::List<ProgramNodeInterface*>* children_;
};
}
}
#endif
| 25.289474 | 107 | 0.797086 | [
"object"
] |
6363968258d13092901c2e2345e8cf9f5fbc4638 | 908 | h | C | src/records/principal_generator.h | raytheonbbn/tc-ta3-api-bindings-cpp | 98c0646e89de52ac8e65948699450fded402c254 | [
"MIT-0"
] | null | null | null | src/records/principal_generator.h | raytheonbbn/tc-ta3-api-bindings-cpp | 98c0646e89de52ac8e65948699450fded402c254 | [
"MIT-0"
] | null | null | null | src/records/principal_generator.h | raytheonbbn/tc-ta3-api-bindings-cpp | 98c0646e89de52ac8e65948699450fded402c254 | [
"MIT-0"
] | 1 | 2020-11-27T20:15:34.000Z | 2020-11-27T20:15:34.000Z | // Copyright (c) 2020 Raytheon BBN Technologies Corp.
// See LICENSE.txt for details.
#ifndef TC_RECORDS_PRINCIPAL_GENERATOR_H_
#define TC_RECORDS_PRINCIPAL_GENERATOR_H_
#include "records/optional_element_generator.h"
#include "records/property_generator.h"
#include "records/uuid_generator.h"
#include "tc_schema/cdm.h"
namespace tc_records {
class PrincipalGenerator {
OptionalElementGenerator oeg;
PropertyGenerator pg;
UuidGenerator ug;
tc_schema::PrincipalType getRandomType();
std::string getRandomUserId();
tc_schema::Principal::username_t getRandomUsername();
std::vector<std::string> getRandomGroupIds();
tc_schema::Principal::properties_t getRandomProperties(uint32_t numKvPairs);
public:
PrincipalGenerator();
tc_schema::Principal getRandomPrincipal(uint32_t numKvPairs);
};
} // namespace tc_records
#endif // TC_RECORDS_PRINCIPAL_GENERATOR_H_
| 27.515152 | 80 | 0.780837 | [
"vector"
] |
636b895f23d5ef409342d32ab03e9ce87d6c9a21 | 766 | h | C | Jiffy Mac/JiffyMac.h | RyanBluth/Jiffy-Mac | e8ce4aeec1b652b7c943d5a33f82648c4afd6114 | [
"MIT"
] | null | null | null | Jiffy Mac/JiffyMac.h | RyanBluth/Jiffy-Mac | e8ce4aeec1b652b7c943d5a33f82648c4afd6114 | [
"MIT"
] | null | null | null | Jiffy Mac/JiffyMac.h | RyanBluth/Jiffy-Mac | e8ce4aeec1b652b7c943d5a33f82648c4afd6114 | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <vector>
#define in ,
#define for_each(x, y) for(auto x : y){
#define is ==
#define is_not !=
#define isnt !=
#define do_many_(x) for(int _it_=0; _it_<x; ++_it_){
#define _end ;}
#define then_ ){
#define when if(
#define and &&
#define or ||
#define also ;
#define elif else if
#define otherwise_when else if(
#define otherwise else{
#define println(x) std::cout<<x<<std::endl
#define let auto
#define be =
#define getp ->
#define get .
#define set
#define to =
#define as(i, t) (t)i
#define nc_p(x, y) (x != nullptr ? x : y)
#define nc(x, y) (y == NULL ? x : y)
#define less_than <
#define greater_than >
#define less_than_or_equal <=
#define greater_than_or_equal >=
#define array_of(x) std::vector<x>
#define declare | 21.277778 | 52 | 0.673629 | [
"vector"
] |
636dbb68359d6108cd12d91f1faa633049418f44 | 3,177 | h | C | export/release/windows/obj/include/HitGraph.h | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | export/release/windows/obj/include/HitGraph.h | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | export/release/windows/obj/include/HitGraph.h | bobisdabbing/Vs-The-United-Lands-stable | 0807e58b6d8ad1440bdd350bf006b37a1b7ca9b5 | [
"MIT"
] | null | null | null | // Generated by Haxe 4.1.5
#ifndef INCLUDED_HitGraph
#define INCLUDED_HitGraph
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#ifndef INCLUDED_openfl_display_Sprite
#include <openfl/display/Sprite.h>
#endif
HX_DECLARE_CLASS0(HitGraph)
HX_DECLARE_CLASS2(openfl,display,Bitmap)
HX_DECLARE_CLASS2(openfl,display,DisplayObject)
HX_DECLARE_CLASS2(openfl,display,DisplayObjectContainer)
HX_DECLARE_CLASS2(openfl,display,IBitmapDrawable)
HX_DECLARE_CLASS2(openfl,display,InteractiveObject)
HX_DECLARE_CLASS2(openfl,display,Shape)
HX_DECLARE_CLASS2(openfl,display,Sprite)
HX_DECLARE_CLASS2(openfl,events,EventDispatcher)
HX_DECLARE_CLASS2(openfl,events,IEventDispatcher)
HX_DECLARE_CLASS2(openfl,text,TextField)
class HXCPP_CLASS_ATTRIBUTES HitGraph_obj : public ::openfl::display::Sprite_obj
{
public:
typedef ::openfl::display::Sprite_obj super;
typedef HitGraph_obj OBJ_;
HitGraph_obj();
public:
enum { _hx_ClassId = 0x0e8c1adb };
void __construct(int X,int Y,int Width,int Height);
inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="HitGraph")
{ return ::hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return ::hx::Object::operator new(inSize+extra,true,"HitGraph"); }
static ::hx::ObjectPtr< HitGraph_obj > __new(int X,int Y,int Width,int Height);
static ::hx::ObjectPtr< HitGraph_obj > __alloc(::hx::Ctx *_hx_ctx,int X,int Y,int Width,int Height);
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(::hx::DynamicArray inArgs);
//~HitGraph_obj();
HX_DO_RTTI_ALL;
::hx::Val __Field(const ::String &inString, ::hx::PropertyAccess inCallProp);
static bool __GetStatic(const ::String &inString, Dynamic &outValue, ::hx::PropertyAccess inCallProp);
::hx::Val __SetField(const ::String &inString,const ::hx::Val &inValue, ::hx::PropertyAccess inCallProp);
void __GetFields(Array< ::String> &outFields);
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_("HitGraph",1b,28,fb,b2); }
static ::openfl::text::TextField createTextField(::hx::Null< Float > X,::hx::Null< Float > Y,::hx::Null< int > Color,::hx::Null< int > Size);
static ::Dynamic createTextField_dyn();
static ::Dynamic initTextField( ::Dynamic tf,::hx::Null< Float > X,::hx::Null< Float > Y,::hx::Null< int > Color,::hx::Null< int > Size);
static ::Dynamic initTextField_dyn();
Float minValue;
Float maxValue;
bool showInput;
int graphColor;
::cpp::VirtualArray history;
::openfl::display::Bitmap bitmap;
Float ts;
::openfl::display::Shape _axis;
int _width;
int _height;
int _labelWidth;
void drawAxes();
::Dynamic drawAxes_dyn();
void drawJudgementLine(Float ms);
::Dynamic drawJudgementLine_dyn();
void drawGraph();
::Dynamic drawGraph_dyn();
Float fitX(Float x);
::Dynamic fitX_dyn();
void addToHistory(Float diff,::String judge,Float time);
::Dynamic addToHistory_dyn();
void update();
::Dynamic update_dyn();
};
#endif /* INCLUDED_HitGraph */
| 32.418367 | 148 | 0.738118 | [
"object",
"shape"
] |
636f8824d0613278f387b9dc651971d7e542c06a | 493 | h | C | src/utils/missilestorage.h | MacDumi/Tie-Invaders | 59edd031020bc85fc51cc1faaa3491a264010a24 | [
"MIT"
] | 1 | 2021-11-14T20:56:02.000Z | 2021-11-14T20:56:02.000Z | src/utils/missilestorage.h | MacDumi/Tie-Invaders | 59edd031020bc85fc51cc1faaa3491a264010a24 | [
"MIT"
] | null | null | null | src/utils/missilestorage.h | MacDumi/Tie-Invaders | 59edd031020bc85fc51cc1faaa3491a264010a24 | [
"MIT"
] | null | null | null | #pragma once
#include <SFML/Graphics.hpp>
#include <gameobjects/missile.h>
#include <vector>
class MissileStorage
{
private:
std::vector<Missile> m_missiles;
static MissileStorage* m_s_Instance;
MissileStorage();
public:
MissileStorage (MissileStorage const &) = delete;
MissileStorage &operator=(MissileStorage const &) = delete;
static MissileStorage *instance();
void addMissile(float startX, float starY, int type);
std::vector<Missile>* getMisiles();
};
| 25.947368 | 63 | 0.724138 | [
"vector"
] |
637855d5349f150c3a519cd76d7e7ffbfad25e07 | 2,635 | h | C | NILButton/NILButton.h | NI92/NILButton | 529855c2021b728aa8d8f1d9124e4d4a1ddfa6d8 | [
"MIT",
"Unlicense"
] | null | null | null | NILButton/NILButton.h | NI92/NILButton | 529855c2021b728aa8d8f1d9124e4d4a1ddfa6d8 | [
"MIT",
"Unlicense"
] | null | null | null | NILButton/NILButton.h | NI92/NILButton | 529855c2021b728aa8d8f1d9124e4d4a1ddfa6d8 | [
"MIT",
"Unlicense"
] | null | null | null | //
// NILButton.h
//
// Created by Nick Ignatenko Leonidevich on 2017-03-11.
// Copyright © 2017 Nick Ignatenko. All rights reserved.
//
// Button class.
#import <SpriteKit/SpriteKit.h>
@class NILButton;
@protocol NILButtonDelegate <NSObject>
@optional
- (void)touchedDownButton:(NILButton *)button;
- (void)touchedUpButton:(NILButton *)button;
- (void)touchMovedButton:(NILButton *)button;
- (void)touchCancelledButton:(NILButton *)button;
@end
// Button types
typedef NS_ENUM (NSUInteger, NILButtonType) {
NILButtonTypePlain, // Size & color (or background image).
NILButtonTypeIcon, // Size, color (or background image) & an icon.
NILButtonTypeLabel, // Size, color (or background image) & label.
NILButtonTypeIconAndLabel // Size, color (or background image), icon & label.
};
// Button object positions
typedef NS_ENUM (NSUInteger, NILButtonObjectPosition) {
NILButtonObjectPositionTop,
NILButtonObjectPositionMiddle,
NILButtonObjectPositionBottom
};
@interface NILButton : SKSpriteNode
@property (weak, nonatomic) id <NILButtonDelegate> delegate;
@property (nonatomic) NILButtonType type; // Defines what objects are available within the button.
// Background & icon images
@property (strong, nonatomic) NSString *backgroundDefaultStateImageName; // Default class object background image. Ignores nil & @"".
@property (strong, nonatomic) NSString *backgroundSelectedStateImageName; // Selected class object background image. Ignores nil & @"".
@property (strong, nonatomic) NSString *iconDefaultStateImageName; // Default icon image. Ignores nil & @"".
@property (strong, nonatomic) NSString *iconSelectedStateImageName; // Selected icon image. Ignores nil & @"".
@property (nonatomic) NILButtonObjectPosition iconPosition; // Icon position within the button itself.
@property (nonatomic) CGSize iconSize; // Icons size.
// Label
@property (strong, nonatomic) NSString *labelText;
@property (strong, nonatomic) UIFont *labelFont;
@property (nonatomic) SKColor *labelDefaultStateFontColor; // Default label text color.
@property (nonatomic) SKColor *labelSelectedStateFontColor; // Selected label text color.
@property (nonatomic) NILButtonObjectPosition labelPosition; // Label position within the button itself.
// SFX
@property (nonatomic) BOOL sfxEnabled;
@property (strong, nonatomic) NSString *selectedButtonSFX; // Input nil or @"" to turn it off (stop it from activating).
@property (strong, nonatomic) NSString *releasedButtonSFX; // Same thing can be done here.
// Init
- (instancetype)initWithType:(NILButtonType)type size:(CGSize)size;
@end
| 37.112676 | 135 | 0.753321 | [
"object"
] |
637b490fead2b84594009a37b244a517ccd6fbcb | 1,540 | h | C | HotPatcher/Source/HotPatcherEditor/Private/Cooker/MultiCooker/SHotPatcherMultiCookerPage.h | stlnkm/HotPatcher | 777520bafb60bf1a1fef48b702f105b461e6d924 | [
"MIT"
] | 1 | 2020-08-04T11:07:15.000Z | 2020-08-04T11:07:15.000Z | HotPatcher/Source/HotPatcherEditor/Private/Cooker/MultiCooker/SHotPatcherMultiCookerPage.h | stlnkm/HotPatcher | 777520bafb60bf1a1fef48b702f105b461e6d924 | [
"MIT"
] | null | null | null | HotPatcher/Source/HotPatcherEditor/Private/Cooker/MultiCooker/SHotPatcherMultiCookerPage.h | stlnkm/HotPatcher | 777520bafb60bf1a1fef48b702f105b461e6d924 | [
"MIT"
] | null | null | null | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Model/FHotPatcherCreatePatchModel.h"
#include "Cooker/SHotPatcherCookerBase.h"
#include "Cooker/MultiCooker/FMultiCookerSettings.h"
// engine header
#include "Templates/SharedPointer.h"
#include "IStructureDetailsView.h"
/**
* Implements the cooked platforms panel.
*/
class SHotPatcherMultiCookerPage
: public SHotPatcherCookerBase
{
public:
SLATE_BEGIN_ARGS(SHotPatcherMultiCookerPage) { }
SLATE_END_ARGS()
public:
/**
* Constructs the widget.
*
* @param InArgs The Slate argument list.
*/
void Construct( const FArguments& InArgs,TSharedPtr<FHotPatcherCookerModel> InCreateModel);
public:
virtual void ImportConfig();
virtual void ExportConfig()const;
virtual void ResetConfig();
virtual void DoGenerate();
virtual void ImportProjectConfig()override;
virtual FString GetMissionName() override{return TEXT("MultiCooker");}
virtual FMultiCookerSettings* GetConfigSettings()override{return CookerSettings.Get();};
protected:
void CreateExportFilterListView();
bool CanCook()const;
FReply RunCook();
virtual FText GetGenerateTooltipText() const override;
private:
class UMultiCookerProxy* MultiCookerProxy;
class UMissionNotificationProxy* MissionNotifyProay;
// TSharedPtr<FHotPatcherCreatePatchModel> mCreatePatchModel;
/** Settings view ui element ptr */
TSharedPtr<IStructureDetailsView> SettingsView;
TSharedPtr<FMultiCookerSettings> CookerSettings;
};
| 27.017544 | 93 | 0.764935 | [
"model"
] |
637f42e26f2e28c4abdfb6789d5ad3e54fcb4be9 | 10,521 | h | C | source/core/sound/WaveIntf.h | metarin/krkrv | 42e5c23483539e2bc1e8d6858548cf13165494e1 | [
"BSD-3-Clause"
] | 48 | 2019-07-11T04:32:41.000Z | 2022-03-20T10:42:47.000Z | source/core/sound/WaveIntf.h | metarin/krkrv | 42e5c23483539e2bc1e8d6858548cf13165494e1 | [
"BSD-3-Clause"
] | 8 | 2019-07-11T02:35:16.000Z | 2021-03-09T06:31:48.000Z | source/core/sound/WaveIntf.h | metarin/krkrv | 42e5c23483539e2bc1e8d6858548cf13165494e1 | [
"BSD-3-Clause"
] | 7 | 2020-07-09T05:32:13.000Z | 2022-03-26T16:52:52.000Z | //---------------------------------------------------------------------------
/*
TVP2 ( T Visual Presenter 2 ) A script authoring tool
Copyright (C) 2000 W.Dee <dee@kikyou.info> and contributors
See details of license at "license.txt"
*/
//---------------------------------------------------------------------------
// Wave Player interface
//---------------------------------------------------------------------------
#ifndef WaveIntfH
#define WaveIntfH
#include "tjsNative.h"
#include "SoundBufferBaseIntf.h"
#include "tjsUtils.h"
typedef float D3DVALUE;
/*[*/
//---------------------------------------------------------------------------
// Sound Global Focus Mode
//---------------------------------------------------------------------------
enum tTVPSoundGlobalFocusMode
{
/*0*/ sgfmNeverMute, // never mutes
/*1*/ sgfmMuteOnMinimize, // will mute on the application minimize
/*2*/ sgfmMuteOnDeactivate // will mute on the application deactivation
};
//---------------------------------------------------------------------------
/*]*/
//---------------------------------------------------------------------------
// GUID identifying WAVEFORMATEXTENSIBLE sub format
//---------------------------------------------------------------------------
extern tjs_uint8 TVP_GUID_KSDATAFORMAT_SUBTYPE_PCM[16];
extern tjs_uint8 TVP_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT[16];
//---------------------------------------------------------------------------
/*[*/
//---------------------------------------------------------------------------
// PCM data format (internal use)
//---------------------------------------------------------------------------
struct tTVPWaveFormat
{
tjs_uint SamplesPerSec; // sample granule per sec
tjs_uint Channels;
tjs_uint BitsPerSample; // per one sample
tjs_uint BytesPerSample; // per one sample
tjs_uint64 TotalSamples; // in sample granule; unknown for zero
tjs_uint64 TotalTime; // in ms; unknown for zero
tjs_uint32 SpeakerConfig; // bitwise OR of SPEAKER_* constants
bool IsFloat; // true if the data is IEEE floating point
bool Seekable;
};
//---------------------------------------------------------------------------
/*]*/
//---------------------------------------------------------------------------
// PCM bit depth converter
//---------------------------------------------------------------------------
TJS_EXP_FUNC_DEF(void, TVPConvertPCMTo16bits, (tjs_int16 *output, const void *input, const tTVPWaveFormat &format, tjs_int count, bool downmix));
TJS_EXP_FUNC_DEF(void, TVPConvertPCMTo16bits, (tjs_int16 *output, const void *input, tjs_int channels, tjs_int bytespersample, tjs_int bitspersample, bool isfloat, tjs_int count, bool downmix));
TJS_EXP_FUNC_DEF(void, TVPConvertPCMToFloat, (float *output, const void *input, tjs_int channels, tjs_int bytespersample, tjs_int bitspersample, bool isfloat, tjs_int count));
TJS_EXP_FUNC_DEF(void, TVPConvertPCMToFloat, (float *output, const void *input, const tTVPWaveFormat &format, tjs_int count));
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// tTVPWaveDecoder interface
//---------------------------------------------------------------------------
class tTVPWaveDecoder
{
public:
virtual ~tTVPWaveDecoder() {};
virtual void GetFormat(tTVPWaveFormat & format) = 0;
/* Retrieve PCM format, etc. */
virtual bool Render(void *buf, tjs_uint bufsamplelen, tjs_uint& rendered) = 0;
/*
Render PCM from current position.
where "buf" is a destination buffer, "bufsamplelen" is the buffer's
length in sample granule, "rendered" is to be an actual number of
written sample granule.
returns whether the decoding is to be continued.
because "redered" can be lesser than "bufsamplelen", the player
should not end until the returned value becomes false.
*/
virtual bool SetPosition(tjs_uint64 samplepos) = 0;
/*
Seek to "samplepos". "samplepos" must be given in unit of sample granule.
returns whether the seeking is succeeded.
*/
virtual bool DesiredFormat(const tTVPWaveFormat & format) { return false; }
};
//---------------------------------------------------------------------------
class tTVPWaveDecoderCreator
{
public:
virtual tTVPWaveDecoder * Create(const ttstr & storagename,
const ttstr &extension) = 0;
/*
Create tTVPWaveDecoder instance. returns NULL if failed.
*/
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// tTVPWaveDecoder interface management
//---------------------------------------------------------------------------
extern void TVPRegisterWaveDecoderCreator(tTVPWaveDecoderCreator *d);
extern void TVPUnregisterWaveDecoderCreator(tTVPWaveDecoderCreator *d);
extern tTVPWaveDecoder * TVPCreateWaveDecoder(const ttstr & storagename);
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// interface for basic filter management
//---------------------------------------------------------------------------
class tTVPSampleAndLabelSource;
class iTVPBasicWaveFilter
{
public:
// recreate filter. filter will remain owned by the each filter instance.
virtual tTVPSampleAndLabelSource * Recreate(tTVPSampleAndLabelSource * source) = 0;
virtual void Clear(void) = 0;
virtual void Update(void) = 0;
virtual void Reset(void) = 0;
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// tTJSNI_BaseWaveSoundBuffer
//---------------------------------------------------------------------------
class tTVPWaveLoopManager;
class tTJSNI_BaseWaveSoundBuffer : public tTJSNI_SoundBuffer
{
typedef tTJSNI_SoundBuffer inherited;
iTJSDispatch2 * WaveFlagsObject;
iTJSDispatch2 * WaveLabelsObject;
struct tFilterObjectAndInterface
{
tTJSVariant Filter; // filter object
iTVPBasicWaveFilter * Interface; // filter interface
tFilterObjectAndInterface(
const tTJSVariant & filter,
iTVPBasicWaveFilter * interf) :
Filter(filter), Interface(interf) {;}
};
std::vector<tFilterObjectAndInterface> FilterInterfaces; // backupped filter interface array
protected:
tTVPWaveLoopManager * LoopManager; // will be set by tTJSNI_WaveSoundBuffer
tTVPSampleAndLabelSource * FilterOutput; // filter output
iTJSDispatch2 * Filters; // wave filters array (TJS2 array object)
public:
tTJSNI_BaseWaveSoundBuffer();
tjs_error TJS_INTF_METHOD
Construct(tjs_int numparams, tTJSVariant **param,
iTJSDispatch2 *tjs_obj);
void TJS_INTF_METHOD Invalidate();
protected:
void InvokeLabelEvent(const ttstr & name);
void RecreateWaveLabelsObject();
void RebuildFilterChain();
void ClearFilterChain();
void ResetFilterChain();
void UpdateFilterChain();
public:
iTJSDispatch2 * GetWaveFlagsObjectNoAddRef();
iTJSDispatch2 * GetWaveLabelsObjectNoAddRef();
tTVPWaveLoopManager * GetWaveLoopManager() const { return LoopManager; }
iTJSDispatch2 * GetFiltersNoAddRef() { return Filters; }
// method
virtual void Open(const ttstr & storagename) = 0;
virtual void Play() = 0;
virtual void Stop() = 0;
virtual void SetPos(float x, float y, float z) = 0;
// properties
virtual tjs_uint64 GetPosition() = 0;
virtual void SetPosition(tjs_uint64 pos) = 0;
virtual tjs_uint64 GetSamplePosition() = 0;
virtual void SetSamplePosition(tjs_uint64 pos) = 0;
virtual bool GetPaused() const = 0;
virtual void SetPaused(bool b) = 0;
virtual tjs_uint64 GetTotalTime() = 0;
virtual void SetLooping(bool b) = 0;
virtual bool GetLooping() const = 0;
virtual void SetVolume(tjs_int v) = 0;
virtual tjs_int GetVolume() const = 0;
virtual void SetVolume2(tjs_int v) = 0;
virtual tjs_int GetVolume2() const = 0;
virtual void SetPan(tjs_int v) = 0;
virtual tjs_int GetPan() const = 0;
virtual void SetPosX(float v) = 0;
virtual float GetPosX() const = 0;
virtual void SetPosY(float v) = 0;
virtual float GetPosY() const = 0;
virtual void SetPosZ(float v) = 0;
virtual float GetPosZ() const = 0;
virtual tjs_int GetFrequency() const = 0;
virtual void SetFrequency(tjs_int freq) = 0;
virtual tjs_int GetBitsPerSample() const = 0;
virtual tjs_int GetChannels() const = 0;
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// tTJSNC_WaveSoundBuffer : TJS WaveSoundBuffer class
//---------------------------------------------------------------------------
class tTJSNC_WaveSoundBuffer : public tTJSNativeClass
{
public:
tTJSNC_WaveSoundBuffer();
static tjs_uint32 ClassID;
typedef tTJSNativeInstance *(*FuncCreateNativeInstance)();
FuncCreateNativeInstance Factory;
protected:
tTJSNativeInstance *CreateNativeInstance() { return Factory(); }
};
//---------------------------------------------------------------------------
extern tTJSNativeClass * TVPCreateNativeClass_SoundBuffer();
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// tTJSNI_WaveFlags : Wave Flags object
//---------------------------------------------------------------------------
class tTJSNI_WaveFlags : public tTJSNativeInstance
{
typedef tTJSNativeInstance inherited;
tTJSNI_BaseWaveSoundBuffer * Buffer;
public:
tTJSNI_WaveFlags();
~tTJSNI_WaveFlags();
tjs_error TJS_INTF_METHOD Construct(tjs_int numparams, tTJSVariant **param,
iTJSDispatch2 *tjs_obj);
void TJS_INTF_METHOD Invalidate();
tTJSNI_BaseWaveSoundBuffer * GetBuffer() const { return Buffer; }
};
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// tTJSNC_WaveFlags : Wave Flags class
//---------------------------------------------------------------------------
class tTJSNC_WaveFlags : public tTJSNativeClass
{
public:
tTJSNC_WaveFlags();
static tjs_uint32 ClassID;
protected:
tTJSNativeInstance *CreateNativeInstance() { return new tTJSNI_WaveFlags(); }
};
//---------------------------------------------------------------------------
iTJSDispatch2 * TVPCreateWaveFlagsObject(iTJSDispatch2 * buffer);
//---------------------------------------------------------------------------
#endif
| 35.187291 | 194 | 0.545005 | [
"render",
"object",
"vector"
] |
6382e7eddaf14c004ba31a2b3ff498d1e38cc178 | 3,936 | h | C | friendsmash_complete/friendSmasher/Library/Math/vec2.h | apportable/FriendSmash | ba2f5f4f52c4a7f48f3f9f2ae5a78a0dfd277b53 | [
"Unlicense"
] | 1 | 2019-03-29T09:43:33.000Z | 2019-03-29T09:43:33.000Z | friendsmash/friendSmasher/Library/Math/vec2.h | VanessaButz/ios-friend-smash | 06b8087fadb2cdf6bb2f00bf8544766d2c277fde | [
"Unlicense"
] | null | null | null | friendsmash/friendSmasher/Library/Math/vec2.h | VanessaButz/ios-friend-smash | 06b8087fadb2cdf6bb2f00bf8544766d2c277fde | [
"Unlicense"
] | null | null | null | /*
* Copyright 2012 Facebook
*
* 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 FRIENDSMASHER_VEC2
#define FRIENDSMASHER_VEC2
namespace FriendSmasher
{
namespace Math
{
class vec2
{
public:
vec2(void) : x(0.0f), y(0.0f) {} ;
vec2(const float broadcast) : x(broadcast), y(broadcast) {};
vec2(const float xin, const float yin) : x(xin), y(yin) {} ;
~vec2(void) {};
// Vector operators
inline vec2 operator + (const vec2 &rhs) const;
inline vec2 operator - (const vec2 &rhs) const;
inline vec2 operator - () const;
inline vec2 operator * (const vec2 &rhs) const;
inline vec2 operator * (const float &rhs) const;
inline vec2 operator / (const float &rhs) const;
inline vec2 operator += (const vec2 &rhs);
inline vec2 operator -= (const vec2 &rhs);
inline bool operator == (const vec2 &rhs) const;
inline bool operator != (const vec2 &rhs) const;
inline vec2 operator *= (const float& rhs);
inline vec2 operator *= (const vec2 &rhs);
inline float operator[] (const int i) const;
inline bool operator < (const vec2 &rhs) const;
inline bool operator <=(const vec2 &rhs) const;
inline bool operator > (const vec2 &rhs) const;
inline bool operator >=(const vec2 &rhs) const;
static vec2 allzero;
static vec2 allone;
static vec2 min;
static vec2 max;
float Length() const;
float Normalise(); // Returns the original length before the normalise operation
void Normalise(const float fLength); // If you've already worked out the length, you can pass it in here to avoid calculating it again.
union
{
struct
{
float x, y;
};
float f[2];
};
};
vec2 vec2::operator + (const vec2 &rhs) const
{
return vec2(this->x + rhs.x, this->y + rhs.y);
}
vec2 vec2::operator - (const vec2 &rhs) const
{
return vec2(this->x - rhs.x, this->y - rhs.y);
}
vec2 vec2::operator - () const
{
return vec2(-this->x, -this->y);
}
vec2 vec2::operator * (const vec2 &rhs) const
{
return vec2(this->x * rhs.x, this->y * rhs.y);
}
vec2 vec2::operator += (const vec2 &rhs)
{
this->x += rhs.x;
this->y += rhs.y;
return *this;
}
vec2 vec2::operator -= (const vec2 &rhs)
{
this->x -= rhs.x;
this->y -= rhs.y;
return *this;
}
bool vec2::operator == (const vec2 &rhs) const
{
return (this->x == rhs.x && this->y == rhs.y );
}
bool vec2::operator != (const vec2 &rhs) const
{
return !(this->x == rhs.x && this->y == rhs.y );
}
vec2 vec2::operator * (const float& rhs) const
{
return vec2( this->x * rhs, this->y * rhs );
}
vec2 vec2::operator / (const float& rhs) const
{
float rcp = 1.0f / rhs;
return vec2( this->x * rcp, this->y * rcp );
}
vec2 vec2::operator *= (const float &rhs)
{
this->x *= rhs;
this->y *= rhs;
return *this;
}
vec2 vec2::operator *= (const vec2 &rhs)
{
this->x *= rhs.x;
this->y *= rhs.y;
return *this;
}
float vec2::operator [](const int i) const
{
return this->f[i];
}
bool vec2::operator< (const vec2 &rhs) const
{
return (x < rhs.x &&
y < rhs.y );
}
bool vec2::operator<=(const vec2 &rhs) const
{
return (x <= rhs.x &&
y <= rhs.y );
}
bool vec2::operator> (const vec2& rhs) const
{
return (x > rhs.x &&
y > rhs.y );
}
bool vec2::operator>=(const vec2& rhs) const
{
return (x >= rhs.x &&
y >= rhs.y );
}
}
}
#endif // namespace FriendSmasher_VEC2 | 21.626374 | 141 | 0.62373 | [
"vector"
] |
638851abe7ffa6cda3df8bb94cacb40c06581ba9 | 20,121 | h | C | src/eplssrc/SN/SSDOSint.h | rknall/openSAFETY | 630495210c5aab1b39884b7b5c8feef62e95f245 | [
"BSD-3-Clause"
] | 2 | 2015-03-15T23:34:03.000Z | 2021-04-14T19:25:51.000Z | src/eplssrc/SN/SSDOSint.h | rknall/openSAFETY | 630495210c5aab1b39884b7b5c8feef62e95f245 | [
"BSD-3-Clause"
] | null | null | null | src/eplssrc/SN/SSDOSint.h | rknall/openSAFETY | 630495210c5aab1b39884b7b5c8feef62e95f245 | [
"BSD-3-Clause"
] | 4 | 2015-01-30T21:53:35.000Z | 2020-09-25T06:23:56.000Z | /**
* @addtogroup SSDOS
* @{
*
*
* @file SSDOSint.h
* This file is the internal header-file of the unit.
*
*
* @copyright Copyright (c) 2009, Bernecker + Rainer Industrie-Elektronik Ges.m.b.H and IXXAT Automation GmbH
* @copyright All rights reserved, Bernecker + Rainer Industrie-Elektronik Ges.m.b.H
* @copyright This source code is free software; you can redistribute it and/or modify it under the terms of the BSD license (according to License.txt).
*
* @author K. Fahrion, IXXAT Automation GmbH
* @author M. Molnar, IXXAT Automation GmbH
*
* <h2>History for SSDOsint.h</h2>
* <table>
* <tr><th>Date</th><th>Author</th><th>Change Description</th></tr>
* <tr><td>03.06.2009</td><td>Hans Pill</td><td>Review SL V10</td></tr>
* </table>
*
*/
#ifndef SSDOSINT_H
#define SSDOSINT_H
/**
* @name Function prototypes for SSDOSupDwnLd.c
* @{
*
***/
/**
* @brief This function initializes the structure with the segment information.
*
* @param b_instNum instance number (not checked, checked in SSC_InitAll() or SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*/
void SSDOS_SegInfoInit(BYTE_B_INSTNUM);
/**
* @brief This function processes a SSDO expedited initiate download request.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
* @param ps_rxBuf reference to received openSAFETY frame to be distributed
* (pointer not checked, only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent
* - otherwise abort response has to be sent with the returned abort code. See SOD_t_ABORT_CODES
*/
UINT32 SSDOS_DwnldInitExpReqProc(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf);
/**
* @brief This function processes a SSDO segmented initiate download request.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxBuf reference to received openSAFETY frame to be distributed
* (pointer not checked, only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent,
* - otherwise abort response has to be sent with the returned abort code. See SOD_t_ABORT_CODES
*/
UINT32 SSDOS_DwnldInitSegReqProc(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf);
/**
* @brief This function generates a SSDOS initiate segmented download response.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxBuf reference to received openSAFETY frame to be distributed (pointer not checked,
* only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @param ps_txBuf reference to openSAFETY frame to be transmitted (pointer not checked, only
* called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent
* - otherwise abort response has to be sent with the returned abort code. See SOD_t_ABORT_CODES
*/
UINT32 SSDOS_DwnldInitSegRespSend(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf,
EPLS_t_FRM *ps_txBuf);
/**
* @brief This function generates a SSDOS initiate expedited download response.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxBuf reference to received openSAFETY frame to be distributed (pointer not checked,
* only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @param ps_txBuf reference to openSAFETY frame to be transmitted (pointer not checked, only called
* with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent,
* - otherwise abort response has to be sent with the returned abort code. See SOD_t_ABORT_CODES
*/
UINT32 SSDOS_DwnldInitExpRespSend(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf,
EPLS_t_FRM *ps_txBuf);
/**
* @brief This function processes a SSDO segmented middle download request.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()),
* valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxBuf reference to received openSAFETY frame to be distributed (pointer not
* checked, only called with reference to struct in processStateReqProc()), valid range: <> NULL,
* see EPLS_t_FRM
*
* @param ps_txBuf reference to openSAFETY frame to be transmitted (pointer not checked,
* only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @param b_echoSaCmd the SOD access command to be sent back (not checked, any value allowed),
* valid range: UINT8
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent,
* - otherwise abort response has to be sent with the returned abort code. See SOD_t_ABORT_CODES
*/
UINT32 SSDOS_DwnldMidSegReqProc(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf,
EPLS_t_FRM *ps_txBuf, UINT8 b_echoSaCmd);
/**
* @brief This function processes a SSDO segmented end download request.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxBuf reference to received openSAFETY frame to be distributed (pointer not checked,
* only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @param ps_txBuf reference to openSAFETY frame to be transmitted (pointer not checked, only
* called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @param b_echoSaCmd the SOD access command to be sent back (not checked, any value allowed), valid range: UINT8
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent,
* - otherwise abort response has to be sent with the returned abort code. See SOD_t_ABORT_CODES
*/
UINT32 SSDOS_DwnldEndSegReqProc(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf,
EPLS_t_FRM *ps_txBuf, UINT8 b_echoSaCmd);
/**
* @brief This function processes a SSDO segmented initiate upload request.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()),
* valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxBuf reference to received openSAFETY frame to be distributed (pointer
* not checked, only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @retval po_seg only relevant if SOD_ABT_NO_ERROR returned,
* - TRUE : segmented upload
* - FALSE : expedited upload (pointer not checked, only called with reference to variable in WfReqInitState()), valid range: TRUE, FALSE
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent,
* - otherwise abort response has to be sent with the returned abort code. See SOD_t_ABORT_CODES
*/
UINT32 SSDOS_UpldInitReqProc(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf,
BOOLEAN *po_seg);
/**
* @brief This function generates a SSDOS initiate expedited upload response.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()),
* valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxBuf reference to received openSAFETY frame to be distributed (pointer not
* checked, only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @param ps_txBuf reference to openSAFETY frame to be transmitted (pointer not checked,
* only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent,
* - otherwise abort response has to be sent with the returned abort code. See SOD_t_ABORT_CODES
*/
UINT32 SSDOS_UpldInitExpRespSend(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf,
EPLS_t_FRM *ps_txBuf);
/**
* @brief This function generates a SSDOS initiate segmented upload response.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()),
* valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxBuf reference to received openSAFETY frame to be distributed (pointer
* not checked, only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @param ps_txBuf reference to openSAFETY frame to be transmitted (pointer not
* checked, only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*/
void SSDOS_UpldInitSegRespSend(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf,
EPLS_t_FRM *ps_txBuf);
/**
* @brief This function processes a SSDO segmented upload request.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()),
* valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxBuf reference to received openSAFETY frame to be distributed (pointer not
* checked, only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @param ps_txBuf reference to openSAFETY frame to be transmitted (pointer not checked,
* only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @retval po_end only relevant if SOD_ABT_NO_ERROR returned,
* - TRUE : end segment
* - FALSE : middle segment (pointer not checked, only called with reference to variable), valid range: TRUE, FALSE
*
* @param b_echoSaCmd the SOD access command to be sent back (not checked, any value allowed), valid range: UINT8
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent,
* - otherwise abort response has to be sent with the returned abort code. See SOD_t_ABORT_CODES
*/
UINT32 SSDOS_UpldSegReqProc(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf,
EPLS_t_FRM *ps_txBuf, BOOLEAN *po_end,
UINT8 b_echoSaCmd);
/** @} */
/**
* @name Function prototypes for SSDOSsodAcs.c
* @{
*/
/**
* @brief This function initializes SOD access structure.
*
* @param b_instNum instance number (not checked, checked in SSC_InitAll() or SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
*/
void SSDOS_SodAcsInit(BYTE_B_INSTNUM);
/**
* @brief This function clears the object data in case of an abort of the segmented download and calls the SOD_Unlock() if the SOD was locked.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
* @param o_abort
* - TRUE : reset because an abort frame was sent or received
* - FALSE : reset because of end of the transfer (not checked, any value allowed), valid range: TRUE, FALSE
*
* @return
* - TRUE - reset of SOD access succeeded
* - FALSE - reset of SOD access failed, FATAL error is already reported
*/
BOOLEAN SSDOS_SodAcsReset(BYTE_B_INSTNUM_ BOOLEAN o_abort);
/**
* @brief This function checks whether the SOD access request in the SSDOC request is valid.
*
* Toggle bit, SOD index and SOD sub-index are checked.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxPyldData reference to the payload data in the received openSAFETY frame
* (pointer not checked, only called with reference to array in DwnldWfReqSegState() or UpldWfReqSegState()),
* valid range: see EPLS_t_FRM
*
* @param o_checkObj objet index subindex is to be checked
*
* @return
* - TRUE - SSDOC Request is valid
* - FALSE - SSDOC Request is invalid
*/
BOOLEAN SSDOS_SodAcsReqValid(BYTE_B_INSTNUM_ const UINT8 *ps_rxPyldData, BOOLEAN const o_checkObj);
/**
* @brief This function gets the data type of the accessed object.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @return data type of the object see EPLS_t_DATATYPE
*/
EPLS_t_DATATYPE SSDOS_SodAcsDataTypeGet(BYTE_B_INSTNUM);
/**
* @brief This function copies SOD index and SOD sub-index from the received SSDOC request.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()),
* valid range: 0 .. <EPLS_cfg_MAX_INSTANCES> - 1
*
* @param ps_rxPyldData reference to the payload data in the received openSAFETY frame
* (pointer not checked, only called with reference to array in WfReqInitState() or SSDOS_UpldInitReqProc()
* or SSDOS_DwnldInitSegReqProc() or SSDOS_DwnldInitExpReqProc()), valid range: see EPLS_t_FRM
*/
void SSDOS_SodAcsIdxCopy(BYTE_B_INSTNUM_ const UINT8 *ps_rxPyldData);
/**
* @brief This function gets the SOD attributes for the corresponding SOD index and SOD sub-index.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxPyldData reference to the payload data in the received openSAFETY frame
* (pointer not checked, only called with reference to array in SSDOS_UpldInitReqProc() or SSDOS_DwnldInitSegReqProc()
* or SSDOS_DwnldInitExpReqProc()), valid range: see EPLS_t_FRM
*
* @param o_readAcs
* - TRUE : read access is requested
* - FALSE : write access is requested (not checked, any value allowed), valid range: TRUE, FALSE
*
* @param pdw_objSize length of the object (pointer not checked, only called with reference to variable in SSDOS_UpldInitReqProc() or SSDOS_DwnldInitSegReqProc() or SSDOS_DwnldInitExpReqProc()), valid range: <> NULL
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent,
* - otherwise abort response has to be sent with the returned abort code. See SOD_t_ABORT_CODES
*/
UINT32 SSDOS_SodAcsAttrGet(BYTE_B_INSTNUM_ const UINT8 *ps_rxPyldData,
BOOLEAN o_readAcs, UINT32 *pdw_objSize);
/**
* @brief This function checks the current SN state. Only in state PREOPERATIONAL an SOD write access is allowed.
*
* In state OPERATIONAL only SOD read access is possible. In case of a shared SOD object to be accessed all instances
* are checked for state OPERATIONAL. Write access to a shared object is only possible in case of no instance of SNs
* is in state OPERATIONAL.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()),
* valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
* @param o_seg
* - TRUE : segmented download
* - FALSE : expedited download (not checked, any value allowed), valid range: TRUE, FALSE
*
* @return
* - TRUE - SOD write access is allowed
* - FALSE - SOD write access is not allowed
*/
BOOLEAN SSDOS_SodAcsWriteAllowed(BYTE_B_INSTNUM_ BOOLEAN o_seg);
/**
* @brief This function converts the data from network format to host format and writes into the SOD.
*
* @param b_instNum instance number (not checked, checked in
* SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
* @param pb_data pointer to the data to be written, (pointer not checked, only called
* with reference to array in SSDOS_DwnldMidSegReqProc() or SSDOS_DwnldEndSegReqProc or SSDOS_DwnldInitExpRespSend()
* or SSDOS_DwnldInitSegRespSend()), valid range: <> NULL
*
* @param dw_offset start offset in bytes of the segment within the data block (not checked,
* checked in SOD_Write()) valid range: UINT32
*
* @param dw_size size in bytes of the segment (not checked, checked in SOD_Write()) valid range: (UINT32)
*
* @param o_actLenSet
* - TRUE : set actual length
* - FALSE : do not set actual length (not checked, any value allowed), valid range: TRUE, FALSE
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent,
* - otherwise abort response has to be sent with the returned abort code.
*/
UINT32 SSDOS_SodAcsWrite(BYTE_B_INSTNUM_ const UINT8 *pb_data, UINT32 dw_offset,
UINT32 dw_size, BOOLEAN o_actLenSet);
/**
* @brief This function reads the data the SOD.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
* @param dw_offset start offset in bytes of the segment within the data block
* (not checked, checked in SOD_Read()), valid range: (UINT32)
* @param dw_size size in bytes of the segment (not checked, checked in
* SOD_Read()), valid range: (UINT32)
* @retval pdw_abortCode abort code, if SOD_ABT_NO_ERROR no abort response has to be sent,
* otherwise abort response has to be sent with the this abort code. (pointer not checked, only called
* with reference to variable in SSDOS_UpldInitReqProc() or SSDOS_UpldSegReqProc()) valid range: <> NULL, see SOD_t_ABORT_CODES
*
* @return
* - <> NULL - pointer to the data, if pdw_abortCode is SOD_ABT_NO_ERROR
* - == NULL - read access failed, see pdw_abortCode
*/
UINT8 *SSDOS_SodAcsRead(BYTE_B_INSTNUM_ UINT32 dw_offset, UINT32 dw_size,
UINT32 *pdw_abortCode);
/**
* @brief This function locks the SOD.
*
* @param b_instNum instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @return
* - if SOD_ABT_NO_ERROR no abort response has to be sent,
* - otherwise abort response has to be sent with the returned abort code.
*/
UINT32 SSDOS_SodAcsLock(BYTE_B_INSTNUM);
/**
* @brief This function assembles a SSDO Service Response for the SOD access except the raw data.
*
* @param b_instNum - instance number (not checked, checked in SSC_ProcessSNMTSSDOFrame()), valid range: 0 .. ( EPLS_cfg_MAX_INSTANCES - 1 )
*
* @param ps_rxBuf reference to received openSAFETY frame to be distributed (pointer not
* checked, only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @param ps_txBuf reference to openSAFETY frame to be transmitted (pointer not checked,
* only called with reference to struct in processStateReqProc()), valid range: <> NULL, see EPLS_t_FRM
*
* @param b_saCmd SOD access command for the response (not checked, any value allowed), valid range: (UINT8)
*
* @param b_respLen length of the response (not checked, any value allowed), valid range: (UINT8)
*
* @param o_insObjInfo index and subindex information is needed in the response
*/
void SSDOS_SodAcsResp(BYTE_B_INSTNUM_ const EPLS_t_FRM *ps_rxBuf,
EPLS_t_FRM *ps_txBuf, UINT8 b_saCmd, UINT8 b_respLen,
BOOLEAN o_insObjInfo);
/** @} */
#endif
/** @} */
| 48.136364 | 230 | 0.697778 | [
"object"
] |
63901d7c5fdaaf65d1b4496bb7fa1b3f557cfb40 | 1,289 | h | C | CharacterComponent.h | thefinalstarman/SimpleEngine | 1df3922732eafa99ba4664b01f8f8d2669bc9e41 | [
"MIT"
] | null | null | null | CharacterComponent.h | thefinalstarman/SimpleEngine | 1df3922732eafa99ba4664b01f8f8d2669bc9e41 | [
"MIT"
] | null | null | null | CharacterComponent.h | thefinalstarman/SimpleEngine | 1df3922732eafa99ba4664b01f8f8d2669bc9e41 | [
"MIT"
] | null | null | null | /*
* CharacterComponent.h
*
* Created on: Aug 7, 2017
* Author: Jordan Richards
*/
#ifndef CHARACTERCOMPONENT_H_
#define CHARACTERCOMPONENT_H_
#include "PhysicsEngine.h"
#include "structures.h"
struct CharacterComponentParams{
double jumpAccelDuration = .1;
double jumpAccel = 60.;
double airDampening = .5;
double maxVelocity = 30.;
double maxAirVelocity = 15.;
CharacterComponentParams() {}
};
class CharacterComponent: public Component{
public:
CharacterComponent(Object* parent, CharacterComponentParams params = CharacterComponentParams(), PhysicsComponent* physicsController = nullptr): Component(parent), controller(physicsController), jumpAccelDuration(params.jumpAccelDuration), jumpAccel(params.jumpAccel), airDampening(params.airDampening), maxVelocity(params.maxVelocity), maxAirVelocity(params.maxAirVelocity) {}
virtual void init();
virtual void destroy(Object*) {}
virtual void update(double dt);
bool isGrounded();
bool isJumping();
void move(double normal);
void jump();
private:
PhysicsComponent* controller;
uint32_t bottom_sensor = -1;
int grounded = 0;
double jumpTime = -1;
double jumpAccelDuration;
double jumpAccel;
double airDampening;
double maxVelocity;
double maxAirVelocity;
};
#endif /* CHARACTERCOMPONENT_H_ */
| 23.87037 | 378 | 0.768037 | [
"object"
] |
639b9bf206d1f3e046164223c9b4360c249b5521 | 182,099 | c | C | backends/asm/optimize_ir.c | dMajoIT/spin2cpp | f2ee655d150c9d69042b2dfaf8cae57123b7702c | [
"MIT"
] | null | null | null | backends/asm/optimize_ir.c | dMajoIT/spin2cpp | f2ee655d150c9d69042b2dfaf8cae57123b7702c | [
"MIT"
] | null | null | null | backends/asm/optimize_ir.c | dMajoIT/spin2cpp | f2ee655d150c9d69042b2dfaf8cae57123b7702c | [
"MIT"
] | null | null | null | //
// IR optimizer
//
// Copyright 2016-2022 Total Spectrum Software Inc.
// see the file COPYING for conditions of redistribution
//
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>
#include <ctype.h>
#include "spinc.h"
#include "outasm.h"
// forward declarations
static int OptimizePeephole2(IRList *irl);
// fcache size in longs; -1 means take a guess
int gl_fcache_size = -1;
//
// helper functions
//
/* IR instructions that have no effect on the generated code */
bool IsDummy(IR *op)
{
switch(op->opc) {
case OPC_COMMENT:
case OPC_LITERAL:
case OPC_CONST:
case OPC_DUMMY:
return true;
default:
return op->cond == COND_FALSE;
}
}
//
// replace an opcode
//
void
ReplaceOpcode(IR *ir, IROpcode op)
{
ir->opc = op;
ir->instr = FindInstrForOpc(op);
}
//
// return TRUE if an instruction uses its destination
// (most do)
//
static bool
InstrReadsDst(IR *ir)
{
switch (ir->opc) {
case OPC_MOV:
case OPC_NEG:
case OPC_NEGC:
case OPC_NEGNC:
case OPC_NEGZ:
case OPC_NEGNZ:
case OPC_ABS:
case OPC_RDBYTE:
case OPC_RDWORD:
case OPC_RDLONG:
case OPC_GETQX:
case OPC_GETQY:
case OPC_GETRND:
case OPC_GETCT:
case OPC_GETNIB:
case OPC_GETBYTE:
case OPC_GETWORD:
case OPC_WRC:
case OPC_WRNC:
case OPC_WRZ:
case OPC_WRNZ:
case OPC_DECOD:
case OPC_ENCOD:
case OPC_BMASK:
case OPC_NOT:
case OPC_ONES:
return false;
case OPC_MUXC:
case OPC_MUXNC:
case OPC_MUXZ:
case OPC_MUXNZ:
if (ir->src && ir->src->kind == IMM_INT && (int32_t)ir->src->val == -1) {
return false;
} else {
return true;
}
default:
break;
}
return true;
}
// recognize instructions that modify their
// destination
// (should only be called on real instructions and OPC_LIVE)
static bool
InstrSetsDst(IR *ir)
{
switch (ir->opc) {
case OPC_LABEL:
case OPC_WRLONG:
case OPC_WRWORD:
case OPC_WRBYTE:
case OPC_QDIV:
case OPC_QFRAC:
case OPC_QMUL:
case OPC_QROTATE:
case OPC_QSQRT:
case OPC_QVECTOR:
case OPC_QLOG:
case OPC_QEXP:
case OPC_DRVH:
case OPC_DRVL:
case OPC_DRVC:
case OPC_DRVNC:
case OPC_DRVZ:
case OPC_DRVNZ:
case OPC_SETQ:
case OPC_SETQ2:
case OPC_TESTB:
case OPC_TESTBN:
return false;
case OPC_CMP:
case OPC_CMPS:
case OPC_TEST:
case OPC_TESTN:
case OPC_GENERIC_NR:
case OPC_GENERIC_NR_NOFLAGS:
case OPC_PUSH:
return (ir->flags & FLAG_WR) != 0;
default:
return (ir->flags & FLAG_NR) == 0;
}
}
// recognizes branch instructions
// jumps and calls are both branches, but sometimes
// we treat them differently
static bool IsJump(IR *ir)
{
switch (ir->opc) {
case OPC_JUMP:
case OPC_REPEAT:
case OPC_DJNZ:
case OPC_REPEAT_END:
case OPC_JMPREL:
case OPC_GENERIC_BRANCH:
case OPC_GENERIC_BRCOND:
return true;
default:
return false;
}
}
static bool IsBranch(IR *ir)
{
return IsJump(ir) || ir->opc == OPC_CALL;
}
static bool IsWrite(IR *ir) {
switch (ir->opc) {
case OPC_WRLONG:
case OPC_WRWORD:
case OPC_WRBYTE:
case OPC_GENERIC:
case OPC_GENERIC_NOFLAGS:
return true;
default:
return false;
}
}
static bool IsRead(IR *ir) {
switch (ir->opc) {
case OPC_RDLONG:
case OPC_RDWORD:
case OPC_RDBYTE:
case OPC_GENERIC:
case OPC_GENERIC_NOFLAGS:
return true;
default:
return false;
}
}
static bool
IsReadWrite(IR *ir)
{
if (!ir) {
return false;
}
switch (ir->opc) {
case OPC_RDBYTE:
case OPC_RDWORD:
case OPC_RDLONG:
case OPC_WRBYTE:
case OPC_WRWORD:
case OPC_WRLONG:
return true;
default:
return false;
}
}
static bool
IsLabel(IR *ir)
{
return ir->opc == OPC_LABEL;
}
// return TRUE if an instruction modifies a register
bool
InstrModifies(IR *ir, Operand *reg)
{
Operand *dst = ir->dst;
Operand *src = ir->src;
if (reg && reg->kind == REG_SUBREG) {
reg = (Operand *)reg->name;
}
if (dst && dst->kind == REG_SUBREG) {
dst = (Operand *)dst->name;
}
if (src && src->kind == REG_SUBREG) {
src = (Operand *)src->name;
}
if (dst == reg) {
return InstrSetsDst(ir);
}
if (ir->opc == OPC_MOVD && reg) {
if (dst->kind == IMM_COG_LABEL && !strcmp(reg->name, dst->name)) {
return true;
}
}
if (src == reg && OPEFFECT_NONE != (ir->srceffect & 0xff)) {
return true;
}
return false;
}
// return TRUE if an instruction uses a register
bool
InstrUses(IR *ir, Operand *reg)
{
Operand *dst = ir->dst;
Operand *src = ir->src;
if (reg && reg->kind == REG_SUBREG) {
reg = (Operand *)reg->name;
}
if (dst && dst->kind == REG_SUBREG) {
dst = (Operand *)dst->name;
}
if (src && src->kind == REG_SUBREG) {
src = (Operand *)src->name;
}
if (src == reg) {
return true;
}
if (dst == reg && InstrReadsDst(ir)) {
return true;
}
if (src && src->kind == IMM_COG_LABEL && reg) {
if (!strcmp(reg->name, src->name)) {
return true;
}
}
return false;
}
// returns TRUE if an operand represents a local register or argument
static bool
IsArg(Operand *op)
{
if (op->kind == REG_SUBREG) op = (Operand *)op->name;
return op->kind == REG_ARG;
}
static bool
isResult(Operand *op)
{
if (op->kind == REG_SUBREG) op = (Operand *)op->name;
return op->kind == REG_RESULT;
}
// returns TRUE if an operand represents a local register
bool
IsLocal(Operand *op)
{
if (op->kind == REG_SUBREG) op = (Operand *)op->name;
return op->kind == REG_LOCAL || op->kind == REG_TEMP;
}
// returns TRUE if an operand represents a local register or argument
bool
IsLocalOrArg(Operand *op)
{
if (op->kind == REG_SUBREG) op = (Operand *)op->name;
return op->kind == REG_LOCAL || op->kind == REG_ARG || op->kind == REG_TEMP;
}
static bool
IsImmediate(Operand *op)
{
return op->kind == IMM_INT || op->kind == IMM_COG_LABEL;
}
static bool
IsImmediateVal(Operand *op, int val)
{
return op->kind == IMM_INT && op->val == val;
}
bool
IsValidDstReg(Operand *op)
{
switch(op->kind) {
case REG_SUBREG:
case REG_LOCAL:
case REG_TEMP:
case REG_ARG:
case REG_REG:
case IMM_COG_LABEL: // for popping ret addresses and such
return true;
default:
return false;
}
}
static unsigned CanonizeFlags(unsigned f) {
return ((f&FLAG_CSET)?FLAG_WC:0)|((f&FLAG_ZSET)?FLAG_WZ:0);
}
static bool
InstrSetsFlags(IR *ir, int flags)
{
return ir->flags & CanonizeFlags(flags);
}
static bool
InstrSetsAnyFlags(IR *ir)
{
return InstrSetsFlags(ir, FLAG_CZSET);
}
static bool
InstrIsVolatile(IR *ir)
{
return 0 != (ir->flags & FLAG_KEEP_INSTR);
}
static unsigned
FlagsUsedByCond(IRCond cond) {
switch (cond) {
case COND_TRUE:
case COND_FALSE:
return 0;
case COND_NC:
case COND_C:
return FLAG_WC;
case COND_NZ:
case COND_Z:
return FLAG_WZ;
default:
return FLAG_WC|FLAG_WZ;
}
}
static bool
InstrUsesFlags_CondAside(IR *ir, unsigned flags)
{
if ((ir->flags & (FLAG_ANDC|FLAG_XORC|FLAG_ORC)) && (flags & FLAG_WC)) return true;
if ((ir->flags & (FLAG_ANDZ|FLAG_XORZ|FLAG_ORZ)) && (flags & FLAG_WZ)) return true;
switch (ir->opc) {
case OPC_GENERIC:
case OPC_GENERIC_DELAY:
case OPC_GENERIC_NR:
case OPC_GENERIC_BRANCH:
case OPC_GENERIC_BRCOND:
/* it might use flags, we don't know (e.g. addx) */
return true;
case OPC_GENERIC_NOFLAGS:
case OPC_GENERIC_NR_NOFLAGS:
/* definitely does not use flags */
return false;
case OPC_WRC:
case OPC_WRNC:
case OPC_DRVC:
case OPC_DRVNC:
case OPC_MUXC:
case OPC_MUXNC:
case OPC_NEGC:
case OPC_NEGNC:
case OPC_BITC:
case OPC_BITNC:
case OPC_RCL:
case OPC_RCR:
case OPC_ADDX:
case OPC_ADDSX:
case OPC_SUBX:
case OPC_SUBSX:
/* definitely uses the C flag */
return (flags & FLAG_WC) != 0;
case OPC_DRVZ:
case OPC_DRVNZ:
case OPC_MUXZ:
case OPC_MUXNZ:
case OPC_NEGZ:
case OPC_NEGNZ:
case OPC_WRZ:
case OPC_WRNZ:
/* definitely uses the Z flag */
return (flags & FLAG_WZ) != 0;
default:
return false;
}
}
static inline bool
InstrUsesFlags(IR *ir, unsigned flags) {
if (FlagsUsedByCond(ir->cond) & flags) return true;
return InstrUsesFlags_CondAside(ir,flags);
}
bool IsHubDest(Operand *dst)
{
switch (dst->kind) {
case IMM_HUB_LABEL:
case REG_HUBPTR:
return true;
default:
return false;
}
}
bool MaybeHubDest(Operand *dst)
{
switch (dst->kind) {
case IMM_COG_LABEL:
if (!strcmp(dst->name, "gosub_"))
return true;
return false;
default:
return true;
}
}
Operand *
JumpDest(IR *jmp)
{
switch (jmp->opc) {
case OPC_DJNZ:
case OPC_GENERIC_BRCOND:
return jmp->src;
default:
return jmp->dst;
}
}
/*
* true if a branch target is after a given instruction
* (or equal to that instruction)
*/
static bool
JumpIsAfterOrEqual(IR *ir, IR *jmp)
{
// ptr to jump destination gets stored in aux
if (jmp->aux) {
IR *label = (IR *)jmp->aux;
if (!label) {
return false;
}
if (label->addr >= ir->addr) {
return true;
}
return false;
}
if (curfunc && (
JumpDest(jmp) == FuncData(curfunc)->asmretname
|| JumpDest(jmp) == FuncData(curfunc)->asmreturnlabel) )
return true;
return false;
}
static bool
IsForwardJump(IR *jmp)
{
return JumpIsAfterOrEqual(jmp, jmp);
}
/* check to see if a jump is relatively close to its
* destination; if this is false then (on P2) djnz may
* exceed its relative distance limit
*/
static bool
IsCloseJump(IR *jmp)
{
if (jmp->aux) {
int delta;
IR *label = (IR *)jmp->aux;
delta = jmp->addr - label->addr;
if (delta < 0) delta = -delta;
if (delta < 200) return true;
}
return false;
}
/*
* find next instruction following ir
*/
static IR *
NextInstruction(IR *ir)
{
while (ir) {
ir = ir->next;
if (ir && !IsDummy(ir) && !IsLabel(ir)) {
return ir;
}
}
return NULL;
}
/* like NextInstruction, but follow unconditional jumps */
static IR *
NextInstructionFollowJumps(IR *ir)
{
ir = NextInstruction(ir);
if (!ir || (ir->opc != OPC_JUMP) || ir->cond != COND_TRUE)
return ir;
if (!ir->aux) {
return ir;
}
ir = (IR *)ir->aux;
return NextInstructionFollowJumps(ir);
}
#if 0
/*
* return the next instruction after (or including) ir
* that uses op, or NULL if we can't determine it
*/
static IR *
NextUseAfter(IR *ir, Operand *op)
{
while (ir) {
while (IsDummy(ir)) {
ir = ir->next;
}
if (!ir) return NULL;
if (IsJump(ir)) {
// we could try to thread through the jumps,
// but for now punt
return NULL;
}
if (InstrUses(ir, op) || InstrModifies(ir, op)) {
if (ir->cond != COND_TRUE) {
return NULL;
}
return ir;
}
ir = ir->next;
}
return NULL;
}
#endif
bool
IsMathInstr(IR *ir)
{
switch (ir->opc) {
case OPC_ADD:
case OPC_SUB:
case OPC_AND:
case OPC_ANDN:
case OPC_OR:
case OPC_XOR:
case OPC_SHL:
case OPC_SHR:
case OPC_SAR:
return true;
default:
return false;
}
}
bool
IsSrcBitIndex(IR *ir)
{
switch (ir->opc) {
case OPC_SHL:
case OPC_SHR:
case OPC_SAR:
case OPC_ROL:
case OPC_ROR:
case OPC_RCL:
case OPC_RCR:
case OPC_TESTB:
case OPC_TESTBN:
case OPC_ZEROX:
case OPC_SIGNX:
return true;
default:
return false;
}
}
static bool
isConstMove(IR *ir, int32_t *valout) {
if (!ir->src || !IsImmediate(ir->src)) return false;
int32_t val = (int32_t)ir->src->val;
switch (ir->opc) {
case OPC_MOV:
break;
case OPC_NEG:
val = -val;
break;
case OPC_ABS:
if (val<0) val = -val;
break;
case OPC_DECOD:
val = 1<<(val&31);
break;
case OPC_BMASK:
val = (2<<(val&31))-1;
break;
case OPC_GETNIB:
val = (val>>(ir->src2->val*4))&0xF;
case OPC_GETBYTE:
val = (val>>(ir->src2->val*8))&0xFF;
case OPC_GETWORD:
val = (val>>(ir->src2->val*16))&0xFFFF;
break;
default:
return false;
}
if (valout) *valout = val;
return true;
}
static uint32_t EvalP2BitMask(int x) {
uint32_t val = (2<<((x>>5)&31))-1;
val = val<<(x&31) | val>>((32-x)&31);
return val;
}
static bool
isMaskingOp(IR *ir, int32_t *maskout) {
if (!ir->src) return false;
int32_t mask;
if (IsImmediate(ir->src)) {
mask = (int32_t)ir->src->val;
switch (ir->opc) {
case OPC_AND:
break;
case OPC_ANDN:
mask = ~mask;
break;
case OPC_ZEROX:
mask = (2<<(mask&31))-1;
break;
case OPC_BITL:
mask = ~EvalP2BitMask(mask);
break;
default:
return false;
}
} else if (ir->src == ir->dst) {
switch (ir->opc) {
case OPC_GETNIB:
if (!IsImmediateVal(ir->src2,0)) return false;
mask = 0xF;
break;
case OPC_GETBYTE:
if (!IsImmediateVal(ir->src2,0)) return false;
mask = 0xFF;
break;
case OPC_GETWORD:
if (!IsImmediateVal(ir->src2,0)) return false;
mask = 0xFFFF;
break;
default:
return false;
}
} else {
return false;
}
if (maskout) *maskout = mask;
return true;
}
// Is this an op that moves data from S to D in some manner?
// For all of these InstrReadsDst is false
static bool
isMoveLikeOp(IR *ir) {
switch (ir->opc) {
case OPC_MOV:
case OPC_NEG:
case OPC_ABS:
case OPC_NOT:
case OPC_ENCOD:
case OPC_DECOD:
case OPC_ONES:
case OPC_BMASK:
case OPC_NEGC:
case OPC_NEGNC:
case OPC_NEGZ:
case OPC_NEGNZ:
case OPC_GETNIB:
case OPC_GETBYTE:
case OPC_GETWORD:
// memory reads also count
case OPC_RDBYTE:
case OPC_RDWORD:
case OPC_RDLONG:
return true;
default:
return false;
}
}
static inline bool CondIsSubset(IRCond super, IRCond sub) {
return sub == (super|sub);
}
// Note: currently only valid for P2
static int InstrMinCycles(IR *ir) {
if (IsDummy(ir)||IsLabel(ir)) return 0;
int aug = 0;
if (ir->src && ir->src->kind == IMM_INT && ir->src->val > 511) aug += 2;
if (ir->dst && ir->dst->kind == IMM_INT && ir->dst->val > 511) aug += 2;
switch (ir->opc) {
case OPC_WRBYTE:
case OPC_WRWORD:
case OPC_WRLONG:
return aug+3;
case OPC_RDBYTE:
case OPC_RDWORD:
case OPC_RDLONG:
return aug+9;
default:
return aug+2;
}
}
#if 0
// Note: currently only valid for P2, and not used yet
static int InstrMaxCycles(IR *ir) {
if (IsDummy(ir)||IsLabel(ir)) return 0;
if (IsBranch(ir)) return 100000; // No good.
int aug = 0;
if (ir->src && ir->src->kind == IMM_INT && ir->src->val > 511) aug += 2;
if (ir->dst && ir->dst->kind == IMM_INT && ir->dst->val > 511) aug += 2;
switch (ir->opc) {
case OPC_WRBYTE:
return aug+26; // Can never be unaligned
case OPC_WRWORD:
case OPC_WRLONG:
return aug+27;
case OPC_RDBYTE:
return aug+20; // Can never be unaligned
case OPC_RDWORD:
case OPC_RDLONG:
return aug+21;
case OPC_GENERIC:
case OPC_GENERIC_NR:
case OPC_GENERIC_DELAY:
case OPC_GENERIC_BRANCH:
case OPC_GENERIC_BRCOND:
case OPC_GENERIC_NR_NOFLAGS:
case OPC_GENERIC_NOFLAGS:
case OPC_WAITX:
case OPC_WAITCNT:
return 100000; // No good;
case OPC_QMUL:
case OPC_QDIV:
case OPC_QFRAC:
case OPC_QSQRT:
case OPC_QLOG:
case OPC_QEXP:
return aug+9;
default:
return aug+2;
}
}
#endif
static int
AddSubVal(IR *ir)
{
int val = ir->src->val;
if (ir->opc == OPC_SUB) val = -val;
return val;
}
extern Operand *mulfunc, *unsmulfunc, *divfunc, *unsdivfunc, *muldiva, *muldivb;
static bool FuncUsesArg(Operand *func, Operand *arg)
{
if (arg == muldiva || arg == muldivb) {
return true;
} else if (func == mulfunc || func == unsmulfunc || func == divfunc || func == unsdivfunc) {
return false;
} else if (func && func->val && (/*func->kind == IMM_COG_LABEL ||*/ func->kind == IMM_HUB_LABEL) && ((Function*)func->val)->is_leaf) {
if (arg->kind != REG_ARG) return true; // subreg or smth
if (arg->val < ((Function*)func->val)->numparams) return true; // Arg used;
return false; // Arg not used
}
return true;
}
static bool IsCallThatUsesReg(IR *ir,Operand *op) {
if (ir->opc != OPC_CALL) return false;
if (IsLocal(op)) return false;
if (IsArg(op) && !FuncUsesArg(ir->dst,op)) return false;
return true;
}
static bool UsedInRange(IR *start,IR *end,Operand *reg) {
if (!reg || !IsRegister(reg->kind)) return false;
for (IR *ir=start;ir!=end->next;ir=ir->next) {
if (InstrUses(ir,reg)||IsJump(ir)) return true;
if (ir->opc == OPC_CALL) {
if (IsArg(reg) && FuncUsesArg(ir->dst,reg)) return true;
if (IsArg(reg)||isResult(reg)) return false; // Becomes dead
if (!IsLocal(reg)) return true;
}
if (InstrModifies(ir,reg) && ir->cond==COND_TRUE) return false; // Has become dead
}
return false;
}
static bool ModifiedInRange(IR *start,IR *end,Operand *reg) {
if (!reg || !IsRegister(reg->kind)) return false;
int32_t offset = 0;
for (IR *ir=start;ir!=end->next;ir=ir->next) {
if (ir->cond == COND_TRUE && (ir->opc == OPC_ADD || ir->opc == OPC_SUB) && ir->dst == reg && ir->src->kind == IMM_INT) {
offset += AddSubVal(ir);
} else if (ir->opc == OPC_CALL) {
if (!IsLocal(reg) && !(IsArg(reg) && !FuncUsesArg(ir->dst,reg)) && reg->kind != REG_HUBPTR && !(reg->kind == REG_REG && !strcmp(reg->name,"fp"))) return true;
} else if (InstrModifies(ir,reg)||IsJump(ir)||IsLabel(ir)) return true;
}
return offset != 0;
}
static bool ReadWriteInRange(IR *start,IR *end) {
for (IR *ir=start;ir!=end->next;ir=ir->next) {
if (IsReadWrite(ir)) return true;
}
return false;
}
static bool WriteInRange(IR *start,IR *end) {
for (IR *ir=start;ir!=end->next;ir=ir->next) {
if (IsWrite(ir)) return true;
}
return false;
}
static int MinCyclesInRange(IR *start,IR *end) {
int cyc = 0;
for (IR *ir=start;ir!=end->next;ir=ir->next) {
cyc += InstrMinCycles(ir);
}
return cyc;
}
/*
* return TRUE if the operand's value does not need to be preserved
* after instruction instr
* follows branches, but gives up after MAX_FOLLOWED_JUMPS to prevent
* infinite loops
*/
#define MAX_FOLLOWED_JUMPS 8
static bool
doIsDeadAfter(IR *instr, Operand *op, int level, IR **stack)
{
IR *ir;
int i;
if (op->kind == REG_HW) {
// hardware registers are never dead
return false;
}
if (op->kind == REG_SUBREG) {
// cannot handle sub registers properly yet
return false;
}
if (level >= MAX_FOLLOWED_JUMPS) {
// give up!
return false;
}
for (ir = instr->next; ir; ir = ir->next) {
if (InstrUses(ir, op) && !IsDummy(ir)) {
// value is used, so definitely not dead
// well, unless the value is used only to update itself:
// check for that here
if (ir->dst != op) {
return false; // op used to modify something else
}
if (InstrSetsAnyFlags(ir)) {
return false; // flag setting matters, we are not dead
}
switch(ir->opc) {
// be very cautious about whether op is dead if
// any "unusal" opcodes (like waitpeq) are used
// so just accept
case OPC_ADD:
case OPC_SUB:
case OPC_AND:
case OPC_OR:
case OPC_XOR:
// not definitely alive or dead yet
break;
default:
// assume live
return false;
}
if (op->kind == REG_SUBREG) {
return false;
}
if (ir->dst && ir->dst->kind == REG_SUBREG) {
return false;
}
if (ir->src && ir->src->kind == REG_SUBREG) {
return false;
}
}
for (i = 0; i < level; i++) {
if (ir == stack[i]) {
// we've come around a loop
// registers may be considered dead, labels not
return IsRegister(op->kind);
}
}
if (ir->opc == OPC_LABEL) {
// potential problem: if there is a branch before instr
// that goes to LABEL then we might miss a set
// so check
IR *comefrom = (IR *)ir->aux;
if (ir->flags & FLAG_LABEL_NOJUMP) {
// this label isn't a jump target, so don't worry about it
continue;
}
if (!ir->next) {
// last label in the function, again, no need to worry
continue;
}
if (!comefrom) {
// we don't know what branches come here,
// so for caution give up
return false;
}
if (level == 0 && comefrom->addr < instr->addr) {
// go back and see if there are any references before the
// jump that brought us here
// if so, abort
IR *backir = comefrom;
while (backir) {
if (backir->src == op || backir->dst == op) {
return false;
}
backir = backir->prev;
}
}
continue;
}
if (InstrModifies(ir, op) && !InstrUses(ir,op) && !IsDummy(ir)) {
// if the instruction modifies but does not use the op,
// then we're setting it from another register and it's dead
if (op->kind == REG_SUBREG) {
return false;
}
if (ir->dst && ir->dst->kind == REG_SUBREG) {
return false;
}
if (ir->cond == COND_TRUE) {
return true;
}
}
if (ir->opc == OPC_RET && ir->cond == COND_TRUE) {
goto done;
} else if (ir->opc == OPC_CALL && !IsDummy(ir)) {
if (!IsLocal(op)) {
// we know of some special cases where argN is not used
if (IsArg(op) && !FuncUsesArg(ir->dst, op)) {
/* OK to continue */
} else if (isResult(op)) {
return true; // Results get set by functions
} else {
return false;
}
}
} else if (IsJump(ir) && !IsDummy(ir)) {
// if the jump is to an unknown place give up
stack[level] = ir; // remember where we were
if (!ir->aux) {
// jump to return is like running off the end
if (ir->dst == FuncData(curfunc)->asmreturnlabel && ir->cond == COND_TRUE) {
goto done;
}
// See if this is a jump table
if (ir->cond == COND_TRUE && ir->next && IsLabel(ir->next) && ir->next->next && (ir->next->next->flags & FLAG_JMPTABLE_INSTR)) {
for (IR *entry=ir->next->next;entry&&(entry->flags&FLAG_JMPTABLE_INSTR);entry=entry->next) {
if (!entry->aux) return false;
if (!doIsDeadAfter((IR *)entry->aux, op, level+1, stack)) return false;
}
return true; // All branches dead
}
return false;
}
if (!doIsDeadAfter((IR *)ir->aux, op, level+1, stack)) {
return false;
}
#if 1
// be very careful about potential conditional jumps to
// after this point, but we did check for that above
if (ir->cond == COND_TRUE && ir->opc == OPC_JUMP) {
return true;
}
#endif
}
}
done:
/* if we reach the end without seeing any use */
if (isResult(op)) {
if (op->kind != REG_RESULT) return false; // subreg or smth else
if (op->val < curfunc->numresults) return false; // This is a defined result of this function
return true;
} else {
return IsLocalOrArg(op);
}
}
static bool
IsDeadAfter(IR *instr, Operand *op)
{
IR *stack[MAX_FOLLOWED_JUMPS];
stack[0] = instr;
return doIsDeadAfter(instr, op, 1, stack);
}
static bool
SafeToReplaceBack(IR *instr, Operand *orig, Operand *replace)
{
IR *ir;
int usecount = 0;
if (SrcOnlyHwReg(replace) || !IsRegister(replace->kind))
return false;
if (replace->kind == REG_SUBREG || (orig && orig->kind == REG_SUBREG) ) {
return false;
}
for (ir = instr; ir; ir = ir->prev) {
if (IsDummy(ir)) {
continue;
}
if (ir->opc == OPC_LABEL) {
if (ir->flags & FLAG_LABEL_NOJUMP) {
continue;
}
return false;
}
if (ir->opc == OPC_LIVE) {
return false;
}
if (IsJump(ir)) {
return false;
}
if (IsCallThatUsesReg(ir,orig) || IsCallThatUsesReg(ir,replace)) {
return false;
}
if (InstrModifies(ir, orig) && !InstrReadsDst(ir)) {
if (InstrIsVolatile(ir)) return false;
if (IsHwReg(replace) && ir->src && IsHwReg(ir->src) && ir->src != replace)
{
return false;
}
if (usecount > 0 && IsHwReg(replace) && ir->src != replace) {
return false;
}
// this was perhaps overly cautious, but I can remember a lot of headaches
// around optimization, so we may need to revert to it
//return ir->cond == COND_TRUE;
if (ir->cond == COND_TRUE) return true;
}
if (InstrUses(ir, replace) || ir->dst == replace) {
return false;
}
if ( (InstrUses(ir, orig) || InstrModifies(ir, orig)) && IsHwReg(replace)) {
if (usecount > 0) {
return false;
}
usecount++;
}
}
// we've reached the start
// is orig dead here? if so we can replace it
// args are live, and so are globals
return IsLocal(orig);
}
bool
IsHwReg(Operand *reg)
{
return reg && reg->kind == REG_HW;
}
//
// returns true if orig is a source only
// hardware register (CNT, INA, INB)
//
bool
SrcOnlyHwReg(Operand *orig)
{
if (orig->kind != REG_HW)
return false;
if (orig->val != 0) {
return true;
}
if (!strcasecmp(orig->name, "CNT")
|| !strcasecmp(orig->name, "INA")
|| !strcasecmp(orig->name, "INB"))
{
return true;
}
return false;
}
//
// see if we can replace "orig" with "replace" in code after first_ir
// returns the IR where we should stop scanning for replacement,
// or NULL if replacement is unsafe
//
static IR*
SafeToReplaceForward(IR *first_ir, Operand *orig, Operand *replace, IRCond setterCond)
{
IR *ir;
IR *last_ir = NULL;
bool assignments_are_safe = true;
bool orig_modified = false;
bool isCond = (setterCond != COND_TRUE);
if (SrcOnlyHwReg(replace) || !IsRegister(replace->kind)) {
return NULL;
}
if (replace->kind == REG_SUBREG) {
return NULL;
}
if (orig && orig->kind == REG_SUBREG) {
return NULL;
}
if (!first_ir) {
return NULL;
}
#if 1
// special case: if orig is dead after this,
// and if first_ir does not modify it, then it is safe to
// replace
if (!IsBranch(first_ir) && IsDeadAfter(first_ir, orig) && !InstrModifies(first_ir, orig) && !isCond) {
return first_ir;
}
#endif
for (ir = first_ir; ir; ir = ir->next) {
if (IsDummy(ir)) {
continue;
}
#if 1
// paranoia: subregisters are more complicated than we realize,
// so be careful if any are in use
if (ir->src && ir->src->kind == REG_SUBREG) {
assignments_are_safe = false;
}
#endif
if (ir->opc == OPC_LIVE && !strcmp(orig->name, ir->dst->name)) {
return NULL;
}
if (ir->opc == OPC_LIVE && !strcmp(replace->name, ir->dst->name)) {
return NULL;
}
if (ir->opc == OPC_RET) {
return (IsLocalOrArg(orig) && !isCond) ? ir : NULL;
} else if (ir->opc == OPC_CALL) {
// it's OK to replace forward over a call as long
// as orig is a local register (not an ARG!)
if (IsArg(orig)) {
if (FuncUsesArg(ir->dst, orig)) {
return NULL;
}
} else if (!IsLocal(orig)) {
return NULL;
}
if (IsArg(replace)) {
if (FuncUsesArg(ir->dst, replace)) {
// if there are any more references to orig then
// replacement will fail (since arg gets changed
// by the call)
return (assignments_are_safe && IsDeadAfter(ir, orig) && !isCond) ? ir : NULL;
}
} else if (!IsLocal(replace)) {
return NULL;
}
} else if (IsJump(ir)) {
// forward branches (or branches to code we've
// already seen) are safe; others we should assume
// will cause problems
// Note though that if we do branch ahead then
// we cannot assume that assignments are safe!
if (ir->aux && IsDeadAfter((IR *)ir->aux,replace) && IsDeadAfter((IR *)ir->aux,orig)) {
// both regs are dead after branch, so we don't care
} else {
if (!JumpIsAfterOrEqual(first_ir, ir)) {
return NULL;
}
if (assignments_are_safe && IsForwardJump(ir) && ir->aux) {
IR *jmpdst = (IR *)ir->aux;
assignments_are_safe = IsDeadAfter(jmpdst, orig);
} else {
assignments_are_safe = false;
}
}
}
if (ir->opc == OPC_LABEL) {
IR *comefrom;
if (ir->flags & FLAG_LABEL_NOJUMP) {
// this label is not a jump target, so ignore it
continue;
}
// do we know who jumps to this label?
comefrom = (IR *)ir->aux;
if (comefrom) {
// if the jumper is before our first instruction, then
// we don't know what may have happened before, so
// replacement is dangerous
// however, in the special case that the register is never
// actually used again then it's safe
if (comefrom->addr < first_ir->addr) {
if (assignments_are_safe && IsDeadAfter(ir, orig) && !isCond) {
return ir;
}
return NULL;
}
assignments_are_safe = false;
} else {
// unknown jumper, assume the worst
return NULL;
}
}
if (!CondIsSubset(setterCond,ir->cond) && InstrUses(ir,orig)) {
return NULL;
}
if (InstrModifies(ir,replace)) {
// special case: if we have a "mov replace,x" and orig is dead
// then we are good to go; at that point we know it is safe to replace
// orig with replace because:
// (a) orig is dead after this, so not used
// (b) whatever we did to replace up til now it doesn't matter, a fresh
// value is being put into it
// if "assignments_are_safe" is false then we don't know if another
// branch might still use "replace", so punt and give up
if (!CondIsSubset(ir->cond,setterCond)) {
return NULL;
}
if (ir->dst->kind == REG_SUBREG || replace->kind == REG_SUBREG) {
// sub register usage is problematic
return NULL;
}
if (!assignments_are_safe) {
return NULL;
}
if (!InstrUses(ir, replace) && IsDeadAfter(ir, orig)) {
return ir;
}
if (!orig_modified && last_ir && IsDeadAfter(last_ir, orig)) {
// orig never actually got changed, and neither did replace (up
// until now) so we can do the replacement
return last_ir;
}
return NULL;
}
if (InstrModifies(ir, orig)) {
if (ir->src == orig && ir->srceffect != OPEFFECT_NONE) {
return NULL;
}
if (ir->dst == orig && ir->dsteffect != OPEFFECT_NONE) {
return NULL;
}
if (ir->dst->kind == REG_SUBREG) {
// sub registers are complicated, punt
return NULL;
}
if (ir->cond != setterCond) {
assignments_are_safe = false;
if (!CondIsSubset(setterCond,ir->cond)) {
// Not a subset of the setter condition, can't replace
return NULL;
}
}
if (!InstrUses(ir, orig) && assignments_are_safe) {
// we are completely re-setting "orig" here, so we can just
// leave now
return last_ir;
}
// we do not want to end accidentally modifying "replace" if it is still live
// note that IsDeadAfter(first_ir, replace) gives a more accurate
// view than IsDeadAfter(ir, replace), because it can look back
// further (and we've already verified that replace is not doing
// anything interesting between first_ir and here)
if (!IsDeadAfter(first_ir, replace)) {
return NULL;
}
orig_modified = true;
}
last_ir = ir;
}
return IsLocalOrArg(orig) ? last_ir : NULL;
}
static void
ReplaceBack(IR *instr, Operand *orig, Operand *replace)
{
IR *ir;
for (ir = instr; ir; ir = ir->prev) {
if (ir->opc == OPC_LABEL) {
if (ir->flags & FLAG_LABEL_NOJUMP) {
continue;
}
break;
}
if (ir->dst == orig) {
ir->dst = replace;
if (InstrSetsDst(ir) && !InstrReadsDst(ir) && ir->cond == COND_TRUE) {
break;
}
}
if (ir->src == orig) {
ir->src = replace;
}
}
}
static void
ReplaceForward(IR *instr, Operand *orig, Operand *replace, IR *stop_ir)
{
IR *ir;
for (ir = instr; ir; ir = ir->next) {
if (ir->src == orig) {
ir->src = replace;
}
if (ir->dst == orig) {
ir->dst = replace;
}
if (ir == stop_ir) break;
}
}
//
// Apply a new condition code based on val being compared to 0
//
int
ApplyConditionAfter(IR *instr, int val)
{
IR *ir;
IRCond newcond;
int change = 0;
int setz = instr->flags & FLAG_WZ;
int setc = instr->flags & FLAG_WC;
int cval = val < 0 ? 2 : 0;
int zval = val == 0 ? 1 : 0;
for (ir = instr->next; ir; ir = ir->next) {
if (IsDummy(ir)) continue;
newcond = ir->cond;
// Bit-magic on the condition values.
// (Basically, take the half that's selected by the constant flag
// and replicate it into the other half)
if (setc) newcond = ((newcond >> cval)&0b0011)*0b0101;
if (setz) newcond = ((newcond >> zval)&0b0101)*0b0011;
if (ir->cond != newcond) {
change = 1;
ir->cond = newcond;
}
switch(ir->opc) {
case OPC_NEGC : if (setc) {ReplaceOpcode(ir, cval ? OPC_NEG : OPC_MOV );change=1;} break;
case OPC_NEGNC: if (setc) {ReplaceOpcode(ir,!cval ? OPC_NEG : OPC_MOV );change=1;} break;
case OPC_NEGZ : if (setz) {ReplaceOpcode(ir, zval ? OPC_NEG : OPC_MOV );change=1;} break;
case OPC_NEGNZ: if (setz) {ReplaceOpcode(ir,!zval ? OPC_NEG : OPC_MOV );change=1;} break;
case OPC_MUXC : if (setc) {ReplaceOpcode(ir, cval ? OPC_OR : OPC_ANDN);change=1;} break;
case OPC_MUXNC: if (setc) {ReplaceOpcode(ir,!cval ? OPC_OR : OPC_ANDN);change=1;} break;
case OPC_MUXZ : if (setz) {ReplaceOpcode(ir, zval ? OPC_OR : OPC_ANDN);change=1;} break;
case OPC_MUXNZ: if (setz) {ReplaceOpcode(ir,!zval ? OPC_OR : OPC_ANDN);change=1;} break;
case OPC_DRVC : if (setc) {ReplaceOpcode(ir, cval ? OPC_DRVH : OPC_DRVL);change=1;} break;
case OPC_DRVNC: if (setc) {ReplaceOpcode(ir,!cval ? OPC_DRVH : OPC_DRVL);change=1;} break;
case OPC_DRVZ : if (setz) {ReplaceOpcode(ir, zval ? OPC_DRVH : OPC_DRVL);change=1;} break;
case OPC_DRVNZ: if (setz) {ReplaceOpcode(ir,!zval ? OPC_DRVH : OPC_DRVL);change=1;} break;
case OPC_WRC : if (setc) {ReplaceOpcode(ir,OPC_MOV);ir->src=NewImmediate( cval?1:0);} break;
case OPC_WRNC : if (setc) {ReplaceOpcode(ir,OPC_MOV);ir->src=NewImmediate(!cval?1:0);} break;
case OPC_WRZ : if (setz) {ReplaceOpcode(ir,OPC_MOV);ir->src=NewImmediate( zval?1:0);} break;
case OPC_WRNZ : if (setz) {ReplaceOpcode(ir,OPC_MOV);ir->src=NewImmediate(!zval?1:0);} break;
case OPC_RCL:
case OPC_RCR:
if (setc) {
ERROR(NULL, "Internal error: ApplyConditionAfter cannot be applied to RCL/RCR");
}
break;
default:
if (InstrUsesFlags(ir,setc|setz)) {
WARNING(NULL,"Internal warning. Couldn't ApplyConditionAfter");
}
break;
}
if (newcond != COND_FALSE) {
if(InstrSetsFlags(ir,FLAG_WC)) setc = 0;
if(InstrSetsFlags(ir,FLAG_WZ)) setz = 0;
}
if (!setc && !setz) break;
}
return change;
}
static bool
SameImmediate(Operand *a, Operand *b)
{
if (a->kind != IMM_INT || b->kind != IMM_INT)
return 0;
return a->val == b->val;
}
static bool
SameOperand(Operand *a, Operand *b)
{
if (a == b) {
return true;
}
if (!a || !b) {
return false;
}
return SameImmediate(a, b);
}
// try to transform an operation with a destination that is
// known to be the constant "imm"
// if the src is also constant, convert it to a move immediate
// returns 1 if there is a change
static int
TransformConstDst(IR *ir, Operand *imm)
{
int32_t val1, val2;
int setsResult = 1;
if (gl_p2 && !InstrSetsDst(ir)) {
// this may be a case where we can replace dst with src
if (ir->instr) {
switch (ir->instr->ops) {
case P2_DST_CONST_OK:
case P2_TWO_OPERANDS:
case P2_RDWR_OPERANDS:
ir->dst = imm;
return 1;
default:
break;
}
}
}
if (ir->src == NULL) {
return 0;
}
if (imm->kind == IMM_INT && imm->val == 0) {
// transform add foo, bar into mov foo, bar, if foo is known to be 0
if ((ir->opc == OPC_ADD || ir->opc == OPC_SUB || ir->opc == OPC_OR || ir->opc == OPC_XOR)
&& (ir->flags == FLAG_WZ || !InstrSetsAnyFlags(ir)))
{
if (ir->opc == OPC_SUB) {
ReplaceOpcode(ir, OPC_NEG);
} else {
ReplaceOpcode(ir, OPC_MOV);
}
return 1;
}
}
if (ir->src->kind != IMM_INT) {
return 0;
}
if (imm->kind == IMM_COG_LABEL && ir->opc == OPC_ADD && ir->flags == 0) {
Operand *newlabel = NewOperand(IMM_COG_LABEL, imm->name, imm->val + ir->src->val);
ir->src = newlabel;
ReplaceOpcode(ir, OPC_MOV);
return 1;
}
if (imm->kind != IMM_INT) {
return 0;
}
if (ir->flags & FLAG_WC) {
// we don't know how to set the WC flag for anything other
// than cmps
if (ir->opc != OPC_CMPS && ir->opc != OPC_CMP) {
return 0;
}
}
val1 = imm->val;
val2 = ir->src->val;
switch (ir->opc)
{
case OPC_ADD:
val1 += val2;
break;
case OPC_SUB:
val1 -= val2;
break;
case OPC_TEST:
setsResult = false;
// fall through
case OPC_AND:
val1 &= val2;
break;
case OPC_OR:
val1 |= val2;
break;
case OPC_XOR:
val1 ^= val2;
break;
case OPC_TESTN:
setsResult = false;
// fall through
case OPC_ANDN:
val1 &= ~val2;
break;
case OPC_SHL:
val1 = val1 << (val2&31);
break;
case OPC_SAR:
val1 = val1 >> (val2&31);
break;
case OPC_SHR:
val1 = ((uint32_t)val1) >> (val2&31);
break;
case OPC_ZEROX:
val2 = 31-(val2&31);
val1 = ((uint32_t)val1<<val2)>>val2;
break;
case OPC_SIGNX:
val2 = 31-(val2&31);
val1 = ((int32_t)val1<<val2)>>val2;
break;
case OPC_CMPS:
val1 -= val2;
setsResult = 0;
break;
case OPC_CMP:
if ((uint32_t)val1 < (uint32_t)val2) {
val1 = -1;
} else if (val1 == val2) {
val1 = 0;
} else {
val1 = 1;
}
setsResult = 0;
break;
case OPC_TESTBN:
setsResult = false;
// Z is set if bit is CLEAR
val1 = val1 & (1<<(val2&31));
break;
case OPC_TESTB:
setsResult = false;
// Z is set if bit is SET
val1 = ~val1 & (1<<(val2&31));
break;
default:
return 0;
}
if (InstrSetsAnyFlags(ir)) {
ApplyConditionAfter(ir, val1);
}
if (setsResult) {
if (val1 < 0) {
ReplaceOpcode(ir, OPC_NEG);
ir->src = NewImmediate(-val1);
} else {
ReplaceOpcode(ir, OPC_MOV);
ir->src = NewImmediate(val1);
}
} else {
ir->cond = COND_FALSE;
}
return 1;
}
static bool
IsOnlySetterFor(IRList *irl, IR *orig_ir, Operand *orig)
{
IR *ir;
if (!IsLocal(orig)) {
return false;
}
for (ir = irl->head; ir; ir = ir->next) {
if (IsDummy(ir) || IsLabel(ir)) {
continue;
}
if (ir != orig_ir && InstrModifies(ir, orig)) {
return false;
}
}
return true;
}
//
// if we see x:=2 then replace future uses of x with 2
// if orig_ir is the only setter for orig in the whole irl,
// then we can do this unconditionally; otherwise we have
// to beware of jumps and labels
//
static int
PropagateConstForward(IRList *irl, IR *orig_ir, Operand *orig, Operand *immval)
{
IR *ir;
int change = 0;
bool unconditional;
int32_t tmp;
if (!isConstMove(orig_ir,&tmp)) ERROR(NULL,"isConstMove == false in PropagateConstForward");
if (immval->val != tmp) {
immval = NewImmediate(tmp);
}
unconditional = IsOnlySetterFor(irl, orig_ir, orig);
for (ir = orig_ir->next; ir; ir = ir->next) {
if (IsDummy(ir)) {
continue;
}
if (IsLabel(ir) && !unconditional) {
return change;
}
if (ir->opc == OPC_CALL) {
if (!unconditional || !IsLocal(orig)) {
return change;
}
}
if (IsJump(ir) && !JumpIsAfterOrEqual(orig_ir, ir)) {
if (unconditional) {
continue;
}
return change;
}
if (ir->opc == OPC_MOV && !InstrSetsAnyFlags(ir) && SameImmediate(ir->src, immval)) {
if ( ir->dst == orig ) {
// updating same register, so kill it
ir->opc = OPC_DUMMY;
change = 1;
} else {
// it would be nice here to substitute forward the
// register "dst" with "orig", so as to eliminate some
// redundant register usage; but my original attempt to
// do this ran into infinite loops, so putting that on hold
// for now
}
} else if (ir->dst == orig) {
// we can perhaps replace the operation with a mov
change |= TransformConstDst(ir, immval);
} else if (ir->src == orig) {
ir->src = immval;
change = 1;
}
if (InstrModifies(ir, orig)) {
// our register has changed, so we must stop
return change;
}
}
return change;
}
static bool
DeleteMulDivSequence(IRList *irl, IR *ir, Operand *lastop, Operand *opa, Operand *opb, IR *lastir)
{
IR *ir2, *ir3;
// ir is pointing at the mov muldiva, opa instruction
ir2 = ir->next;
if (!ir2) return false;
ir3 = ir2->next;
if (!ir3) return false;
if (ir2->opc != OPC_MOV) return false;
if (ir2->dst != muldivb || !SameOperand(ir2->src, opb)) return false;
if (ir3->opc != OPC_CALL) return false;
if (ir3->dst != lastop) {
// There is a case here where we might want to
// merge "multiply" (getting low word) and "unsigned multiply"
// (getting high word)
// not sure how to do that yet...
if (lastop == unsmulfunc && ir3->dst == mulfunc && lastir) {
lastir->dst = ir3->dst;
} else {
return false;
}
}
ir->opc = OPC_DUMMY;
ir2->opc = OPC_DUMMY;
ir3->opc = OPC_DUMMY;
return true;
}
int
OptimizeMulDiv(IRList *irl)
{
// known operands (NULL if not known)
Operand *opa = NULL; // first operand to multiply or divide
Operand *opb = NULL; // second operand to multiply or divide
Operand *lastop = NULL;
IR *ir;
IR *lastir = NULL;
int change = 0;
int hiresult_used = 0;
ir = irl->head;
while (ir != 0) {
if (IsLabel(ir)) {
opa = opb = lastop = NULL;
hiresult_used = 0;
} else if (IsDummy(ir)) {
// do nothing
} else if (InstrModifies(ir, muldiva)) {
if (ir->opc == OPC_MOV && ir->cond == COND_TRUE) {
// this may be a particular sequence:
// mov muldiva, opa
// mov muldivb, opb
// call #function
// if so, see if we have just done that sequence previously
// so that the proper results are already in their
// registers
if (opa == ir->src && DeleteMulDivSequence(irl, ir, lastop, opa, opb, hiresult_used ? 0 : lastir)) {
change = 1;
} else {
opa = ir->src;
opb = NULL;
lastop = NULL;
hiresult_used = 0;
}
} else {
opa = opb = lastop = NULL;
}
} else if (InstrModifies(ir, muldivb)) {
if (ir->opc == OPC_MOV) {
opb = ir->src;
} else if (InstrSetsDst(ir)) {
opb = NULL;
hiresult_used = 0;
}
} else if (InstrUses(ir, muldivb)) {
hiresult_used = 1;
} else if (opa && InstrModifies(ir, opa)) {
opa = NULL;
} else if (opb && InstrModifies(ir, opb)) {
opb = NULL;
hiresult_used = 0;
} else if (ir->opc == OPC_CALL) {
if (ir->dst == mulfunc || ir->dst == unsmulfunc || ir->dst == divfunc || ir->dst == unsdivfunc) {
lastir = ir;
lastop = lastir->dst;
hiresult_used = 0;
} else {
lastop = NULL;
hiresult_used = 1;
}
}
ir = ir->next;
}
return change;
}
/* return 1 if the instruction can have wz appended and produce a sensible
* result (compares result to 0)
*/
static int
CanTestZero(int opc)
{
switch (opc) {
case OPC_ADD:
case OPC_SUB:
case OPC_AND:
case OPC_ANDN:
case OPC_OR:
case OPC_MOV:
case OPC_NEG:
case OPC_NEGC:
case OPC_NEGNC:
case OPC_NEGZ:
case OPC_NEGNZ:
case OPC_RDLONG:
case OPC_RDBYTE:
case OPC_RDWORD:
case OPC_XOR:
case OPC_SAR:
case OPC_SHR:
case OPC_SHL:
case OPC_SIGNX:
case OPC_ZEROX:
case OPC_MULU:
case OPC_MULS:
return 1;
default:
return 0;
}
}
//
// find the previous instruction that sets a particular operand
// used for compares
// returns NULL if we cannot
//
static IR*
FindPrevSetterForCompare(IR *irl, Operand *dst)
{
IR *ir;
int orig_condition = irl->cond;
if (SrcOnlyHwReg(dst))
return NULL;
for (ir = irl->prev; ir; ir = ir->prev) {
if (IsDummy(ir)) {
continue;
}
if (ir->opc == OPC_LABEL) {
// we may have branched to here from somewhere
// else that did the set
return NULL;
}
if (ir->cond != orig_condition) {
if (ir->dst == dst) {
return NULL;
}
}
if (InstrSetsAnyFlags(ir)) {
// flags are messed up here, so we can't go back any further
return NULL;
}
if (IsBranch(ir)) {
return NULL;
}
if (ir->dst == dst && InstrSetsDst(ir)) {
if (ir->cond != COND_TRUE) {
// cannot be sure that we set the value here,
// since the set is conditional
return NULL;
}
return ir;
}
}
return NULL;
}
//
// find the previous instruction that changes a particular operand
// also will return if it's in the dst field of a TEST
//
// used for peephole optimization
// returns NULL if we cannot find the instruction
//
static IR*
FindPrevSetterForReplace(IR *irorig, Operand *dst)
{
IR *ir;
IR *saveir;
if (irorig->cond != COND_TRUE) {
return NULL;
}
if (SrcOnlyHwReg(dst))
return NULL;
for (ir = irorig->prev; ir; ir = ir->prev) {
if (IsDummy(ir)) {
continue;
}
if (ir->opc == OPC_LABEL) {
// we may have branched to here from somewhere
// else that did the set
return NULL;
}
if (IsJump(ir)) {
return NULL;
}
if (IsCallThatUsesReg(ir,dst)) {
return NULL;
}
if (ir->dst == dst && (InstrSetsDst(ir) || ir->opc == OPC_TEST || ir->opc == OPC_TESTBN)) {
if (ir->cond != COND_TRUE) {
// cannot be sure that we set the value here,
// since the set is conditional
return NULL;
}
break;
}
if (ir->src == dst || ir->dst == dst) {
// we cannot replace the setter, it's in use
return NULL;
}
}
if (!ir) {
return NULL;
}
// OK, now go forward and make sure ir->src is not changed
// until irorig
saveir = ir;
ir = ir->next;
while (ir && ir != irorig) {
if (IsDummy(ir)) {
ir = ir->next;
continue;
}
if (ir->dst == saveir->src && InstrSetsDst(ir)) {
return NULL;
}
ir = ir->next;
}
return saveir;
}
//
// check for flags used between ir1 and ir2
//
static int
FlagsNotUsedBetween(IR *ir1, IR *ir2, unsigned flags)
{
while (ir1 && ir1 != ir2) {
if (InstrUsesFlags(ir1, flags)) {
return 0;
}
ir1 = ir1->next;
}
if (!ir1) {
return 0;
}
return 1;
}
//
// check for flags set between ir1 and ir2
//
static int
FlagsNotSetBetween(IR *ir1, IR *ir2, unsigned flags)
{
while (ir1 && ir1 != ir2) {
if (InstrSetsFlags(ir1, flags)) {
return 0;
}
ir1 = ir1->next;
}
if (!ir1) {
return 0;
}
return 1;
}
int
OptimizeMoves(IRList *irl)
{
IR *ir;
IR *ir_next;
IR *stop_ir;
int change;
int everchange = 0;
int32_t cval;
do {
change = 0;
ir = irl->head;
while (ir != 0) {
ir_next = ir->next;
if (InstrIsVolatile(ir)) {
/* do nothing */
} else if (ir->opc == OPC_MOV && ir->src == ir->dst) {
if (!InstrSetsAnyFlags(ir)) {
DeleteIR(irl, ir);
change = 1;
} else if (ir->flags == FLAG_WZ) {
IR *prev_ir = FindPrevSetterForCompare(ir,ir->src);
if (prev_ir && CanTestZero(prev_ir->opc)
&& (prev_ir->flags&(FLAG_ZSET&~FLAG_WZ)) == 0
&& prev_ir->cond == COND_TRUE && ir->cond == COND_TRUE
&& FlagsNotUsedBetween(prev_ir,ir,FLAG_WZ)
&& FlagsNotSetBetween(prev_ir,ir,FLAG_WZ)) {
prev_ir->flags |= FLAG_WZ;
DeleteIR(irl, ir);
change = 1;
}
}
} else if (ir->cond == COND_TRUE && isConstMove(ir,&cval)) {
int sawchange;
if (ir->flags == FLAG_WZ && CanTestZero(ir->opc)) {
// because this is a mov immediate, we know how
// WZ will be set
change |= ApplyConditionAfter(ir, cval);
}
change |= (sawchange = PropagateConstForward(irl, ir, ir->dst, ir->src));
if (sawchange && !InstrSetsAnyFlags(ir) && IsDeadAfter(ir, ir->dst)) {
// we no longer need the original mov
DeleteIR(irl, ir);
}
} else if (ir->opc == OPC_MOV) {
if (ir->src == ir->dst && !InstrSetsAnyFlags(ir)) {
DeleteIR(irl, ir);
change = 1;
} else if (!InstrSetsAnyFlags(ir) && ir->cond == COND_TRUE && IsDeadAfter(ir, ir->src) && SafeToReplaceBack(ir->prev, ir->src, ir->dst)) {
ReplaceBack(ir->prev, ir->src, ir->dst);
DeleteIR(irl, ir);
change = 1;
}
else if ( !InstrSetsAnyFlags(ir) && 0 != (stop_ir = SafeToReplaceForward(ir->next, ir->dst, ir->src,ir->cond)) ) {
ReplaceForward(ir->next, ir->dst, ir->src, stop_ir);
DeleteIR(irl, ir);
change = 1;
}
} else if (isMoveLikeOp(ir) && (stop_ir = FindPrevSetterForReplace(ir,ir->src)) && stop_ir->opc == OPC_MOV
&& !InstrIsVolatile(stop_ir) && !InstrSetsAnyFlags(stop_ir) && (ir->src==ir->dst||IsDeadAfter(ir,ir->src))) {
ir->src = stop_ir->src;
DeleteIR(irl,stop_ir);
change = 1;
}
ir = ir_next;
}
everchange |= change;
} while (change && 0);
return everchange;
}
// Are given flag bits currently in use at this IR?
static unsigned
FlagsUsedAt(IR *ir,unsigned flags) {
for (IR *irnext = ir; irnext; irnext = irnext->next) {
if (InstrUsesFlags(irnext, flags)) return true;
if (InstrIsVolatile(irnext)) return true;
if (irnext->cond == COND_TRUE && IsBranch(irnext)) break;
if (irnext->cond == COND_TRUE && InstrSetsFlags(irnext,flags)) break;
}
return false;
}
static bool
HasUsedFlags(IR *ir) {
if (InstrSetsAnyFlags(ir)) {
// if the flags might possibly be used, we have to assume there
// are side effects
return FlagsUsedAt(ir->next,CanonizeFlags(ir->flags));
}
return false;
}
static bool
HasSideEffectsOtherThanReg(IR *ir)
{
if ( (ir->dst && ir->dst->kind == REG_HW)
|| (ir->src && ir->src->kind == REG_HW) )
{
return true;
}
if (ir->dsteffect != OPEFFECT_NONE || ir->srceffect != OPEFFECT_NONE) {
return true;
}
if (IsBranch(ir)) {
if (ir->opc == OPC_CALL &&
(ir->dst == mulfunc || ir->dst == divfunc || ir->dst == unsdivfunc))
{
return false;
}
return true;
}
if (HasUsedFlags(ir)) return true;
if (InstrIsVolatile(ir)) {
return true;
}
switch (ir->opc) {
case OPC_GENERIC:
case OPC_GENERIC_NR:
case OPC_GENERIC_DELAY:
case OPC_GENERIC_NOFLAGS:
case OPC_GENERIC_NR_NOFLAGS:
case OPC_LOCKCLR:
case OPC_LOCKNEW:
case OPC_LOCKRET:
case OPC_LOCKSET:
case OPC_SETQ:
case OPC_SETQ2:
case OPC_WAITCNT:
case OPC_WAITX:
case OPC_WRBYTE:
case OPC_WRLONG:
case OPC_WRWORD:
case OPC_COGSTOP:
case OPC_COGID:
case OPC_ADDCT1:
case OPC_HUBSET:
case OPC_QDIV:
case OPC_QFRAC:
case OPC_QMUL:
case OPC_QROTATE:
case OPC_QSQRT:
case OPC_QVECTOR:
case OPC_QLOG:
case OPC_QEXP:
case OPC_DRVC:
case OPC_DRVNC:
case OPC_DRVL:
case OPC_DRVH:
case OPC_DRVNZ:
case OPC_DRVZ:
case OPC_PUSH:
case OPC_POP:
case OPC_RCL:
case OPC_RCR:
return true;
default:
return false;
}
}
#if 0
static bool
HasSideEffects(IR *ir)
{
if (ir->dst && !IsLocalOrArg(ir->dst) /*ir->dst->kind == REG_HW*/) {
return true;
}
return HasSideEffectsOtherThanReg(ir);
}
#endif
static bool
MeaninglessMath(IR *ir)
{
int val;
if (0 != (ir->flags & (FLAG_WC|FLAG_WZ))) {
return false;
}
if (!ir->src || ir->src->kind != IMM_INT) {
return false;
}
val = ir->src->val;
switch (ir->opc) {
case OPC_ADD:
case OPC_SUB:
case OPC_SHL:
case OPC_SHR:
case OPC_SAR:
case OPC_ROL:
case OPC_ROR:
case OPC_RCL:
case OPC_RCR:
case OPC_OR:
case OPC_XOR:
case OPC_ANDN:
case OPC_MUXC:
case OPC_MUXNC:
case OPC_MUXZ:
case OPC_MUXNZ:
case OPC_MINU:
return (val == 0);
case OPC_ZEROX:
case OPC_SIGNX:
return (val == 31);
case OPC_AND:
return (val == -1);
case OPC_MAXU:
return (val == UINT32_MAX);
case OPC_MINS:
return (val == INT32_MIN);
case OPC_MAXS:
return (val == INT32_MAX);
default:
return false;
}
}
//
// see if all instructions between ir and the label "lab" are
// conditional, and have condition "cond"
//
static bool
AllInstructionsConditional(IRCond cond, IR *ir, Operand *lab)
{
while (ir) {
if (ir->opc == OPC_LABEL) {
if (ir->dst == lab) {
return true;
}
return false; // some other jump may go in here
} else if (!IsDummy(ir)) {
if (InstrSetsAnyFlags(ir)) {
return false;
}
if (ir->cond != cond) {
return false;
}
}
ir = ir->next;
}
return false;
}
//
// eliminate code that is unnecessary
//
int EliminateDeadCode(IRList *irl)
{
int change;
IR *ir, *ir_next;
int remove_jumps;
change = 0;
if (curfunc) {
remove_jumps = (curfunc->optimize_flags & OPT_DEADCODE) != 0;
} else {
remove_jumps = (gl_optimize_flags & OPT_DEADCODE) != 0;
}
// first case: a jump at the end to the ret label
ir = irl->tail;
while (ir && IsDummy(ir)) {
ir = ir->prev;
}
if (ir && ir->opc == OPC_JUMP && curfunc && ir->dst == FuncData(curfunc)->asmreturnlabel && !InstrIsVolatile(ir)) {
DeleteIR(irl, ir);
change = 1;
}
// now look for other dead code
ir = irl->head;
while (ir) {
ir_next = ir->next;
if (ir->opc == OPC_SETQ || ir->opc == OPC_SETQ2 || ir->opc == OPC_GENERIC_DELAY) {
ir->flags |= FLAG_KEEP_INSTR;
ir->next->flags |= FLAG_KEEP_INSTR;
}
if (InstrIsVolatile(ir)) {
/* do nothing */
} else if (ir->opc == OPC_JUMP && remove_jumps) {
if (ir->cond == COND_TRUE && !IsRegister(ir->dst->kind)) {
// dead code from here to next label
IR *x = ir->next;
while (x && x->opc != OPC_LABEL) {
ir_next = x->next;
if (!IsDummy(x) && !InstrIsVolatile(x)) {
DeleteIR(irl, x);
change = 1;
}
x = ir_next;
}
/* is the branch to the next instruction? */
if (ir_next && ir_next->opc == OPC_LABEL && ir_next->dst == ir->dst && !InstrIsVolatile(ir)) {
DeleteIR(irl, ir);
change = 1;
}
} else if (ir->cond == COND_FALSE && !InstrIsVolatile(ir)) {
DeleteIR(irl, ir);
} else {
/* if the branch skips over things that already have the right
condition, delete it
*/
if (ir->dst && !IsRegister(ir->dst->kind) && ir_next && AllInstructionsConditional(InvertCond(ir->cond), ir_next, ir->dst) && !InstrIsVolatile(ir))
{
DeleteIR(irl, ir);
change = 1;
}
}
} else if (ir->cond == COND_FALSE) {
DeleteIR(irl, ir);
change = 1;
} else if (!IsDummy(ir) && ir->dst && !HasSideEffectsOtherThanReg(ir) && IsDeadAfter(ir, ir->dst)) {
DeleteIR(irl, ir);
change = 1;
} else if (MeaninglessMath(ir)) {
DeleteIR(irl, ir);
change = 1;
}
ir = ir_next;
}
return change;
}
static void CheckOpUsage(Operand *op)
{
if (op) {
op->used = 1;
}
}
static void CheckUsage(IRList *irl)
{
IR *ir;
for (ir = irl->head; ir; ir = ir->next) {
if (ir->opc == OPC_LABEL) {
if (InstrIsVolatile(ir)) {
ir->dst->used = 1;
}
continue;
} else if (IsDummy(ir) || ir->opc == OPC_LABEL) {
continue;
}
CheckOpUsage(ir->src);
CheckOpUsage(ir->dst);
}
/* remove unused labels */
for (ir = irl->head; ir; ir = ir->next) {
if (ir->opc == OPC_LABEL && !InstrIsVolatile(ir)) {
if (ir->dst->used == 0) {
ir->opc = OPC_DUMMY;
}
}
}
}
/* checks for short forward (conditional) jumps
* returns the number of instructions forward
* or 0 if not a valid candidate for optimization
*/
static int IsSafeShortForwardJump(IR *irbase) {
int n = 0;
Operand *target;
IR *ir;
int limit = (curfunc->optimize_flags & OPT_EXTRASMALL) ? 10 : (gl_p2 ? 5 : 3);
unsigned dirty_flags = 0;
if (irbase->opc != OPC_JUMP) return 0;
if (InstrIsVolatile(irbase)) return 0;
target = irbase->dst;
if (IsRegister(target->kind)) return 0;
ir = irbase->next;
IRCond newcond = InvertCond(irbase->cond);
while (ir) {
if (!IsDummy(ir)) {
//if (ir->cond != COND_TRUE) return 0;
if (ir->opc == OPC_LABEL) {
if (ir->dst == target) return n;
else return 0;
}
unsigned problem_flags = FlagsUsedByCond(newcond) & dirty_flags;
// If flags are dirty, we can only accept instructions whose
// condition is already a subset of our new condition
if (problem_flags != 0 && !CondIsSubset(newcond,ir->cond)) {
return 0;
}
// If you're wondering about instrs with inherent flag use (NEGC etc),
// Those are not an issue, since if they aren't already conditional,
// they're either using the initial flag value or will be cought by the subset check
if (ir->flags & FLAG_CSET) dirty_flags |= FLAG_WC;
if (ir->flags & FLAG_ZSET) dirty_flags |= FLAG_WZ;
if (ir->opc == OPC_CALL) {
// calls do not preserve condition codes
dirty_flags |= FLAG_WC|FLAG_WZ;
}
if (ir->opc == OPC_DJNZ && !gl_p2) {
// DJNZ does not work conditionally in LMM
return 0;
}
if (++n > limit) return 0;
}
ir = ir->next;
}
// we reached the end... were we trying to jump to the end?
if (curfunc && target == FuncData(curfunc)->asmreturnlabel) return n;
else return 0;
}
static void ConditionalizeInstructions(IR *ir, IRCond cond, int n)
{
while (ir && n > 0) {
if (!IsDummy(ir)) {
if (ir->opc == OPC_LABEL) {
ERROR(NULL, "Internal error bad conditionalize");
return;
}
ir->cond |= cond;
--n;
}
ir = ir->next;
}
while (ir && IsDummy(ir)) {
ir = ir->next;
}
if (ir && ir->opc == OPC_LABEL) {
// this is the destination label
// mark it to check for optimization
ir->cond = cond;
}
}
int OptimizeShortBranches(IRList *irl)
{
IR *ir;
IR *ir_next;
int n;
int change = 0;
ir = irl->head;
if (gl_compress) {
return 0;
}
while (ir) {
ir_next = ir->next;
n = IsSafeShortForwardJump(ir);
if (n) {
ConditionalizeInstructions(ir->next, InvertCond(ir->cond), n);
DeleteIR(irl, ir);
change++;
}
ir = ir_next;
}
return change;
}
//
// Optimize compares with 0 by changing a previous instruction to set
// flags instead
//
static int
OptimizeCompares(IRList *irl)
{
IR *ir;
IR *ir_next;
IR *ir_prev;
int change = 0;
if (gl_compress) {
return 0;
}
ir_prev = 0;
ir = irl->head;
while (ir) {
ir_next = ir->next;
while (ir && IsDummy(ir)) {
ir = ir_next;
if (ir) ir_next = ir->next;
}
if (!ir) break;
// Convert pointless moves into CMPS S,#0
if (ir->opc == OPC_MOV && !InstrIsVolatile(ir) && !IsHwReg(ir->src)
&& (ir->flags & (FLAG_WZ|FLAG_WC)) && (ir->src == ir->dst || (IsDeadAfter(ir,ir->dst) && !IsImmediate(ir->src))) ) {
ReplaceOpcode(ir,OPC_CMPS);
ir->dst = ir->src;
ir->src = NewImmediate(0);
// Flags can stay as they are
change |= 1;
// Note that we do not break;
}
if ( (ir->opc == OPC_CMP||ir->opc == OPC_CMPS) && ir->cond == COND_TRUE
&& (ir->flags & (FLAG_WZ|FLAG_WC))
&& !InstrIsVolatile(ir)
&& ir->src == ir->dst)
{
// this compare always sets Z and clears C
ApplyConditionAfter(ir, 0);
DeleteIR(irl, ir);
change |= 1;
}
else if (ir->cond == COND_TRUE
&& ((ir->opc == OPC_CMP && IsImmediateVal(ir->src, 0)) || (ir->opc == OPC_CMPS && IsImmediateVal(ir->src, INT32_MIN)) )
&& (FLAG_WC == (ir->flags & (FLAG_WZ|FLAG_WC)))
&& !InstrIsVolatile(ir)
)
{
// this compare always clears C
ApplyConditionAfter(ir, 1);
DeleteIR(irl, ir);
change |= 1;
}
else if ( (ir->opc == OPC_CMP||ir->opc == OPC_CMPS) && ir->cond == COND_TRUE
&& (FLAG_WZ == (ir->flags & (FLAG_WZ|FLAG_WC)))
&& !InstrIsVolatile(ir)
&& IsImmediateVal(ir->src, 0)
)
{
ir_prev = FindPrevSetterForCompare(ir, ir->dst);
if (!ir_prev) {
// we can't find where that register was set? maybe it will be
// set inside a loop
IR *loopend;
IR *jmpend;
Operand *newlabel;
IR *ircmp;
IR *irlabel;
ir_prev = ir->prev;
while (ir_prev && IsDummy(ir_prev)) {
ir_prev = ir_prev->prev;
}
jmpend = ir_next;
while (jmpend && IsDummy(jmpend)) {
jmpend = jmpend->next;
}
if (ir_prev && ir_prev->opc == OPC_LABEL
&& jmpend && jmpend->opc == OPC_JUMP && jmpend->cond == COND_EQ && jmpend->aux)
{
loopend = (IR *)jmpend->aux;
loopend = loopend->prev;
while (loopend && IsDummy(loopend)) {
loopend = loopend->prev;
}
if (loopend && loopend->opc == OPC_JUMP && loopend->cond == COND_TRUE && loopend->aux && ir_prev == (IR *)loopend->aux) {
// OK, we've found the jump to loop end
// insert a new label after jmpend, copy the compare, and
// change the loopend jmp to jump to the new label
newlabel = NewCodeLabel();
irlabel = NewIR(OPC_LABEL);
irlabel->dst = newlabel;
ircmp = NewIR(ir->opc);
ircmp->cond = COND_TRUE;
ircmp->flags = ir->flags;
ircmp->dst = ir->dst;
ircmp->src = ir->src;
InsertAfterIR(irl, jmpend, irlabel);
InsertAfterIR(irl, loopend->prev, ircmp);
loopend->aux = irlabel;
loopend->dst = newlabel;
loopend->cond = COND_NE;
}
}
}
else if (ir_prev
&& !InstrSetsAnyFlags(ir_prev)
&& !InstrIsVolatile(ir_prev)
&& !InstrIsVolatile(ir)
&& ir_prev->cond == COND_TRUE
&& (ir_prev->flags & (FLAG_ZSET&~FLAG_WZ)) == 0
&& CanTestZero(ir_prev->opc)
&& FlagsNotUsedBetween(ir_prev, ir, FLAG_WZ)
&& FlagsNotSetBetween(ir_prev,ir,FLAG_WZ))
{
ir_prev->flags |= FLAG_WZ;
DeleteIR(irl, ir);
change = 1;
/* now we may be able to do a further optimization,
if ir_prev is a sub and the next instruction is a jmp
*/
if (ir_prev->opc == OPC_SUB
&& ir_next->opc == OPC_JUMP
&& ir_next->cond == COND_NE
&& IsImmediateVal(ir_prev->src, 1)
&& IsCloseJump(ir_next)
&& !UsedInRange(ir_prev->next,ir_next->prev,ir_prev->dst)
)
{
// replace jmp with djnz
ReplaceOpcode(ir_next, OPC_DJNZ);
ir_next->cond = COND_TRUE;
ir_next->src = ir_next->dst;
ir_next->dst = ir_prev->dst;
DeleteIR(irl, ir_prev);
}
}
}
ir_prev = ir;
ir = ir_next;
}
return change;
}
static int
OptimizeImmediates(IRList *irl)
{
IR *ir;
Operand *src;
int val;
int change = 0;
for (ir = irl->head; ir; ir = ir->next) {
if (InstrIsVolatile(ir)) {
continue;
}
src = ir->src;
if (! (src && src->kind == IMM_INT) ) {
continue;
}
val = src->val;
if (val != (val&31) && IsSrcBitIndex(ir)) {
// always cut unused bits when immediate is a bit index
ir->src = NewImmediate(val&31);
change++;
} else if (!gl_p2 && (src->name == NULL || src->name[0] == 0)) {
/* already a small immediate */
continue;
} else if (ir->opc == OPC_MOV && val < 0 && val >= -511) {
ReplaceOpcode(ir, OPC_NEG);
ir->src = NewImmediate(-val);
change++;
} else if (ir->opc == OPC_AND && val < 0 && val >= -512) {
ReplaceOpcode(ir, OPC_ANDN);
ir->src = NewImmediate( ~val ); /* note that is a tilde! */
change++;
} else if (ir->opc == OPC_ADD && val < 0 && val >= -511) {
ReplaceOpcode(ir, OPC_SUB);
ir->src = NewImmediate(-val);
change++;
} else if (ir->opc == OPC_SUB && val < 0 && val >= -511) {
ReplaceOpcode(ir, OPC_ADD);
ir->src = NewImmediate(-val);
change++;
}
}
return change;
}
static int
OptimizeAddSub(IRList *irl)
{
int change = 0;
IR *ir, *ir_next;
IR *prev;
ir = irl->head;
while (ir) {
ir_next = ir->next;
while (ir_next && IsDummy(ir_next)) {
ir_next = ir_next->next;
}
if (!ir_next) break;
if ((ir->opc == OPC_ADD || ir->opc == OPC_SUB) && !InstrIsVolatile(ir)) {
prev = FindPrevSetterForReplace(ir, ir->dst);
if (prev && (prev->opc == OPC_ADD || prev->opc == OPC_SUB) ) {
if (ir->src->kind == IMM_INT && prev->src->kind == IMM_INT
&& ir->cond == prev->cond)
{
int val = AddSubVal(ir) + AddSubVal(prev);
if (val < 0) {
val = -val;
ReplaceOpcode(ir, OPC_SUB);
} else {
ReplaceOpcode(ir, OPC_ADD);
}
ir->src = NewImmediate(val);
DeleteIR(irl, prev);
change = 1;
}
}
}
ir = ir_next;
}
return change;
}
//
// assign addresses to instructions
// these do not have to be exact, just close enough that they
// can help guide optimization, in particular whether jumps are
// forward or backward
//
static void
AssignTemporaryAddresses(IRList *irl)
{
IR *ir;
unsigned addr = 0;
for (ir = irl->head; ir; ir = ir->next) {
ir->flags &= ~FLAG_OPTIMIZER;
ir->addr = addr;
if (IsDummy(ir) || IsLabel(ir)) {
// do not increment
} else {
addr++;
}
if (IsJump(ir) || IsLabel(ir)) {
ir->aux = NULL;
}
}
}
//
// find out if a label is referenced (perhaps indirectly)
// if there is a unique jump to it, return a pointer to it
//
static void
MarkLabelUses(IRList *irl, IR *irlabel)
{
IR *ir;
Operand *label = irlabel->dst;
Operand *dst;
if (label->used >= 9999) {
// GOSUB labels get flagged with a large used value so they do not get taken away
irlabel->flags |= FLAG_LABEL_USED;
}
for (ir = irl->head; ir; ir = ir->next) {
if (IsDummy(ir)) continue;
if (IsJump(ir)) {
dst = JumpDest(ir);
if (dst == label) {
ir->aux = irlabel; // record where the jump goes to
if (irlabel->flags & FLAG_LABEL_USED) {
// the label has more than one use
irlabel->aux = NULL;
} else {
irlabel->flags |= FLAG_LABEL_USED;
irlabel->aux = ir;
}
}
} else if (ir != irlabel) {
if (ir->src == label || ir->dst == label) {
irlabel->flags |= FLAG_LABEL_USED;
irlabel->aux = NULL;
}
}
}
}
static bool
IsTemporaryLabel(Operand *op)
{
const char *name = op->name;
if (name && (name[0] == 'L' && name[1] == '_' && name[2] == '_')) {
return true;
}
return false;
}
//
// check label usage
//
static int
CheckLabelUsage(IRList *irl)
{
IR *ir, *ir_next;
ir = irl->head;
int change = 0;
while (ir) {
ir_next = ir->next;
if (ir->opc == OPC_LABEL) {
MarkLabelUses(irl, ir);
if ( IsTemporaryLabel(ir->dst) && !(ir->flags & (FLAG_LABEL_USED|FLAG_KEEP_INSTR))) {
DeleteIR(irl, ir);
change = 1;
}
}
ir = ir_next;
}
return change;
}
//
// replace use of NZ with C and Z with NC
//
static void
ReplaceZWithNC(IR *ir)
{
switch (ir->cond) {
case COND_EQ:
ir->cond = COND_NC;
break;
case COND_NE:
ir->cond = COND_C;
break;
case COND_TRUE:
case COND_FALSE:
break;
default:
ERROR(NULL, "Internal error, unexpected condition");
}
switch (ir->opc) {
case OPC_MUXZ:
ReplaceOpcode(ir, OPC_MUXNC);
break;
case OPC_MUXNZ:
ReplaceOpcode(ir, OPC_MUXC);
break;
case OPC_NEGZ:
ReplaceOpcode(ir, OPC_NEGNC);
break;
case OPC_NEGNZ:
ReplaceOpcode(ir, OPC_NEGC);
break;
case OPC_DRVZ:
ReplaceOpcode(ir, OPC_DRVNC);
break;
case OPC_DRVNZ:
ReplaceOpcode(ir, OPC_DRVC);
break;
case OPC_MUXC:
case OPC_MUXNC:
case OPC_NEGC:
case OPC_NEGNC:
case OPC_GENERIC:
case OPC_GENERIC_DELAY:
case OPC_GENERIC_NR:
case OPC_LOCKNEW:
case OPC_LOCKSET:
case OPC_LOCKCLR:
case OPC_LOCKRET:
case OPC_SETQ:
case OPC_SETQ2:
case OPC_PUSH:
case OPC_POP:
case OPC_RCL:
case OPC_RCR:
ERROR(NULL, "Internal error, unexpected use of C");
break;
default:
break;
}
}
static bool
IsCommutativeMath(IROpcode opc)
{
switch (opc) {
case OPC_ADD:
case OPC_OR:
case OPC_AND:
case OPC_XOR:
case OPC_TEST:
return true;
default:
return false;
}
}
// check if x is of the form (A ROL n)
// where A is a small integer that is all 1's
// in binary; if so, return a bit mask
// otherwise, return -1
static int P2CheckBitMask(unsigned int x)
{
if (x == 0 || x == 0xFFFFFFFF) return -1;
int rshift = __builtin_ctz(x);
if (rshift == 0 && (x>>31)) { // No trailing zero, but leading one -> try wraparound case
rshift = 32-__builtin_clz(~x);
}
x = x>>rshift | x<<((32-rshift)&31);
if(x&(x+1)) return -1; // x is not (2^n)-1
int addbits = 31-__builtin_clz(x);
if (addbits > 15) return -1; // Doesn't fit in 9 bits
return rshift + (addbits<<5);
}
static bool
FlagsDeadAfter(IRList *irl, IR *ir, unsigned flags)
{
if (!ir) return true;
ir = ir->next;
while (ir && flags) {
if (IsLabel(ir)) {
return true;
}
if (ir->cond != COND_TRUE) {
return false;
}
if (InstrUsesFlags(ir, flags)) {
return false;
}
if (InstrSetsFlags(ir, flags)) {
flags &= ~(ir->flags);
}
if (!flags) {
return true;
}
ir = ir->next;
}
return true;
}
//
// basic peephole substitution
//
// mov tmp, x
// and tmp, y wz
// becomes test x,y wz if tmp is dead
//
// test tmp, #1 wz
// shr tmp, #1
// becomes shr tmp, #1 wc if we can replace NZ with C
//
// similarly for test tmp, #$8000_0000 wz ; shl tmp, #1
//
// if_c or a, b
// if_nc andn a, b
// becomes muxc a, b
//
// and x, #0xf
// mov y, x
// and y #0xff
//
// can remove the last and, it is redundant
//
// add objptr, x
// mov tmp, objptr
// sub objptr, x
// becomes mov tmp,objptr
// add tmp,objptr
//
// mov a,b
// mov b,a
// we can delete the second mov
// add a,b
// mov b,a
// becomes add b, a, if a is dead
// mov a, #1
// shl a, N
// becomes decod a, N on P2
// xor a, #(1<<x)
// becomes bitnot a, #x on P2
int
OptimizePeepholes(IRList *irl)
{
IR *ir, *ir_next;
IR *previr;
int changed = 0;
IROpcode opc;
ir = irl->head;
while (ir) {
ir_next = ir->next;
while (ir_next && IsDummy(ir_next)) {
ir_next = ir_next->next;
}
if (InstrIsVolatile(ir) || ir->srceffect != OPEFFECT_NONE || ir->dsteffect != OPEFFECT_NONE) {
goto done;
}
opc = ir->opc;
if ( (opc == OPC_AND || opc == OPC_OR)
&& IsImmediate(ir->src)
&& !InstrSetsFlags(ir, FLAG_WC)
)
{
previr = FindPrevSetterForReplace(ir, ir->dst);
if (previr && previr->opc == OPC_MOV && !IsImmediate(previr->src)) {
previr = FindPrevSetterForReplace(previr, previr->src);
}
if (previr && previr->opc == opc && IsImmediate(previr->src)) {
unsigned oldmask = previr->src->val;
unsigned newmask = ir->src->val;
// check to see if ir is redundant
if (opc == OPC_AND && ((oldmask & newmask) == oldmask)) {
if (InstrSetsFlags(ir, FLAG_WZ)) {
ReplaceOpcode(ir, OPC_CMP);
ir->src->val = 0;
changed = 1;
} else if (!InstrSetsAnyFlags(ir)) {
DeleteIR(irl, ir);
changed = 1;
}
goto done;
} else if (opc == OPC_OR && ((oldmask | newmask) == oldmask)) {
if (InstrSetsFlags(ir, FLAG_WZ)) {
ReplaceOpcode(ir, OPC_CMP);
ir->src->val = 0;
changed = 1;
} else if (!InstrSetsAnyFlags(ir)) {
DeleteIR(irl, ir);
changed = 1;
}
goto done;
}
}
}
if (opc == OPC_AND && InstrSetsAnyFlags(ir)) {
previr = FindPrevSetterForReplace(ir, ir->dst);
if (previr && previr->opc == OPC_MOV && IsDeadAfter(ir, ir->dst) && !SrcOnlyHwReg(previr->src) && IsRegister(previr->src->kind)) {
ReplaceOpcode(ir, OPC_TEST);
ir->dst = previr->src;
DeleteIR(irl, previr);
changed = 1;
} else if (IsDeadAfter(ir, ir->dst)) {
ReplaceOpcode(ir, OPC_TEST);
changed = 1;
}
} else if ( (opc == OPC_SHR || opc == OPC_SAR)
&& !InstrSetsFlags(ir, FLAG_WC)
&& !InstrUsesFlags(ir, FLAG_WC|FLAG_WZ)
&& IsImmediateVal(ir->src, 1))
{
previr = FindPrevSetterForReplace(ir, ir->dst);
if (previr && previr->opc == OPC_TEST
&& IsImmediateVal(previr->src, 1))
{
/* maybe we can replace the test with the shr */
/* we already know the result isn't used between previr
and ir; check the instructions in between for use
of C, and also verify that the flags aren't used
in subsequent instructions
*/
int test_is_z = (previr->flags & (FLAG_WZ|FLAG_WC)) == FLAG_WZ;
int test_is_c = (previr->flags & (FLAG_WZ|FLAG_WC)) == FLAG_WC;
IR *testir;
IR *lastir = NULL;
bool sawir = false;
bool changeok = test_is_z || test_is_c;
int irflags = (ir->flags & FLAG_WZ) | FLAG_WC;
for (testir = previr->next; testir && changeok; testir = testir->next) {
if (testir == ir) {
sawir = true;
}
if (IsBranch(testir)) {
/* we assume flags do not have to be preserved across branches*/
lastir = testir;
break;
}
if (test_is_z && InstrUsesFlags(testir, FLAG_WC)) {
changeok = false;
} else if (InstrSetsAnyFlags(testir)) {
changeok = sawir;
lastir = testir;
break;
}
}
if (changeok) {
/* ok, let's go ahead and change it */
ReplaceOpcode(previr, opc);
previr->flags &= ~(FLAG_WZ|FLAG_WC);
previr->flags |= irflags;
if (test_is_z) {
for (testir = previr->next; testir && testir != lastir;
testir = testir->next)
{
ReplaceZWithNC(testir);
}
if (IsBranch(lastir)) {
ReplaceZWithNC(lastir);
}
}
DeleteIR(irl, ir);
changed = 1;
goto done;
}
}
} else if ( (opc == OPC_SHL || opc == OPC_ROL)
&& !InstrSetsFlags(ir, FLAG_WC)
&& !InstrUsesFlags(ir, FLAG_WC|FLAG_WZ)
&& IsImmediateVal(ir->src, 1))
{
previr = FindPrevSetterForReplace(ir, ir->dst);
if (previr &&
( (previr->opc == OPC_TEST
&& IsImmediateVal(previr->src, 0x80000000))
|| (previr->opc == OPC_TESTBN
&& IsImmediateVal(previr->src, 31))
)
&& (previr->flags & (FLAG_WZ|FLAG_WC)) == FLAG_WZ)
{
/* maybe we can replace the test with the shl */
/* we already know the result isn't used between previr
and ir; check the instructions in between for use
of C, and also verify that the flags aren't used
in subsequent instructions
*/
IR *testir;
IR *lastir = NULL;
bool sawir = false;
bool changeok = true;
int irflags = (ir->flags & FLAG_WZ) | FLAG_WC;
for (testir = previr->next; testir && changeok; testir = testir->next) {
if (testir == ir) {
sawir = true;
}
if (IsBranch(testir)) {
/* we assume flags do not have to be preserved across branches*/
lastir = testir;
break;
}
if (InstrUsesFlags(testir, FLAG_WC)) {
changeok = false;
} else if (InstrSetsAnyFlags(testir)) {
changeok = sawir;
lastir = testir;
break;
}
}
if (changeok) {
/* ok, let's go ahead and change it */
ReplaceOpcode(previr, opc);
previr->src = NewImmediate(1); // change to shl #1 wc
previr->flags &= ~(FLAG_WZ|FLAG_WC);
previr->flags |= irflags;
for (testir = previr->next; testir && testir != lastir;
testir = testir->next)
{
ReplaceZWithNC(testir);
}
if (IsBranch(lastir)) {
ReplaceZWithNC(lastir);
}
DeleteIR(irl, ir);
changed = 1;
goto done;
}
}
}
else if (opc == OPC_OR && ir->cond == COND_C && !InstrSetsAnyFlags(ir)
&& ir_next && ir_next->opc == OPC_ANDN && ir_next->cond == COND_NC
&& !InstrSetsAnyFlags(ir_next)
&& ir->src == ir_next->src
&& ir->dst == ir_next->dst)
{
ir_next->cond = COND_TRUE;
ReplaceOpcode(ir_next, OPC_MUXC);
DeleteIR(irl, ir);
changed = 1;
goto done;
}
else if (opc == OPC_OR && ir->cond == COND_NE && !InstrSetsAnyFlags(ir)
&& ir_next
&& ir_next->opc == OPC_ANDN && ir_next->cond == COND_EQ
&& !InstrSetsAnyFlags(ir_next)
&& ir->src == ir_next->src
&& ir->dst == ir_next->dst)
{
ir_next->cond = COND_TRUE;
ReplaceOpcode(ir_next, OPC_MUXNZ);
DeleteIR(irl, ir);
changed = 1;
goto done;
}
else if (opc == OPC_MOV && !InstrSetsAnyFlags(ir)
&& ir_next
&& !InstrSetsAnyFlags(ir_next)
&& ir_next->cond == ir->cond
&& ir_next->opc == OPC_SUB
&& ir_next->dst == ir->src
&& 0 != (previr = FindPrevSetterForReplace(ir, ir->src))
&& previr->cond == ir->cond
&& previr->opc == OPC_ADD
&& previr->src == ir_next->src
&& previr->dst == ir_next->dst
&& !InstrSetsAnyFlags(ir_next)
)
{
// add ptr, y '' previr
// mov a, ptr '' ir
// sub ptr, y '' ir_next
// => mov a, x
// add a, y
ReplaceOpcode(ir_next, OPC_ADD);
ir_next->dst = ir->dst;
DeleteIR(irl, previr);
changed = 1;
goto done;
}
else if (gl_p2
&& opc == OPC_MOV && !InstrSetsAnyFlags(ir)
&& ir_next
&& !InstrSetsAnyFlags(ir_next)
&& ir_next->cond == ir->cond
&& ir_next->opc == OPC_SHL
&& ir->dst == ir_next->dst
&& IsImmediateVal(ir->src, 1)
)
{
// mov x, #1
// shl x, y
// -> decod x, y
ReplaceOpcode(ir_next, OPC_DECOD);
DeleteIR(irl, ir);
goto done;
}
// check for mov a,b ;; mov b,a
if (opc == OPC_MOV && ir_next && ir_next->opc == OPC_MOV
&& ir->dst == ir_next->src
&& ir->src == ir_next->dst
&& !InstrSetsAnyFlags(ir)
&& !InstrSetsAnyFlags(ir_next)
&& ir->cond == ir_next->cond)
{
ir_next->dst = ir->dst;
ir_next->src = ir->src;
DeleteIR(irl, ir);
changed = 1;
goto done;
}
// check for and a, x ;; test a, x wcz
if (ir->opc == OPC_TEST && ir->cond == COND_TRUE)
{
IR *previr = FindPrevSetterForReplace(ir, ir->dst);
if (previr && previr->opc == OPC_AND && !InstrSetsAnyFlags(previr) && previr->cond == COND_TRUE && SameOperand(previr->src, ir->src))
{
if (IsDeadAfter(ir, ir->dst)) {
DeleteIR(irl, previr);
} else {
previr->flags |= (ir->flags & (FLAG_WC|FLAG_WZ));
DeleteIR(irl, ir);
}
changed = 1;
goto done;
}
}
// check for add a,b ;; mov b,a ;; isdead a
// becomes add b, a
if ( (IsCommutativeMath(opc) || (gl_p2 && opc == OPC_SUB))
&& ir_next && ir_next->opc == OPC_MOV
&& ir->dst == ir_next->src
&& ir->src == ir_next->dst
&& !InstrSetsAnyFlags(ir)
&& !InstrSetsAnyFlags(ir_next)
&& ir->cond == ir_next->cond
&& IsDeadAfter(ir_next, ir->dst)
)
{
ReplaceOpcode(ir_next, opc == OPC_SUB ? OPC_SUBR : opc);
DeleteIR(irl, ir);
changed = 1;
goto done;
}
int32_t tmp;
// AND -> GET* optimization
if (gl_p2 && isMaskingOp(ir,&tmp) && !InstrSetsAnyFlags(ir)) {
IROpcode getopc;
int shift;
switch (tmp) {
case 0xF:
getopc = OPC_GETNIB;
shift = 2;
break;
case 0xFF:
getopc = OPC_GETBYTE;
shift = 3;
break;
case 0xFFFF:
getopc = OPC_GETWORD;
shift = 4;
break;
default: goto no_getx;
}
IR *previr;
int which = 0;
previr = FindPrevSetterForReplace(ir,ir->dst);
if (previr && (previr->opc == OPC_SHR || previr->opc == OPC_SAR)
&& !InstrSetsAnyFlags(ir) && previr->src->kind == IMM_INT
&& (previr->src->val & ((1<<shift)-1)) == 0) {
which = (previr->src->val&31)>>shift;
DeleteIR(irl,previr);
changed = 1;
} else if (previr && previr->opc == getopc) {
// No-op
ir->cond = COND_FALSE;
changed = 1;
goto done;
}
if (ir->opc != getopc) {
ReplaceOpcode(ir,getopc);
changed = 1;
}
if (!ir->src2 || !IsImmediateVal(ir->src2,which)) {
ir->src2 = NewImmediate(which);
changed = 1;
}
ir->src = ir->dst;
goto done;
}
no_getx:
// on P2, check for immediate operand with just one bit set
if (gl_p2 && ir->src && ir->src->kind == IMM_INT && !InstrSetsAnyFlags(ir) && ((uint32_t)ir->src->val) > 511) {
if (ir->opc == OPC_AND) {
int invmask = P2CheckBitMask(~(ir->src->val));
if (invmask != -1) {
ReplaceOpcode(ir, OPC_BITL);
ir->src = NewImmediate(invmask);
changed = 1;
goto done;
}
}
int mask = P2CheckBitMask(ir->src->val);
if (mask != -1) {
if (ir->opc == OPC_ANDN) {
ReplaceOpcode(ir, OPC_BITL);
ir->src = NewImmediate(mask);
changed = 1;
goto done;
}
if (ir->opc == OPC_OR) {
ReplaceOpcode(ir, OPC_BITH);
ir->src = NewImmediate(mask);
changed = 1;
goto done;
}
if (ir->opc == OPC_XOR) {
ReplaceOpcode(ir, OPC_BITNOT);
ir->src = NewImmediate(mask);
changed = 1;
goto done;
}
if (ir->opc == OPC_MOV && mask < 32) {
ReplaceOpcode(ir, OPC_DECOD);
ir->src = NewImmediate(mask);
changed = 1;
goto done;
}
}
if (ir->opc == OPC_MOV || ir->opc == OPC_AND || ir->opc == OPC_ANDN) {
uint32_t mask = ir->src->val;
if (ir->opc == OPC_ANDN) mask = ~mask;
int bits = 0;
while ( (mask & 1) ) {
bits++;
mask = mask >> 1;
}
if (bits > 0 && mask == 0) {
// could use BMASK/ZEROX instruction
ReplaceOpcode(ir, ir->opc == OPC_MOV ? OPC_BMASK : OPC_ZEROX);
ir->src = NewImmediate(bits-1);
changed = 1;
goto done;
}
}
}
else if (gl_p2 && ir->opc == OPC_TEST && ir->flags == FLAG_WZ)
{
// this code isn't finished yet
int mask = P2CheckBitMask(ir->src->val);
if (mask==(mask & 0x1f) // just one bit set
&& ((unsigned)ir->src->val) > 511) // and a large constant
{
ReplaceOpcode(ir, OPC_TESTBN);
ir->src = NewImmediate(mask);
changed = 1;
goto done;
}
}
done:
ir = ir_next;
}
return changed;
}
/* special peephole for buf[i++] := n */
/* look for mov tmp, b; add b, #1; use tmp */
/* in this case push the add b, #1 as far forward as we can */
static int
OptimizeIncDec(IRList *irl)
{
IR *ir, *ir_next;
ir = irl->head;
int change = 0;
while (ir) {
ir_next = ir->next;
while (ir_next && IsDummy(ir_next)) {
ir_next = ir_next->next;
}
if (ir->opc == OPC_MOV
&& IsLocal(ir->dst)
&& ir->cond == COND_TRUE
&& ir_next
&& (ir_next->opc == OPC_ADD || ir_next->opc == OPC_SUB)
&& ir_next->dst == ir->src
&& IsImmediate(ir_next->src)
&& !InstrIsVolatile(ir)
&& !InstrIsVolatile(ir_next)
&& !InstrSetsAnyFlags(ir_next)
)
{
// push the add forward in the instruction stream as far as we can
IR *placeir = NULL;
IR *stepir = ir_next->next;
Operand *changedOp = ir_next->dst;
while (stepir) {
if (IsJump(stepir))
break;
if (IsCallThatUsesReg(stepir,changedOp))
break;
if (IsLabel(stepir))
break;
if (stepir->dst == changedOp || stepir->src == changedOp) {
// cannot push any further
break;
}
if (InstrModifies(stepir, changedOp)) {
// also cannot push further
break;
}
// technically we could push past conditionals, but
// the code may look ugly if we do
if (stepir->cond != COND_TRUE)
break;
placeir = stepir;
stepir = stepir->next;
}
if (placeir) {
DeleteIR(irl, ir_next);
ir_next->next = NULL;
InsertAfterIR(irl, placeir, ir_next);
change = 1;
}
}
ir = ir->next;
}
return change;
}
/* helper function: see if we can find any registers in this IRL that
* use the name "name". This is needed because some indirect operations
* create COG labels that don't point back to the original Operand; to
* de-reference those and convert back to the original we need to search
* for it
*/
static Operand *
FindNamedOperand(IRList *irl, const char *name, int val)
{
IR *ir;
for (ir = irl->head; ir; ir = ir->next) {
if (IsDummy(ir) || IsLabel(ir)) continue;
if (ir->dst && IsRegister(ir->dst->kind) && ir->dst->val == val) {
if (!strcmp(ir->dst->name, name)) {
return ir->dst;
}
}
if (ir->src && IsRegister(ir->src->kind) && ir->src->val == val) {
if (!strcmp(ir->src->name, name)) {
return ir->src;
}
}
}
// if we get here, punt
return NewOperand(REG_HW, name, val);
}
/* optimizer for COG memory accesses
* if we see something like:
* movs wrcog, #x
* movd wrcog, #y
* call #wrcog
* we can replace it with
* mov x, y
*/
extern Operand *putcogreg;
static int
IsMovIndirect(IR *ir, IR *ir_prev, IR *ir_next)
{
if (!ir_prev
|| ir_prev->opc != OPC_LIVE)
{
return 0;
}
if (!ir_next) {
return 0;
}
if (ir->opc == OPC_MOVS
&& ir->dst == putcogreg
&& ir->src->kind == IMM_COG_LABEL
&& ir_next
&& ir_next->opc == OPC_MOVD
&& ir_next->dst == putcogreg
&& ir_next->src->kind == IMM_COG_LABEL
&& ir_next->next
&& ir_next->next->opc == OPC_CALL
&& ir_next->next->dst == putcogreg
)
{
return 1;
}
if (0 && gl_p2
&& ir->opc == OPC_MOV
&& ir->dst == ir_next->dst
&& ir->src->kind == IMM_COG_LABEL
&& ir_next->opc == OPC_ALTS
&& ir_next->src->kind == IMM_INT
&& ir_next->src->val == 0
&& ir_next->next
&& ir_next->next->opc == OPC_MOV
&& ir_next->next->src == ir_next->dst
)
{
return 2;
}
return 0;
}
static int
OptimizeCogWrites(IRList *irl)
{
IR *ir, *ir_next, *ir_prev;
int change = 0;
int x;
ir = irl->head;
ir_prev = NULL;
while (ir) {
ir_next = ir->next;
x = IsMovIndirect(ir, ir_prev, ir_next);
if (x)
{
Operand *src = ir->src;
Operand *dst = ir_next->src;
if (!strcmp(src->name, ir_prev->dst->name)) {
src = ir_prev->dst;
}
if (!strcmp(dst->name, ir_prev->dst->name)) {
dst = ir_prev->dst;
}
if (dst->kind == IMM_COG_LABEL) {
dst = FindNamedOperand(irl, dst->name, dst->val);
}
if (src->kind == IMM_COG_LABEL) {
src = FindNamedOperand(irl, src->name, src->val);
}
if (1) {
ReplaceOpcode(ir, OPC_MOV);
ir->dst = dst;
ir->src = src;
ir_prev->opc = OPC_DUMMY;
ir_next->opc = OPC_DUMMY;
ir_next->next->opc = OPC_DUMMY;
change = 1;
}
}
ir_prev = ir;
ir = ir_next;
}
return change;
}
/* the code generator produces some obviously silly sequences
* like: mov T, A; op T, B; mov A, T
* replace those with op A, B... but ONLY if T is dead after the 3rd one
*/
static int
OptimizeSimpleAssignments(IRList *irl)
{
int change = 0;
IR *ir, *ir_next, *ir_prev;
ir_prev = ir_next = NULL;
ir = irl->head;
while (ir) {
ir_next = ir->next;
if (ir_prev && ir_next
&& ir_prev->opc == OPC_MOV && ir_next->opc == OPC_MOV
&& ir_prev->dst == ir_next->src && ir_prev->src == ir_next->dst
&& ir->dst == ir_prev->dst
&& ir_prev->cond == ir->cond
&& ir_next->cond == ir->cond
&& IsMathInstr(ir)
&& !InstrIsVolatile(ir) && !InstrIsVolatile(ir_prev) && !InstrIsVolatile(ir_next)
&& !InstrSetsAnyFlags(ir)
&& !InstrSetsAnyFlags(ir_prev)
&& !InstrSetsAnyFlags(ir_next)
&& IsDeadAfter(ir_next, ir_next->src)
)
{
ir->dst = ir_next->dst;
ir = ir_next;
ir_next = ir->next;
change = 1;
DeleteIR(irl, ir);
if (IsDeadAfter(ir_prev, ir_prev->dst)) {
DeleteIR(irl, ir_prev);
ir_prev = NULL;
}
}
ir_prev = ir;
ir = ir_next;
}
return change;
}
/* perform P2 specific optimizations */
int
OptimizeP2(IRList *irl)
{
IR *ir, *ir_next;
IR *previr;
int changed = 0;
int opc;
ir = irl->head;
while (ir) {
ir_next = ir->next;
while (ir_next && IsDummy(ir_next)) {
ir_next = ir_next->next;
}
opc = ir->opc;
if (opc == OPC_ADDCT1 && IsImmediateVal(ir->src, 0)) {
previr = FindPrevSetterForReplace(ir, ir->dst);
if (previr && previr->opc == OPC_ADD && !InstrSetsAnyFlags(previr)) {
// add foo, val / addct1 foo, #0 -> addct1 foo, val
ir->src = previr->src;
DeleteIR(irl, previr);
changed = 1;
}
}
if ( (opc == OPC_DJNZ || opc == OPC_JUMP) && ir->cond == COND_TRUE) {
// see if we can change the loop to use "repeat"
Operand *var;
Operand *dst;
IR *labir = NULL;
IR *pir = NULL;
IR *repir = NULL;
bool canRepeat = true;
bool didAnything = false;
if (opc == OPC_DJNZ) {
var = ir->dst;
dst = ir->src;
} else {
var = NULL;
dst = ir->dst;
}
if (var == NULL || IsDeadAfter(ir, var)) {
for (pir = ir->prev; pir; pir = pir->prev) {
if (pir->opc == OPC_LABEL) {
if (pir->dst != dst) {
canRepeat = false;
}
break;
} else if (IsBranch(pir) || pir->opc == OPC_BREAK) {
canRepeat = false;
break;
} else if (var && (pir->src == var || pir->dst == var)) {
canRepeat = false;
break;
} else if (!IsDummy(pir)) {
didAnything = true;
}
}
if (pir && canRepeat && didAnything) {
pir = pir->prev; // WARNING: could be NULL, but InsertAfterIR will handle that
labir = NewIR(OPC_LABEL);
labir->dst = NewCodeLabel();
repir = NewIR(OPC_REPEAT);
repir->dst = labir->dst;
repir->src = var ? var : NewImmediate(0);
repir->aux = labir;
labir->aux = repir;
InsertAfterIR(irl, pir, repir);
InsertAfterIR(irl, ir, labir);
ir->dst = dst;
ir->src = NULL;
ir->opc = OPC_REPEAT_END;
ir->instr = NULL;
changed = 1;
}
}
}
ir = ir_next;
}
return changed;
}
//
// find the next IR after orig that uses dest
//
static IR* FindNextUse(IR *ir, Operand *dst)
{
ir = ir->next;
while (ir) {
if (InstrUses(ir, dst)) {
return ir;
}
if (InstrModifies(ir, dst)) {
// modifies but does not use? abort
return NULL;
}
if (IsJump(ir)) {
return NULL;
}
if (ir->opc == OPC_LABEL) {
return NULL;
}
ir = ir->next;
}
return NULL;
}
//
// find the next rdlong that uses src
// returns NULL if we spot anything that changes src, dest,
// memory, or a branch
//
static IR* FindNextRead(IR *irorig, Operand *dest, Operand *src)
{
IR *ir;
int32_t offset = 0;
for ( ir = irorig->next; ir; ir = ir->next) {
if (IsDummy(ir)) continue;
if (ir->opc == OPC_LABEL) {
return NULL;
}
if (IsBranch(ir)) {
if (ir->opc == OPC_CALL &&
(ir->dst == mulfunc || ir->dst == divfunc || ir->dst == unsdivfunc)
) {
// Do nothing
} else {
return NULL;
}
}
if (ir->cond != irorig->cond) {
return NULL;
}
if (ir->src == src && offset == 0 && (ir->opc == OPC_RDLONG||ir->opc == OPC_RDWORD||ir->opc == OPC_RDBYTE)) {
return ir;
}
if ((ir->opc == OPC_ADD || ir->opc == OPC_SUB) && ir->dst == src && ir->src && ir->src->kind == IMM_INT) {
if (ir->opc == OPC_ADD) offset += ir->src->val;
else offset -= ir->src->val;
} else if (InstrModifies(ir, dest) || InstrModifies(ir, src)) {
return NULL;
}
if (IsWrite(ir)) {
return NULL;
}
}
return NULL;
}
static int
MemoryOpSize(IR *ir) {
if (!ir) {
return 0;
}
switch (ir->opc) {
case OPC_RDBYTE:
case OPC_WRBYTE:
return 1;
case OPC_RDWORD:
case OPC_WRWORD:
return 2;
case OPC_RDLONG:
case OPC_WRLONG:
return 4;
default:
return 0;
}
}
// true if ir represents a real instruction which does not
// read/write memory
static bool
IsNonReadWriteOpcode(IR *ir)
{
int opc;
if (!ir) {
return false;
}
opc = (int)ir->opc;
if (opc < OPC_GENERIC && !IsReadWrite(ir)) {
return true;
}
return false;
}
//
// return true if it's OK to swap IR a and b
// if a changes b's src, then no
//
static bool
CanSwap(IR *a, IR *b)
{
if (InstrSetsAnyFlags(a) || InstrSetsAnyFlags(b)) return false;
if (a->cond != b->cond) return false;
if (InstrIsVolatile(a) || InstrIsVolatile(b)) return false;
if (IsBranch(a) || IsBranch(b)) return false;
if (InstrModifies(a, b->src)) return false;
if (InstrUses(b, a->dst)) return false;
if (InstrModifies(b, a->src)) return false;
if (InstrUses(a, b->dst)) return false;
return true;
}
//
// optimize read/write calls
// rdlong a,b
// rdlong c,b
// can become
// rdlong a, b
// mov c, a
// also in:
// rdbyte a, b
// and a, #255
// we can skip the "and"
static int
OptimizeReadWrite(IRList *irl)
{
Operand *base;
Operand *dst1;
IR *ir;
IR *nextread;
IR *next_ir, *prev_ir;
int change = 0;
restart_check:
prev_ir = next_ir = NULL;
ir = irl->head;
while (ir) {
next_ir = ir->next;
while (next_ir && IsDummy(next_ir)) {
next_ir = next_ir->next;
}
if (InstrIsVolatile(ir)) {
goto get_next;
}
if (ir->srceffect != OPEFFECT_NONE || ir->dsteffect != OPEFFECT_NONE) {
goto get_next;
}
if (ir->opc == OPC_RDLONG || ir->opc == OPC_WRLONG
|| ir->opc == OPC_RDWORD || ir->opc == OPC_WRWORD
|| ir->opc == OPC_RDBYTE || ir->opc == OPC_WRBYTE) {
// don't mess with it if prev instr was OPC_SETQ
if (prev_ir && (prev_ir->opc == OPC_SETQ || prev_ir->opc == OPC_SETQ2)) {
prev_ir->flags |= FLAG_KEEP_INSTR;
goto get_next;
}
dst1 = ir->dst;
base = ir->src;
int size = MemoryOpSize(ir);
bool write = IsWrite(ir);
// don't mess with it if src==dst
if (!write && ir->src == ir->dst) goto get_next;
nextread = FindNextRead(ir, dst1, base);
int nextsize = MemoryOpSize(nextread);
if (nextread && CondIsSubset(ir->cond,nextread->cond)) {
// wrlong a, b ... rdlong c, b -> mov c, a
// rdlong a, b ... rdlong c, b -> mov c, a
if(size == nextsize && (!write || size==4) && (gl_p2 || !InstrSetsFlags(nextread,FLAG_WC)) ) {
nextread->src = dst1;
ReplaceOpcode(nextread, OPC_MOV);
change = 1;
goto get_next;
}
}
}
if (ir->opc == OPC_RDBYTE || ir->opc == OPC_RDWORD) {
int32_t mval;
dst1 = ir->dst;
int mask = ir->opc == OPC_RDBYTE ? 0xFF : 0xFFFF;
nextread = FindNextUse(ir, dst1);
if (nextread
&& nextread->dst == dst1
&& !InstrSetsAnyFlags(nextread)
&& isMaskingOp(nextread,&mval)
&& mval == mask)
{
// don't need zero extend after rdbyte
change = 1;
nextread->opc = OPC_DUMMY;
}
}
// cut unneccessary bits for immediate write values
if (gl_p2 && (ir->opc == OPC_WRBYTE || ir->opc == OPC_WRWORD) && ir->dst && ir->dst->kind == IMM_INT) {
int mask = ir->opc == OPC_WRBYTE ? 0xFF : 0xFFFF;
if ((ir->dst->val & mask) != ir->dst->val) {
ir->dst = NewImmediate(ir->dst->val & mask);
change = 1;
}
}
#if 1
// try to avoid having two read/write ops in a row
if (IsReadWrite(ir) && IsReadWrite(next_ir) && IsNonReadWriteOpcode(prev_ir)) {
if (CanSwap(ir, prev_ir)) {
// want to swap prev_ir and ir here
DeleteIR(irl, prev_ir); // remove prev_ir from list
prev_ir->next = NULL;
InsertAfterIR(irl, ir, prev_ir); // move it to later
ir = prev_ir;
change = 1;
goto restart_check;
}
}
#endif
get_next:
prev_ir = ir;
ir = next_ir;
}
return change;
}
static void
DoReorderBlock(IRList *irl,IR *after,IR *top,IR *bottom) {
IR *above = top->prev;
IR *below = bottom->next;
// Unlink block
if (above) above->next = below;
else irl->head = below;
if (below) below->prev = above;
else irl->tail = above;
// Link block at new location
top->prev = after;
bottom->next = after->next;
if (after->next) after->next->prev = bottom;
else irl->tail = bottom;
after->next = top;
}
// Pull matching add/sub instructions out of loops
static int
OptimizeLoopPtrOffset(IRList *irl) {
int change = 0;
// Find loops
for (IR *ir=irl->head;ir;ir=ir->next) {
if (IsLabel(ir) && ir->prev && ir->aux && IsJump(ir->aux) && !IsForwardJump(ir->aux)) {
IR *end = ir->aux;
// Find top add/sub
IR *nexttop;
for(IR *top=ir->next;top&&top!=end;top=nexttop) {
nexttop = top->next;
if (!IsDummy(top)
&& (top->opc == OPC_ADD || top->opc == OPC_SUB)
&& top->cond == COND_TRUE && top->src->kind == IMM_INT
&& !HasSideEffectsOtherThanReg(top)) {
// Try to find matching sub/add that's safe to move out of the loop
for(IR *bot=end->prev;bot&&bot!=top;bot=bot->prev) {
if (!IsDummy(bot) && 1
&& (bot->opc == OPC_ADD || bot->opc == OPC_SUB)
&& bot->dst == top->dst && bot->src->kind == IMM_INT
&& bot->cond == COND_TRUE
&& !HasSideEffectsOtherThanReg(bot)
&& AddSubVal(bot) == 0-AddSubVal(top)
&& !UsedInRange(ir->next,top->prev,top->dst) && !UsedInRange(bot->next,end->prev,top->dst)
&& !ModifiedInRange(ir->next,top->prev,top->dst) && !ModifiedInRange(bot->next,end->prev,top->dst)
&& !ModifiedInRange(top->next,bot->prev,top->dst)) {
DoReorderBlock(irl,ir->prev,top,top);
DoReorderBlock(irl,end,bot,bot);
change++;
break;
}
}
}
}
}
}
return change;
}
//
// optimize for tail calls
static int
OptimizeTailCalls(IRList *irl, Function *f)
{
IR *ir = irl->head;
IR *irnext;
int change = 0;
if (f->local_address_taken) {
// &local_var; do not try to optimize
return change;
}
while (ir) {
if (ir->opc == OPC_CALL && ir->dst == FuncData(f)->asmname) {
irnext = NextInstructionFollowJumps(ir);
if (!irnext)
{
ReplaceOpcode(ir, OPC_JUMP);
ir->dst = FuncData(f)->asmentername;
change = 1;
}
}
ir = ir->next;
}
return change;
}
// optimize jumps: jmp #A where the instruction after A is jmp #B gets
// turned into jmp #B
static int
OptimizeJumps(IRList *irl)
{
IR *ir = irl->head;
IR *jmpdest;
int change = 0;
while (ir) {
// internal jumptables are marked volatile (to avoid removal) but
// we should allow jmp to jmp, so they're also marked with
// FLAG_JMPTABLE_INSTR
if (ir->opc == OPC_JUMP && (!InstrIsVolatile(ir) || ir->flags & FLAG_JMPTABLE_INSTR)) {
// ptr to jump destination (if known) is in aux; see if it's also a jump
jmpdest = NextInstruction((IR *)ir->aux);
if (jmpdest && jmpdest->opc == OPC_JUMP && jmpdest->cond == COND_TRUE && jmpdest->aux && jmpdest != ir && jmpdest->dst != ir->dst) {
ir->dst = jmpdest->dst;
ir->aux = jmpdest->aux;
change++;
}
}
ir = ir->next;
}
return change;
}
static bool IsPrefixOpcode(IR *ir) {
if (!ir) return false;
switch (ir->opc) {
case OPC_GENERIC_DELAY:
case OPC_SETQ:
case OPC_SETQ2:
return true;
default:
return false;
}
}
static bool IsCordicCommand(IR *ir) {
if (!ir) return false;
switch (ir->opc) {
case OPC_QMUL:
case OPC_QDIV:
case OPC_QFRAC:
case OPC_QROTATE:
case OPC_QSQRT:
case OPC_QVECTOR:
case OPC_QLOG:
case OPC_QEXP:
return true;
default:
return false;
}
}
static bool IsCordicGet(IR *ir) {
if (!ir) return false;
switch (ir->opc) {
case OPC_GETQX:
case OPC_GETQY:
return true;
default:
return false;
}
}
static bool IsReorderBarrier(IR *ir) {
if (!ir||InstrIsVolatile(ir)||IsBranch(ir)||IsLabel(ir)) return true;
if (ir->dst&&IsHwReg(ir->dst)) return true;
if (ir->src&&IsHwReg(ir->src)) return true;
switch (ir->opc) {
case OPC_GENERIC:
case OPC_GENERIC_NR:
case OPC_GENERIC_NR_NOFLAGS:
case OPC_GENERIC_DELAY:
case OPC_GENERIC_NOFLAGS:
case OPC_LOCKCLR:
case OPC_LOCKNEW:
case OPC_LOCKRET:
case OPC_LOCKSET:
case OPC_WAITCNT:
case OPC_WAITX:
case OPC_COGSTOP:
case OPC_ADDCT1:
case OPC_HUBSET:
case OPC_QDIV: // TODO
case OPC_QFRAC:
case OPC_QMUL:
case OPC_QSQRT:
case OPC_QROTATE:
case OPC_QVECTOR:
case OPC_QLOG:
case OPC_QEXP:
case OPC_GETQX: // TODO
case OPC_GETQY:
case OPC_DRVC:
case OPC_DRVNC:
case OPC_DRVL:
case OPC_DRVH:
case OPC_DRVNZ:
case OPC_DRVZ:
case OPC_PUSH:
case OPC_POP:
case OPC_FCACHE:
case OPC_RCL:
case OPC_RCR:
return true;
default:
return false;
}
}
struct reorder_block {
unsigned count; // If zero, everything else is invalid
IR *top,*bottom;
};
// a kingdom for a std::vector....
struct dependency {
struct dependency *link;
Operand *reg;
};
static void DeleteDependencyList(struct dependency **list) {
for (struct dependency *tmp=*list;tmp;) {
struct dependency *tmp2 = tmp->link;
free(tmp);
tmp=tmp2;
}
*list = NULL;
}
static void PrependDependency(struct dependency **list,Operand *reg) {
struct dependency *tmp = malloc(sizeof(struct dependency));
tmp->link = *list;
tmp->reg = reg;
*list = tmp;
}
static bool CheckDependency(struct dependency **list, Operand *reg) {
for (struct dependency *tmp=*list;tmp;tmp=tmp->link) {
if (tmp->reg == reg) return true;
}
return false;
}
static void DeleteDependencies(struct dependency **list,Operand *reg) {
struct dependency **prevlink = list;
for (struct dependency *tmp=*list;tmp;) {
struct dependency *next = tmp->link;
if (tmp->reg == reg) {
*prevlink = next;
free(tmp);
} else {
prevlink = &tmp->link;
}
tmp=next;
}
}
static struct reorder_block
FindBlockForReorderingDownward(IR *after) {
IR *bottom = after;
DEBUG(NULL,"Looking for a block to move down... (in %s)",curfunc->name);
// Are the flags used at after?
bool volatileC = FlagsUsedAt(after,FLAG_WC);
bool volatileZ = FlagsUsedAt(after,FLAG_WZ);
// Encountered a flag write on the way up?
// (if a block uses a flag, but we didn't find a flag write inbetween,
// that is the same flag state as after)
bool foundC = InstrSetsFlags(after,FLAG_WC), foundZ = InstrSetsFlags(after,FLAG_WZ);
// Encountered a flag read on the way up?
bool dependC = InstrUsesFlags(after,FLAG_WC),dependZ = InstrUsesFlags(after,FLAG_WZ);
struct dependency *depends = NULL;
// Hunt for the start of a potential reordering block
for (;;) {
bottom = bottom->prev;
if (!bottom || IsReorderBarrier(bottom)) return (struct reorder_block){0};
IR *top;
// Need closure on a flag? (In this case, a setter)
bool needC = false, needZ = false;
unsigned count = 0;
for (top=bottom;top;top=top->prev) {
count++;
if (IsReorderBarrier(top)) break;
if (InstrSetsFlags(top,FLAG_WC)) {
needC = false;
if (volatileC && foundC) break;
if (dependC) break;
}
if (InstrSetsFlags(top,FLAG_WZ)) {
needZ = false;
if (volatileZ && foundZ) break;
if (dependZ) break;
}
if (foundC && InstrUsesFlags(top,FLAG_WC)) needC = true;
if (foundZ && InstrUsesFlags(top,FLAG_WZ)) needZ = true;
// Can only reorder reads with reads
if (IsWrite(top) && ReadWriteInRange(bottom->next,after)) break;
if (IsRead(top) && WriteInRange(bottom->next,after)) break;
// Can't reorder over dependent code
if (InstrSetsDst(top) && UsedInRange(bottom->next,after,top->dst)) break;
// Check if this instruction meets some dependencies
if (InstrSetsDst(top)) {
DeleteDependencies(&depends,top->dst);
}
// Does _this_ depend on anything that we can't take through reorder?
if (ModifiedInRange(bottom->next,after,top->src)) {
PrependDependency(&depends,top->src);
}
if (InstrReadsDst(top) && ModifiedInRange(bottom->next,after,top->dst)) {
PrependDependency(&depends,top->dst);
}
// Ok, if there are no unmet dependencies, the block is good.
if (!needC && !needZ && !depends && (!top->prev || !IsPrefixOpcode(top->prev))) {
return (struct reorder_block){.count=count,.top=top,.bottom=bottom};
}
}
// broke out of loop, this block is invalid
if (InstrSetsFlags(bottom,FLAG_WC)) {
foundC = true;
dependC = false;
}
if (InstrSetsFlags(bottom,FLAG_WZ)) {
foundZ = true;
dependZ = false;
}
if (InstrUsesFlags(bottom,FLAG_WC)) dependC = true;
if (InstrUsesFlags(bottom,FLAG_WZ)) dependZ = true;
DeleteDependencyList(&depends);
}
}
static struct reorder_block
FindBlockForReorderingUpward(IR *before) {
IR *top = before;
DEBUG(NULL,"Looking for a block to move up... (in %s)",curfunc->name);
// Are the flags used at before?
bool volatileC = FlagsUsedAt(before,FLAG_WC);
bool volatileZ = FlagsUsedAt(before,FLAG_WZ);
//DEBUG(NULL,"Volatile C: %s , Volatile Z: %s",volatileC?"Y":"n",volatileZ?"Y":"n");
// Encountered a flag write on the way down?
bool foundC = InstrSetsFlags(before,FLAG_WC), foundZ = InstrSetsFlags(before,FLAG_WZ);
struct dependency *depends = NULL;
// Hunt for the start of a potential reordering block
for (;;) {
top = top->next;
if (!top || IsReorderBarrier(top)) return (struct reorder_block){0};
IR *bottom;
// Need closure on a flag? (In this case, the last user)
bool needC = false, needZ = false;
// Have a flag setter in the block?
bool foundClocal = false, foundZlocal = false;
unsigned count = 0;
for (bottom=top;bottom;bottom=bottom->next) {
count++;
if (IsReorderBarrier(bottom)) break;
// if we use a flag that isn't set inside the block but we want to reorder over another flag write, abort
if (foundC && !foundClocal && InstrUsesFlags(bottom,FLAG_WC)) break;
if (foundZ && !foundZlocal && InstrUsesFlags(bottom,FLAG_WZ)) break;
// If we write a flag, but there's another write we want to move over
// we need to pull instructions until the flag is dead
if (InstrSetsFlags(bottom,FLAG_WC)) {
if (volatileC) break;
if (foundC) needC = true;
foundClocal = true;
}
if (InstrSetsFlags(bottom,FLAG_WZ)) {
if (volatileZ) break;
if (foundZ) needZ = true;
foundZlocal = true;
}
// Flags dead?
if (needC && !FlagsUsedAt(bottom->next,FLAG_WC)) needC = false;
if (needZ && !FlagsUsedAt(bottom->next,FLAG_WZ)) needZ = false;
// Can only reorder reads with reads
if (IsWrite(bottom) && ReadWriteInRange(before,bottom->prev)) break;
if (IsRead(bottom) && WriteInRange(before,bottom->prev)) break;
// Can't reorder over code depending on another value for dst
if (InstrSetsDst(bottom) && UsedInRange(before,top->prev,bottom->dst)) break;
// Can't reorder over code this depends on
if (ModifiedInRange(before,top->prev,bottom->src) && UsedInRange(top,bottom,bottom->src)) break;
if (InstrReadsDst(bottom)&&ModifiedInRange(before,top->prev,bottom->dst) && UsedInRange(top,bottom,bottom->dst)) break;
// if this result is modified by code we reorder over, it must become dead at the end of the block
if (InstrSetsDst(bottom) && ModifiedInRange(before,top->prev,bottom->dst)) {
PrependDependency(&depends,bottom->dst);
}
// Delete dependencies that go dead
if (bottom->src && IsDeadAfter(bottom,bottom->src)) DeleteDependencies(&depends,bottom->src);
if (InstrReadsDst(bottom) && IsDeadAfter(bottom,bottom->dst)) DeleteDependencies(&depends,bottom->dst);
// Ok, if there are no unmet dependencies, the block is good.
if (!needC && !needZ && !depends && !IsPrefixOpcode(bottom)) {
return (struct reorder_block){.count=count,.top=top,.bottom=bottom};
}
}
// broke out of loop, this block is invalid
if (InstrSetsFlags(top,FLAG_WC)) foundC = true;
if (InstrSetsFlags(top,FLAG_WZ)) foundZ = true;
DeleteDependencyList(&depends);
}
}
#define CORDIC_PIPE_LENGTH 56
// Try to move code between QMUL/QDIV and GETQ* to amortize CORDIC latency
static bool
OptimizeCORDIC(IRList *irl) {
// Search for QMUL/QDIV
bool change = false;
for (IR *ir=irl->tail;ir;ir=ir->prev) {
if (!IsCordicCommand(ir)) continue;
if(IsHwReg(ir->dst)||IsHwReg(ir->src)) continue;
int cycles = 0;
// Count min-cycles already inbetween command and get
for (IR *ir2=ir->next;ir2;ir2=ir2->next) {
if (IsCordicGet(ir2)) break;
cycles += InstrMinCycles(ir2);
}
// Try pulling down blocks
// (The cycle limit only applies in pathological cases)
while (cycles<CORDIC_PIPE_LENGTH) {
struct reorder_block blk = FindBlockForReorderingDownward(ir);
if (blk.count == 0) break; // No block found
DEBUG(NULL,"Reordering block of %d instructions down",blk.count);
DoReorderBlock(irl,ir,blk.top,blk.bottom);
cycles += MinCyclesInRange(blk.top,blk.bottom);
change = true;
}
}
// Search for GETQ*
for (IR *ir=irl->head;ir;ir=ir->next) {
if(!IsCordicGet(ir)) continue;
if(IsHwReg(ir->dst)) continue;
int cycles = 0;
// Count min-cycles already inbetween command and get
for (IR *ir2=ir->prev;ir2;ir2=ir2->prev) {
if (IsCordicCommand(ir2)) break;
cycles += InstrMinCycles(ir2);
}
// Try pulling up blocks
// (The cycle limit only applies in pathological cases)
while (cycles<CORDIC_PIPE_LENGTH) {
struct reorder_block blk = FindBlockForReorderingUpward(ir);
if (blk.count == 0) break; // No block found
DEBUG(NULL,"Reordering block of %d instructions up",blk.count);
DoReorderBlock(irl,ir->prev,blk.top,blk.bottom);
cycles += MinCyclesInRange(blk.top,blk.bottom);
change = true;
}
}
return change;
}
//
static bool
CORDICconstPropagate(IRList *irl) {
bool constantCommand=false,change=false,foundX=false,foundY=false;
int32_t const_x=0,const_y=0;
for(IR *ir=irl->head;ir;ir=ir->next) {
if (IsCordicCommand(ir) && !IsPrefixOpcode(ir->prev)
&& ir->dst && ir->dst->kind == IMM_INT
&& ir->src && ir->src->kind == IMM_INT) {
constantCommand = true;
foundX = false;
foundY = false;
switch(ir->opc) {
case OPC_QMUL: {
DEBUG(NULL,"Got const QMUL %ld,%ld",(long)ir->dst->val,(long)ir->src->val);
uint64_t tmp = (uint64_t)((uint32_t)ir->dst->val) * (uint32_t)ir->src->val;
const_x = (int32_t)tmp;
const_y = (int32_t)(tmp>>32);
} break;
case OPC_QDIV: {
if (ir->src->val == 0) {
const_x = 0xFFFFFFFF;
const_y = ir->dst->val;
} else {
const_x = (uint32_t)ir->dst->val / (uint32_t)ir->src->val;
const_x = (uint32_t)ir->dst->val % (uint32_t)ir->src->val;
}
} break;
default: // other ops make brain hurt, owie
constantCommand = false;
break;
}
if (constantCommand) {
DeleteIR(irl,ir);
change = true;
}
} else if (constantCommand&&(ir->opc==OPC_GETQX || ir->opc==OPC_GETQY)) {
if (ir->opc==OPC_GETQX) {
if (foundX) WARNING(NULL,"Internal warning, found two GETQX during constant propagate??");
foundX = true;
ir->src = NewImmediate(const_x);
} else {
if (foundY) WARNING(NULL,"Internal warning, found two GETQY during constant propagate??");
foundY = true;
ir->src = NewImmediate(const_y);
}
ReplaceOpcode(ir,OPC_MOV);
} else if (constantCommand&&(IsBranch(ir)||IsLabel(ir))) {
if (!foundX && !foundY) WARNING(NULL,"Internal warning, unused CORDIC constant??");
constantCommand = false;
}
}
if (constantCommand && !foundX && !foundY) WARNING(NULL,"Internal warning, unused CORDIC constant at end of function??");
return change;
}
// Optimization may have created lone CORDIC commands
// which will lead to strange results.
// Thus, we shall remove these.
static bool
FixupLoneCORDIC(IRList *irl) {
bool seenCommand = true, change = false;
for(IR *ir=irl->tail;ir;ir=ir->prev) {
if (IsCordicCommand(ir)) {
if (seenCommand && !InstrIsVolatile(ir)) {
if (IsPrefixOpcode(ir->prev)) DeleteIR(irl,ir->prev);
DeleteIR(irl,ir);
change = true;
} else seenCommand = true;
} else if (IsCordicGet(ir)) {
seenCommand = false;
} else if (IsBranch(ir)||IsLabel(ir)) {
seenCommand = true;
}
}
return change;
}
static void addKnownReg(struct dependency **list, Operand *op, bool arg) {
if (op && op->kind != REG_SUBREG && (arg?IsArg(op)||isResult(op):IsLocal(op)) && !CheckDependency(list,op)) PrependDependency(list,op);
}
static bool
ReuseLocalRegisters(IRList *irl) {
struct dependency *known_regs = NULL;
bool change = false;
IR *stop_ir;
for(IR *ir=irl->head;ir;ir=ir->next) {
// Find all the arg/result regs first
addKnownReg(&known_regs,ir->src,true);
addKnownReg(&known_regs,ir->dst,true);
}
for (IR *ir=irl->head;ir;ir=ir->next) {
// Start of new dependency chain
if (ir->dst && ir->dst != ir->src && IsLocal(ir->dst) && ir->dst->kind != REG_SUBREG && InstrModifies(ir,ir->dst) && !InstrUses(ir,ir->dst) && !CheckDependency(&known_regs,ir->dst)) {
for (struct dependency *tmp=known_regs;tmp;tmp=tmp->link) {
if (tmp->reg!=ir->dst && IsDeadAfter(ir,tmp->reg) && (stop_ir = SafeToReplaceForward(ir->next,ir->dst,tmp->reg,ir->cond))) {
//DEBUG(NULL,"Using %s instead of %s",tmp->reg->name,ir->dst->name);
ReplaceForward(ir->next,ir->dst,tmp->reg,stop_ir);
ir->dst = tmp->reg;
change = true;
break;
}
}
}
// Collect known registers
addKnownReg(&known_regs,ir->src,false);
addKnownReg(&known_regs,ir->dst,false);
}
return change;
}
// optimize an isolated piece of IRList
// (typically a function)
void
OptimizeIRLocal(IRList *irl, Function *f)
{
int change;
int flags = f->optimize_flags;
if (gl_errors > 0) return;
if (!irl->head) return;
// multiply divide optimization need only be performed once,
// and should be done before other optimizations confuse things
OptimizeMulDiv(irl);
again:
do {
change = 0;
AssignTemporaryAddresses(irl);
if (flags & OPT_BASIC_REGS) {
change |= CheckLabelUsage(irl);
change |= OptimizeReadWrite(irl);
change |= EliminateDeadCode(irl);
change |= OptimizeCogWrites(irl);
change |= OptimizeSimpleAssignments(irl);
change |= OptimizeMoves(irl);
}
if (flags & OPT_CONST_PROPAGATE) {
change |= OptimizeImmediates(irl);
}
if (flags & OPT_BASIC_REGS) {
change |= OptimizeCompares(irl);
change |= OptimizeAddSub(irl);
change |= OptimizeLoopPtrOffset(irl);
}
if (flags & OPT_BRANCHES) {
change |= OptimizeShortBranches(irl);
}
if (flags & OPT_PEEPHOLE) {
change |= OptimizePeepholes(irl);
change |= OptimizePeephole2(irl);
}
if (flags & OPT_BASIC_REGS) {
change |= OptimizeIncDec(irl);
change |= OptimizeJumps(irl);
}
if (gl_p2 && (flags & OPT_BASIC_REGS)) {
change |= OptimizeP2(irl);
}
if (gl_p2) {
change |= FixupLoneCORDIC(irl);
if (flags & OPT_CONST_PROPAGATE) {
change |= CORDICconstPropagate(irl);
}
}
} while (change != 0);
if (flags & OPT_TAIL_CALLS) {
change = OptimizeTailCalls(irl, f);
}
if (change) goto again;
if (gl_p2 && (flags & OPT_CORDIC_REORDER)) {
change = OptimizeCORDIC(irl);
}
if (change) goto again;
if (flags & OPT_LOCAL_REUSE) {
change = ReuseLocalRegisters(irl);
}
if (change) goto again;
}
//
// optimize the whole program
//
void
OptimizeIRGlobal(IRList *irl)
{
IR *ir, *ir_next;
// remove dummy and dead notes
ir = irl->head;
while (ir) {
ir_next = ir->next;
if (ir->opc == OPC_DUMMY) {
DeleteIR(irl, ir);
}
ir = ir_next;
}
if (gl_lmm_kind == LMM_KIND_ORIG) {
// check for fcache
if (gl_optimize_flags & OPT_AUTO_FCACHE) {
OptimizeFcache(irl);
}
}
// check for usage
CheckUsage(irl);
}
static bool
NeverInline(Function *f)
{
if (f->no_inline) return true;
if (f->uses_alloca) return true;
if (f->stack_local) return true;
if (f->closure) return true;
if (gl_exit_status && !strcmp(f->name, "main")) return true;
return false;
}
//
// check a function to see if it should be inlined
//
#define INLINE_THRESHOLD_P1 2
#define INLINE_THRESHOLD_P2 4
bool
ShouldBeInlined(Function *f)
{
IR *ir;
int n = 0;
int paramfactor;
int threshold;
if (gl_p2) {
threshold = INLINE_THRESHOLD_P2;
} else {
threshold = INLINE_THRESHOLD_P1;
}
if (!(gl_optimize_flags & (OPT_INLINE_SMALLFUNCS|OPT_INLINE_SINGLEUSE))) {
return false;
}
if (NeverInline(f)) {
return false;
}
for (ir = FuncIRL(f)->head; ir; ir = ir->next) {
if (IsDummy(ir)) continue;
// we have to re-label any labels and branches
if (IsLabel(ir)) {
if (!ir->aux) {
// cannot find a unique jump going to this label
return false;
}
if (!IsTemporaryLabel(ir->dst)) {
return false;
}
continue; // do not count labels against the cost
} else if (IsJump(ir)) {
if (!ir->aux) {
// cannot find where this jump goes
return false;
}
if (!IsTemporaryLabel( ((IR *)ir->aux)->dst )) {
return false;
}
}
n++;
}
// a function called from only 1 place should be inlined
// if it means that the function definition can be eliminated
if (RemoveIfInlined(f) && (gl_optimize_flags & OPT_INLINE_SINGLEUSE)) {
if (f->callSites == 1) {
return true;
} else if (f->callSites == 2) {
return (n <= 2*threshold);
}
}
// otherwise only inline small functions
// also note that we should consider the cost of moving instructions
// into argument registers when considering this
paramfactor = f->numparams;
if (paramfactor < 2) {
paramfactor = 2;
} else if (paramfactor > 4) {
paramfactor = 4;
} else {
paramfactor = f->numparams;
}
return n <= (threshold + paramfactor);
}
//
// expand function calls inline if appropriate
// returns 1 if anything was expanded
int
ExpandInlines(IRList *irl)
{
Function *f;
IR *ir, *ir_next;
int change = 0;
ir = irl->head;
while (ir) {
ir_next = ir->next;
if (ir->opc == OPC_CALL) {
f = (Function *)ir->aux;
if (f && FuncData(f)->isInline) {
ReplaceIRWithInline(irl, ir, f);
FuncData(f)->actual_callsites--;
change = 1;
}
}
ir = ir_next;
}
return change;
}
//
// convert loops to FCACHE when we can
//
// see if a loop can be cached
// "root" is a label
// returns NULL if no fcache, otherwise
// a new label which can point to the end
// of the loop
static IR *
LoopCanBeFcached(IRList *irl, IR *root, int size_left)
{
IR *endjmp;
IR *endlabel;
IR *newlabel;
IR *ir = root;
if (!IsHubDest(ir->dst)) {
// this loop is not in HUB memory
return 0;
}
endjmp = (IR *)ir->aux;
if (!endjmp || !IsJump(endjmp)) {
// we don't know who jumps here
return 0;
}
endlabel = endjmp;
// addr != 0 check is to avoid picking up return labels
while (endlabel->next && endlabel->next->opc == OPC_LABEL && endlabel->next->addr != 0) {
endlabel = endlabel->next;
}
if (IsForwardJump(endjmp)) {
return 0;
}
ir = ir->next;
while (ir != endjmp) {
if (ir->fcache || InstrIsVolatile(ir)) {
return 0;
}
if (ir->opc == OPC_CALL) {
// no calls to hub memory
if (MaybeHubDest(ir->dst)) {
return 0;
}
// mul/div functions are definitely OK
if (ir->dst == mulfunc || ir->dst == unsmulfunc || ir->dst == divfunc || ir->dst == unsdivfunc) {
goto call_ok;
}
// otherwise we assume the function may call other
// things which will end up using FCACHE, so bad
// FIXME: if we did this at a higher level we might
// be able to detect leaf functions
return 0;
call_ok: ;
}
if (ir->opc == OPC_FCACHE) {
return 0;
}
if (IsJump(ir)) {
if (!JumpIsAfterOrEqual(root, ir))
return 0;
if (JumpDest(ir) != endlabel->dst && JumpIsAfterOrEqual(endlabel, ir))
return 0;
}
if (!IsDummy(ir) && ir->opc != OPC_LABEL) {
--size_left;
if (size_left <= 0) {
return 0;
}
}
ir = ir->next;
}
//
// OK, if we got here then the stuff from "root" to "endjmp"
// is eligible for fcache
// if there's another loop just after this one, it may be worth
// trying to fit it in as well
//
if (ir == endjmp && size_left > gl_fcache_size/2) {
// peek ahead a few instructions
// if there's a loop there we can stick into fcache as well,
// combine them both into one big block
int n = 4;
while (n > 0 && ir && size_left > 0) {
if (IsLabel(ir)) {
IR *newend = LoopCanBeFcached(irl, ir, size_left);
if (newend) {
return newend;
} else {
break;
}
} else if (ir->opc == OPC_CALL && MaybeHubDest(ir->dst) ) {
break;
} else if (ir->opc == OPC_FCACHE) {
break;
} else if (!IsDummy(ir)) {
--n;
--size_left;
}
ir = ir->next;
}
}
Operand *dst = NewHubLabel();
newlabel = NewIR(OPC_LABEL);
newlabel->dst = dst;
InsertAfterIR(irl, endjmp, newlabel);
return newlabel;
}
void
OptimizeFcache(IRList *irl)
{
IR *ir;
IR *endlabel;
ir = irl->head;
while (ir) {
if (IsLabel(ir)) {
endlabel = LoopCanBeFcached(irl, ir, gl_fcache_size);
if (endlabel) {
Operand *src = ir->dst;
Operand *dst = endlabel->dst;
IR *startlabel = ir;
IR *fcache = NewIR(OPC_FCACHE);
IR *loopstart = ir->prev;
fcache->src = src;
fcache->dst = dst;
while (loopstart && IsDummy(loopstart)) {
loopstart = loopstart->prev;
}
if (loopstart && loopstart->opc == OPC_REPEAT) {
loopstart = loopstart->prev;
startlabel = NewIR(OPC_LABEL);
fcache->src = startlabel->dst = NewHubLabel();
InsertAfterIR(irl, loopstart, startlabel);
ir = startlabel;
}
InsertAfterIR(irl, loopstart, fcache);
while (ir != endlabel) {
ir->fcache = src;
ir = ir->next;
}
}
}
ir = ir->next;
}
}
/////////////////////////////////////////////////////
// new peephole optimization scheme
/////////////////////////////////////////////////////
typedef struct PeepholePattern {
int cond;
int opc;
int dst;
int src1;
unsigned flags;
} PeepholePattern;
#define PEEP_FLAGS_NONE 0x0000
#define PEEP_FLAGS_P2 0x0001
#define PEEP_FLAGS_WCZ_OK 0x0002
#define PEEP_FLAGS_MUST_WZ 0x0004
#define PEEP_FLAGS_MUST_WC 0x0008
#define PEEP_FLAGS_DONE 0xffff
#define OPERAND_ANY -1
#define COND_ANY -1
#define OPC_ANY -1
#define MAX_OPERANDS_IN_PATTERN 16
#define PEEP_OPNUM_MASK 0x00ffffff
#define PEEP_OP_MASK 0xff000000
#define PEEP_OP_SET 0x01000000
#define PEEP_OP_MATCH 0x02000000
#define PEEP_OP_IMM 0x03000000
#define PEEP_OP_SET_IMM 0x04000000
#define PEEP_OP_MATCH_DEAD 0x05000000 /* like PEEP_OP_MATCH, but operand is dead after this instr */
#define PEEP_OP_CLRBITS 0x06000000
#define PEEP_OP_MATCH_M1S 0x07000000
#define PEEP_OP_MATCH_M1U 0x08000000
#define PEEP_OP_CLRMASK(bits, shift) (PEEP_OP_CLRBITS|(bits<<6)|(shift))
static Operand *peep_ops[MAX_OPERANDS_IN_PATTERN];
static int PeepOperandMatch(int patrn_dst, Operand *dst, IR *ir)
{
int opnum, opflag;
if (patrn_dst != OPERAND_ANY) {
opnum = patrn_dst & PEEP_OPNUM_MASK;
opflag = patrn_dst & PEEP_OP_MASK;
if (opflag == PEEP_OP_SET) {
peep_ops[opnum] = dst;
} else if (opflag == PEEP_OP_SET_IMM) {
if (dst->kind != IMM_INT) {
return 0;
}
peep_ops[opnum] = dst;
} else if (opflag == PEEP_OP_MATCH) {
if (!SameOperand(peep_ops[opnum], dst)) {
return 0;
}
} else if (opflag == PEEP_OP_MATCH_DEAD) {
if (!SameOperand(peep_ops[opnum], dst)) {
return 0;
}
if (!IsDeadAfter(ir, dst)) {
return 0;
}
} else if (opflag == PEEP_OP_MATCH_M1U) {
// the new operand must have the same value as the original, minus 1
// (used for compares)
if (dst->kind != IMM_INT) return 0;
if (peep_ops[opnum]->kind != IMM_INT) return 0;
if ( (uint32_t)(peep_ops[opnum]->val) != 1+((uint32_t)dst->val) ) {
return 0;
}
// disallow overflow case
if ((uint32_t)dst->val == 0xFFFFFFFFU) {
return 0;
}
} else if (opflag == PEEP_OP_MATCH_M1S) {
// the new operand must have the same value as the original, minus 1
// (signed version of above)
if (dst->kind != IMM_INT) return 0;
if (peep_ops[opnum]->kind != IMM_INT) return 0;
if ( (int32_t)(peep_ops[opnum]->val) != 1+((int32_t)dst->val) ) {
return 0;
}
// disallow overflow case
if ((uint32_t)dst->val == 0x7fffffffU) {
return 0;
}
} else if (opflag == PEEP_OP_IMM) {
if (dst->kind != IMM_INT) {
return 0;
}
if (dst->val != opnum) {
return 0;
}
} else if (opflag == PEEP_OP_CLRBITS) {
uint32_t mask, shift;
if (dst->kind != IMM_INT) {
return 0;
}
mask = (opnum>>6) & 0x3f;
shift = (opnum & 0x3f);
mask = ((1<<mask)-1)<<shift;
mask = ~mask;
if ( ((uint32_t)dst->val) != mask) {
return 0;
}
}
}
return 1;
}
static int MatchPattern(PeepholePattern *patrn, IR *ir)
{
int ircount = 0;
unsigned flags;
int cur_cond = COND_ANY;
for(;;) {
flags = patrn->flags;
if (flags == PEEP_FLAGS_DONE) {
break; // we've matched so far
}
if ( (flags & PEEP_FLAGS_P2) && !gl_p2 ) {
return 0;
}
if (!ir) {
return 0; // no match, ran out of instructions
}
if (patrn->cond == COND_ANY) {
if (cur_cond == COND_ANY) {
cur_cond = ir->cond;
}
if (cur_cond != ir->cond) {
return 0;
}
}
else if ((ir->cond != patrn->cond)) {
return 0;
}
if (patrn->opc != ir->opc && patrn->opc != OPC_ANY) {
return 0;
}
// not all patterns are compatible with wcz bits
if (ir->flags & 0xff) {
if (!(flags & PEEP_FLAGS_WCZ_OK)) {
return 0;
}
}
if ((flags & PEEP_FLAGS_MUST_WC) && !(ir->flags & FLAG_WC) && !(ir->flags & FLAG_WCZ)) return 0;
if ((flags & PEEP_FLAGS_MUST_WZ) && !(ir->flags & FLAG_WZ) && !(ir->flags & FLAG_WCZ)) return 0;
if (!PeepOperandMatch(patrn->dst, ir->dst, ir)) {
return 0;
}
if (!PeepOperandMatch(patrn->src1, ir->src, ir)) {
return 0;
}
patrn++;
ir = ir->next;
ircount++;
}
return ircount;
}
// cmp + mov -> max/min
static PeepholePattern pat_maxs[] = {
{ COND_TRUE, OPC_CMPS, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_WCZ_OK },
{ COND_GT, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_maxu[] = {
{ COND_TRUE, OPC_CMP, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_WCZ_OK },
{ COND_GT, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_mins[] = {
{ COND_TRUE, OPC_CMPS, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_WCZ_OK },
{ COND_LT, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_minu[] = {
{ COND_TRUE, OPC_CMP, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_WCZ_OK },
{ COND_LT, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_maxs_off[] = {
{ COND_TRUE, OPC_CMPS, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_WCZ_OK },
{ COND_GE, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_MATCH_M1S|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_maxu_off[] = {
{ COND_TRUE, OPC_CMP, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_WCZ_OK },
{ COND_GE, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_MATCH_M1U|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// zero/sign extend via x = (x<<N) >> N
static PeepholePattern pat_zeroex[] = {
{ COND_ANY, OPC_SHL, PEEP_OP_SET|0, PEEP_OP_SET_IMM|1, PEEP_FLAGS_P2 },
{ COND_ANY, OPC_SHR, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_signex[] = {
{ COND_ANY, OPC_SHL, PEEP_OP_SET|0, PEEP_OP_SET_IMM|1, PEEP_FLAGS_P2 },
{ COND_ANY, OPC_SAR, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// wrc x; cmp x, #0 wz
static PeepholePattern pat_wrc_cmp[] = {
{ COND_TRUE, OPC_WRC, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_CMP, PEEP_OP_MATCH|0, PEEP_OP_IMM|0, PEEP_FLAGS_P2|PEEP_FLAGS_WCZ_OK },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// muxc x,#-1; cmp x, #0 wz
static PeepholePattern pat_muxc_cmp[] = {
{ COND_TRUE, OPC_MUXC, PEEP_OP_SET|0, PEEP_OP_CLRMASK(0,0), PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_CMP, PEEP_OP_MATCH|0, PEEP_OP_IMM|0, PEEP_FLAGS_WCZ_OK },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// wrc x; and x, #1 -> the AND is redundant
static PeepholePattern pat_wrc_and[] = {
{ COND_TRUE, OPC_WRC, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_AND, PEEP_OP_MATCH|0, PEEP_OP_IMM|1, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// wrc x; test x, #1 wc -> the TEST is redundant
static PeepholePattern pat_wrc_test[] = {
{ COND_TRUE, OPC_WRC, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_TEST, PEEP_OP_MATCH|0, PEEP_OP_IMM|1, PEEP_FLAGS_P2 | PEEP_FLAGS_WCZ_OK },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_clrc[] = {
{ COND_ANY, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_IMM|0, PEEP_FLAGS_NONE },
{ COND_ANY, OPC_TEST, PEEP_OP_MATCH_DEAD|0, PEEP_OP_IMM|1, PEEP_FLAGS_WCZ_OK },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_setc1[] = {
{ COND_ANY, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_IMM|1, PEEP_FLAGS_NONE },
{ COND_ANY, OPC_TEST, PEEP_OP_MATCH_DEAD|0, PEEP_OP_IMM|1, PEEP_FLAGS_WCZ_OK },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_setc2[] = {
{ COND_ANY, OPC_NEG, PEEP_OP_SET|0, PEEP_OP_IMM|1, PEEP_FLAGS_NONE },
{ COND_ANY, OPC_TEST, PEEP_OP_MATCH_DEAD|0, PEEP_OP_IMM|1, PEEP_FLAGS_WCZ_OK },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// XOR x,##-1 to NOT x,x
static PeepholePattern pat_not[] = {
{ COND_ANY, OPC_XOR, PEEP_OP_SET|0, PEEP_OP_CLRMASK(0,0), PEEP_FLAGS_P2},
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// remove redundant zero extends after rdbyte/rdword
static PeepholePattern pat_rdbyte1[] = {
{ COND_TRUE, OPC_RDBYTE, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_SHL, PEEP_OP_MATCH|0, PEEP_OP_IMM|24, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_SHR, PEEP_OP_MATCH|0, PEEP_OP_IMM|24, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_rdword1[] = {
{ COND_TRUE, OPC_RDWORD, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_SHL, PEEP_OP_MATCH|0, PEEP_OP_IMM|16, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_SHR, PEEP_OP_MATCH|0, PEEP_OP_IMM|16, PEEP_FLAGS_WCZ_OK },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_rdbyte2[] = {
{ COND_TRUE, OPC_RDBYTE, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_ZEROX, PEEP_OP_MATCH|0, PEEP_OP_IMM|7, PEEP_FLAGS_P2 | PEEP_FLAGS_WCZ_OK },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_rdword2[] = {
{ COND_TRUE, OPC_RDWORD, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_ZEROX, PEEP_OP_MATCH|0, PEEP_OP_IMM|15, PEEP_FLAGS_P2 | PEEP_FLAGS_WCZ_OK},
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// potentially eliminate a redundant mov+add sequence
static PeepholePattern pat_movadd[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_ADD, PEEP_OP_SET|2, PEEP_OP_MATCH|0, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// replace mov x, #2; shl x, y; sub x, #1 with bmask x, y
static PeepholePattern pat_bmask1[] = {
{ COND_ANY, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_IMM|2, PEEP_FLAGS_P2 },
{ COND_ANY, OPC_SHL, PEEP_OP_MATCH|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_ANY, OPC_SUB, PEEP_OP_MATCH|0, PEEP_OP_IMM|1, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// replace add y, #1; decod x, y; sub x, #1 with bmask x, y
static PeepholePattern pat_bmask2[] = {
{ COND_ANY, OPC_ADD, PEEP_OP_SET|1, PEEP_OP_IMM|1, PEEP_FLAGS_P2 },
{ COND_ANY, OPC_DECOD, PEEP_OP_SET|0, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 },
{ COND_ANY, OPC_SUB, PEEP_OP_MATCH|0, PEEP_OP_IMM|1, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// replace mov a, x; waitx a with waitx x
static PeepholePattern pat_waitx[] = {
{ COND_ANY, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_ANY, OPC_WAITX, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// replace if_c drvh / if_nc drvl with drvc
static PeepholePattern pat_drvc1[] = {
{ COND_C, OPC_DRVH, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_NC, OPC_DRVL, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_drvc2[] = {
{ COND_NC, OPC_DRVL, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_C, OPC_DRVH, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// replace if_c drvl / if_nc drvh with drvnc
static PeepholePattern pat_drvnc1[] = {
{ COND_C, OPC_DRVL, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_NC, OPC_DRVH, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_drvnc2[] = {
{ COND_NC, OPC_DRVH, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_C, OPC_DRVL, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// replace if_c bith / if_nc bitl with bitc
static PeepholePattern pat_bitc1[] = {
{ COND_C, OPC_BITH, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_NC, OPC_BITL, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_bitc2[] = {
{ COND_NC, OPC_BITL, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_C, OPC_BITH, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// replace if_c bitl / if_nc bith with bitnc
static PeepholePattern pat_bitnc1[] = {
{ COND_C, OPC_BITL, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_NC, OPC_BITH, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_bitnc2[] = {
{ COND_NC, OPC_BITH, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_C, OPC_BITL, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// replace if_z drvh / if_nz drvl with drvz
static PeepholePattern pat_drvz[] = {
{ COND_EQ, OPC_DRVH, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_NE, OPC_DRVL, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_drvnz1[] = {
{ COND_NE, OPC_DRVH, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_EQ, OPC_DRVL, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_drvnz2[] = {
{ COND_EQ, OPC_DRVL, PEEP_OP_SET|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ COND_NE, OPC_DRVH, PEEP_OP_MATCH|0, OPERAND_ANY, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// replace if_c neg / if_nc mov and smiliar patterns with NEGcc
static PeepholePattern pat_negc1[] = {
{ COND_C, OPC_NEG, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_NONE },
{ COND_NC, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_negc2[] = {
{ COND_NC, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_NONE },
{ COND_C, OPC_NEG, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_negnc1[] = {
{ COND_NC, OPC_NEG, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_NONE },
{ COND_C, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_negnc2[] = {
{ COND_C, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_NONE },
{ COND_NC, OPC_NEG, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_negz1[] = {
{ COND_Z, OPC_NEG, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_NONE },
{ COND_NZ, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_negz2[] = {
{ COND_NZ, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_NONE },
{ COND_Z, OPC_NEG, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_negnz1[] = {
{ COND_NZ, OPC_NEG, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_NONE },
{ COND_Z, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_negnz2[] = {
{ COND_Z, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_NONE },
{ COND_NZ, OPC_NEG, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// replace mov x, #0 / cmp a, b wz / if_e mov x, #1
static PeepholePattern pat_seteq[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_IMM|0, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_CMP, OPERAND_ANY, OPERAND_ANY, PEEP_FLAGS_WCZ_OK },
{ COND_EQ, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_IMM|1, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_setne[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_IMM|0, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_CMP, OPERAND_ANY, OPERAND_ANY, PEEP_FLAGS_WCZ_OK },
{ COND_NE, OPC_MOV, PEEP_OP_MATCH|0, PEEP_OP_IMM|1, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
#if 0
static PeepholePattern pat_sar24getbyte[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_SAR, PEEP_OP_MATCH|0, PEEP_OP_IMM|24, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_AND, PEEP_OP_MATCH|0, PEEP_OP_IMM|255, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_shr24getbyte[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_SHR, PEEP_OP_MATCH|0, PEEP_OP_IMM|24, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_AND, PEEP_OP_MATCH|0, PEEP_OP_IMM|255, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_sar16getbyte[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_SAR, PEEP_OP_MATCH|0, PEEP_OP_IMM|16, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_AND, PEEP_OP_MATCH|0, PEEP_OP_IMM|255, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_shr16getbyte[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_SHR, PEEP_OP_MATCH|0, PEEP_OP_IMM|16, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_AND, PEEP_OP_MATCH|0, PEEP_OP_IMM|255, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_sar8getbyte[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_SAR, PEEP_OP_MATCH|0, PEEP_OP_IMM|8, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_AND, PEEP_OP_MATCH|0, PEEP_OP_IMM|255, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_shr8getbyte[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_SHR, PEEP_OP_MATCH|0, PEEP_OP_IMM|8, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_AND, PEEP_OP_MATCH|0, PEEP_OP_IMM|255, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_sar16getword[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_SAR, PEEP_OP_MATCH|0, PEEP_OP_IMM|16, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_BITL, PEEP_OP_MATCH|0, PEEP_OP_IMM|(16+(15<<5)), PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_shr16getword[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_SAR, PEEP_OP_MATCH|0, PEEP_OP_IMM|16, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_BITL, PEEP_OP_MATCH|0, PEEP_OP_IMM|0xffff, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
#endif
static PeepholePattern pat_shl8setbyte[] = {
{ COND_TRUE, OPC_SHL, PEEP_OP_SET|0, PEEP_OP_IMM|8, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_BITL, PEEP_OP_SET|1, PEEP_OP_IMM|(8+(7<<5)), PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_OR, PEEP_OP_MATCH|1, PEEP_OP_MATCH|0, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_shl16setbyte[] = {
{ COND_TRUE, OPC_SHL, PEEP_OP_SET|0, PEEP_OP_IMM|16, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_BITL, PEEP_OP_SET|1, PEEP_OP_IMM|(16+(7<<5)), PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_OR, PEEP_OP_MATCH|1, PEEP_OP_MATCH|0, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_shl24setbyte[] = {
{ COND_TRUE, OPC_SHL, PEEP_OP_SET|0, PEEP_OP_IMM|24, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_BITL, PEEP_OP_SET|1, PEEP_OP_IMM|(24+(7<<5)), PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_OR, PEEP_OP_MATCH|1, PEEP_OP_MATCH|0, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static PeepholePattern pat_shl16setword[] = {
{ COND_TRUE, OPC_SHL, PEEP_OP_SET|0, PEEP_OP_IMM|16, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_BITL, PEEP_OP_SET|1, PEEP_OP_IMM|(16+(15<<5)), PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_OR, PEEP_OP_MATCH|1, PEEP_OP_MATCH|0, PEEP_FLAGS_P2 },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// mov x, y; and x, #1; add z, x => test y, #1 wz; if_nz add z, #1
static PeepholePattern pat_mov_and_add[] = {
{ COND_TRUE, OPC_MOV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_AND, PEEP_OP_MATCH|0, PEEP_OP_IMM|1, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_ADD, PEEP_OP_SET|2, PEEP_OP_MATCH_DEAD|0, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// qmul x, y; getqx z; qmul x, y; getqy w -> qmul x, y; getqx z; getqy w
static PeepholePattern pat_qmul_qmul1[] = {
{ COND_TRUE, OPC_QMUL, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQX, PEEP_OP_SET|2, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_QMUL, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQY, PEEP_OP_SET|3, OPERAND_ANY, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// qmul x, y; getqx z; qmul x, y; getqy w -> qmul x, y; getqx z; getqy w
static PeepholePattern pat_qmul_qmul2[] = {
{ COND_TRUE, OPC_QMUL, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQY, PEEP_OP_SET|2, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_QMUL, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQX, PEEP_OP_SET|3, OPERAND_ANY, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// qdiv x, y; getqx z; qdiv x, y; getqy w -> qdiv x, y; getqx z; getqy w
static PeepholePattern pat_qdiv_qdiv1[] = {
{ COND_TRUE, OPC_QDIV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQX, PEEP_OP_SET|2, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_QDIV, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQY, PEEP_OP_SET|3, OPERAND_ANY, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// qdiv x, y; getqx z; qdiv x, y; getqy w -> qdiv x, y; getqx z; getqy w
static PeepholePattern pat_qdiv_qdiv2[] = {
{ COND_TRUE, OPC_QDIV, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQY, PEEP_OP_SET|2, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_QDIV, PEEP_OP_MATCH|0, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQX, PEEP_OP_SET|3, OPERAND_ANY, PEEP_FLAGS_NONE },
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// Fuse signed quotient+remainder (constant divider)
static PeepholePattern pat_qdiv_qdiv_signed1[] = {
{ COND_TRUE, OPC_ABS, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 | PEEP_FLAGS_MUST_WC | PEEP_FLAGS_WCZ_OK },
{ COND_TRUE, OPC_QDIV, PEEP_OP_MATCH|0, PEEP_OP_SET|2, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQX, PEEP_OP_SET|3, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_ANY, OPERAND_ANY, PEEP_OP_MATCH|3, PEEP_FLAGS_NONE }, // NEGC/NEGNC
{ COND_TRUE, OPC_ABS, PEEP_OP_SET|4, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 | PEEP_FLAGS_MUST_WC | PEEP_FLAGS_WCZ_OK },
{ COND_TRUE, OPC_QDIV, PEEP_OP_MATCH|4, PEEP_OP_MATCH|2, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQY, PEEP_OP_SET|5, OPERAND_ANY, PEEP_FLAGS_NONE },
// NEGC/NEGNC here, but we don't really care if it's actually there
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// Fuse signed remainder+quotient (constant divider)
static PeepholePattern pat_qdiv_qdiv_signed2[] = {
{ COND_TRUE, OPC_ABS, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 | PEEP_FLAGS_MUST_WC | PEEP_FLAGS_WCZ_OK },
{ COND_TRUE, OPC_QDIV, PEEP_OP_MATCH|0, PEEP_OP_SET|2, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQY, PEEP_OP_SET|3, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_ANY, OPERAND_ANY, PEEP_OP_MATCH|3, PEEP_FLAGS_NONE }, // NEGC/NEGNC
{ COND_TRUE, OPC_ABS, PEEP_OP_SET|4, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 | PEEP_FLAGS_MUST_WC | PEEP_FLAGS_WCZ_OK },
{ COND_TRUE, OPC_QDIV, PEEP_OP_MATCH|4, PEEP_OP_MATCH|2, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQX, PEEP_OP_SET|5, OPERAND_ANY, PEEP_FLAGS_NONE },
// NEGC/NEGNC here, but we don't really care if it's actually there
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// Fuse signed quotient+remainder (constant dividend)
static PeepholePattern pat_qdiv_qdiv_signed3[] = {
{ COND_TRUE, OPC_ABS, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2 | PEEP_FLAGS_MUST_WC | PEEP_FLAGS_WCZ_OK },
{ COND_TRUE, OPC_QDIV, PEEP_OP_SET|2, PEEP_OP_MATCH|0, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQX, PEEP_OP_SET|3, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_ANY, OPERAND_ANY, PEEP_OP_MATCH|3, PEEP_FLAGS_NONE }, // NEGC/NEGNC
{ COND_TRUE, OPC_ABS, PEEP_OP_SET|4, PEEP_OP_MATCH|1, PEEP_FLAGS_P2},
{ COND_TRUE, OPC_QDIV, PEEP_OP_MATCH|2, PEEP_OP_MATCH|4, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQY, PEEP_OP_SET|5, OPERAND_ANY, PEEP_FLAGS_NONE },
// There may be a NEG here
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// Fuse signed remainder+quotient (constant dividend, negative)
static PeepholePattern pat_qdiv_qdiv_signed4[] = {
{ COND_TRUE, OPC_ABS, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2},
{ COND_TRUE, OPC_QDIV, PEEP_OP_SET|2, PEEP_OP_MATCH|0, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQY, PEEP_OP_SET|3, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_NEG, OPERAND_ANY, PEEP_OP_MATCH|3, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_ABS, PEEP_OP_SET|4, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 | PEEP_FLAGS_MUST_WC | PEEP_FLAGS_WCZ_OK },
{ COND_TRUE, OPC_QDIV, PEEP_OP_MATCH|2, PEEP_OP_MATCH|4, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQX, PEEP_OP_SET|5, OPERAND_ANY, PEEP_FLAGS_NONE },
// NEGC/NEGNC here, but we don't really care if it's actually there
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
// Fuse signed remainder+quotient (constant dividend, positive)
static PeepholePattern pat_qdiv_qdiv_signed5[] = {
{ COND_TRUE, OPC_ABS, PEEP_OP_SET|0, PEEP_OP_SET|1, PEEP_FLAGS_P2},
{ COND_TRUE, OPC_QDIV, PEEP_OP_SET|2, PEEP_OP_MATCH|0, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQY, PEEP_OP_SET|3, OPERAND_ANY, PEEP_FLAGS_NONE },
{ COND_TRUE, OPC_ABS, PEEP_OP_SET|4, PEEP_OP_MATCH|1, PEEP_FLAGS_P2 | PEEP_FLAGS_MUST_WC | PEEP_FLAGS_WCZ_OK },
{ COND_TRUE, OPC_QDIV, PEEP_OP_MATCH|2, PEEP_OP_MATCH|4, PEEP_FLAGS_P2 },
{ COND_TRUE, OPC_GETQX, PEEP_OP_SET|5, OPERAND_ANY, PEEP_FLAGS_NONE },
// There may be a NEG here
{ 0, 0, 0, 0, PEEP_FLAGS_DONE }
};
static int ReplaceMaxMin(int arg, IRList *irl, IR *ir)
{
if (!InstrSetsFlags(ir, FLAG_WZ|FLAG_WC)) {
return 0;
}
if (!FlagsDeadAfter(irl, ir->next, FLAG_WZ|FLAG_WC)) {
return 0;
}
ReplaceOpcode(ir, (IROpcode)arg);
// note: one of the patterns checks for cmp with GT instead of GE, so
// we have to use the second instruction's operand
ir->src = ir->next->src;
DeleteIR(irl, ir->next);
return 1;
}
static int ReplaceExtend(int arg, IRList *irl, IR *ir)
{
Operand *src = ir->src;
int zbit;
if (src->kind != IMM_INT) {
return 0;
}
zbit = 31 - src->val;
ir->src = NewImmediate(zbit);
ReplaceOpcode(ir, (IROpcode)arg);
DeleteIR(irl, ir->next);
return 1;
}
//
// looks at the sequence
// wrc x (or muxc x,#-1)
// cmp x, #0 wz
// and if possible deletes it and replaces subsequent uses of C with NZ
//
static int ReplaceWrcCmp(int arg, IRList *irl, IR *ir)
{
IR *ir0 = ir;
IR *ir1 = ir->next;
IR *lastir = NULL;
if (InstrIsVolatile(ir0) || !ir1 || InstrIsVolatile(ir1)) {
return 0;
}
ir = ir1->next;
for(lastir = ir; lastir; lastir = lastir->next) {
if (!lastir || InstrIsVolatile(lastir)) {
return 0;
}
if (IsBranch(lastir)) {
// we assume flags do not have to be preserved across branches */
break;
}
if (InstrUsesFlags(lastir, FLAG_WC)) {
// C is explicitly used, so preserve it
return 0;
}
if (InstrSetsAnyFlags(lastir)) {
// flags are to be replaced
break;
}
}
if (!lastir) {
return 0;
}
// OK, let's go ahead and change Z to NC
while (ir != lastir) {
ReplaceZWithNC(ir);
ir = ir->next;
}
if (IsBranch(lastir)) {
ReplaceZWithNC(lastir);
}
if (IsDeadAfter(ir1,ir0->dst)) DeleteIR(irl, ir0);
DeleteIR(irl, ir1);
return 1;
}
static int ReplaceWrcTest(int arg, IRList *irl, IR *ir)
{
IR *ir1 = ir->next;
// make sure the TEST only sets WC
if (!ir1) return 0;
if (ir1->flags & FLAG_WZ) return 0;
if (!(ir1->flags & FLAG_WC)) return 0;
if (InstrIsVolatile(ir1)) return 0;
DeleteIR(irl, ir1);
return 1;
}
//
// remove "arg" instructions following the current one
// and transfer their flag bits to the current one
//
static int RemoveNFlagged(int arg, IRList *irl, IR *ir)
{
IR *irlast, *irnext;
unsigned wcz_flags = 0;
irnext = ir->next;
while (arg > 0 && irnext) {
irlast = irnext;
irnext = irlast->next;
--arg;
if (arg == 0) {
wcz_flags = irlast->flags & 0xff;
}
DeleteIR(irl, irlast);
}
ir->flags |= wcz_flags;
return 1;
}
static int FixupMovAdd(int arg, IRList *irl, IR *ir)
{
Operand *newsrc = ir->src;
ir = ir->next;
if (ir->src != newsrc) {
ir->src = newsrc;
return 1;
}
return 0;
}
/* mov x, #0 ; test x, #1 wc => mov x, #0 wc */
static int FixupClrC(int arg, IRList *irl, IR *ir)
{
IR *testir = ir->next;
int newflags;
newflags = (testir->flags & (FLAG_WC|FLAG_WZ));
ir->flags |= newflags;
DeleteIR(irl, testir);
/* an interesting other thing to check: if we have
* a "drvc x" instruction following, replace it with
* "drvl x"
*/
if (ir->next && ir->next->opc == OPC_DRVC) {
ReplaceOpcode(ir->next, OPC_DRVL);
}
return 1;
}
/* mov x, #1 ; test x, #1 wc => neg x, #1 wc */
static int FixupSetC(int arg, IRList *irl, IR *ir)
{
IR *testir = ir->next;
int newflags;
ReplaceOpcode(ir, OPC_NEG);
newflags = (testir->flags & (FLAG_WC|FLAG_WZ));
ir->flags |= newflags;
DeleteIR(irl, testir);
/* an interesting other thing to check: if we have
* a "drvc x" instruction following, replace it with
* "drvh x"
*/
if (ir->next && ir->next->opc == OPC_DRVC) {
ReplaceOpcode(ir->next, OPC_DRVH);
}
return 1;
}
// mov x, y; shr x, #N; and x, #255 => getbyte x, y, #N/8
// mov x, y; shr x, #N; and x, #65535 => getword x, y, #N/16
#if 0
static int FixupGetByteWord(int arg, IRList *irl, IR *ir0)
{
IR *ir1 = ir0->next;
IR *ir2;
int shift = 0;
if (ir1->opc == OPC_SHR || ir1->opc == OPC_SAR) {
ir2 = ir1->next;
shift = ir1->src->val;
} else if (ir1->opc == OPC_AND) {
ir2 = ir1;
ir1 = NULL;
shift = 0;
} else {
return 0;
}
ReplaceOpcode(ir0, (IROpcode)arg);
if (arg == OPC_GETBYTE) {
shift = shift/8;
} else {
shift = shift/16;
}
ir0->src2 = NewImmediate(shift);
if (ir1) {
DeleteIR(irl, ir1);
}
DeleteIR(irl, ir2);
return 1;
}
#endif
// shl x, #N; and y, #MASK; or y, x => setbyte y, x, #N/8
static int FixupSetByteWord(int arg, IRList *irl, IR *ir0)
{
IR *ir1 = ir0->next;
IR *ir2 = ir1->next;
int shift = 0;
if (ir0->opc == OPC_SHL || ir0->opc == OPC_ROL) {
shift = ir0->src->val;
} else {
return 0;
}
ReplaceOpcode(ir2, (IROpcode)arg);
if (arg == OPC_SETBYTE) {
shift = shift/8;
} else {
shift = shift/16;
}
ir2->src2 = NewImmediate(shift);
if (IsDeadAfter(ir2, ir0->dst)) {
DeleteIR(irl, ir0);
}
DeleteIR(irl, ir1);
return 1;
}
static int FixupBmask(int arg, IRList *irl, IR *ir)
{
IR *irnext, *irnext2;
irnext = ir->next;
irnext2 = irnext->next;
ReplaceOpcode(irnext2, OPC_BMASK);
irnext2->src = peep_ops[1];
DeleteIR(irl, ir);
DeleteIR(irl, irnext);
return 1;
}
static int FixupWaitx(int arg, IRList *irl, IR *ir)
{
IR *irnext;
irnext = ir->next;
irnext->dst = peep_ops[1];
DeleteIR(irl, ir);
return 1;
}
// pattern is
// mov x, #0
// cmp arg01, arg02 wz
// if_e mov x, #1
//
// delete first move, and replace second with wrz x
static int FixupEq(int arg, IRList *irl, IR *ir)
{
IR *irnext, *irnext2;
irnext = ir->next;
irnext2 = irnext->next;
ReplaceOpcode(irnext2, (IROpcode)arg);
irnext2->src = NULL;
irnext2->cond = COND_TRUE;
DeleteIR(irl, ir);
return 1;
}
static int ReplaceDrvc(int arg, IRList *irl, IR *ir)
{
ReplaceOpcode(ir, (IROpcode)arg);
ir->cond = COND_TRUE;
DeleteIR(irl, ir->next);
return 1;
}
static int ReplaceNot(int arg, IRList *irl, IR *ir) {
ReplaceOpcode(ir,OPC_NOT);
ir->src = ir->dst;
return 1;
}
// pattern is
// mov x, y
// and x, #1
// add z, x '' x is dead
//
// change to
// test y, #1 wz
// if_nz add z, #1
//
static int FixupAndAdd(int arg, IRList *irl, IR *ir0)
{
IR *ir1, *ir2;
ir1 = ir0->next;
ir2 = ir1->next;
ir1->dst = ir0->src;
ReplaceOpcode(ir1, OPC_TEST);
ir1->flags |= FLAG_WZ;
ir2->src = NewImmediate(1);
ir2->cond = COND_NE;
DeleteIR(irl, ir0);
return 1;
}
// pattern is
// qmul x, y
// getqx z
// qmul x, y
// getqx w
//
// check that z != x and z != y
// if so, delete second qmul
//
static int FixupQmuls(int arg, IRList *irl, IR *ir0)
{
IR *ir1, *ir2;
ir1 = ir0->next;
ir2 = ir1->next;
if (InstrModifies(ir1, ir0->src) || InstrModifies(ir2, ir0->dst)) {
return 0;
}
DeleteIR(irl, ir2);
return 1;
}
// pattern:
// abs a, x wc
// qdiv a,y
// getq* b
// neg* z,b
// abs c, x wc
// qdiv c,y
// getq* d
// neg* w,d
static int FixupQdivSigned(int arg, IRList *irl, IR *ir0)
{
IR* ir1 = ir0->next; // qdiv 1
IR* ir2 = ir1->next; // getq* 1
IR* ir3 = ir2->next; // neg* 1
IR* ir4 = ir3->next; // abs 2
IR* ir5 = ir4->next; // qdiv 2
if (ir3->opc != OPC_NEGC && ir3->opc != OPC_NEGNC) return 0;
if (InstrModifies(ir2,ir4->src)||InstrModifies(ir3,ir4->src)||
InstrModifies(ir2,ir5->src)||InstrModifies(ir3,ir5->src) ) {
return 0;
}
if (IsDeadAfter(ir5,ir5->dst)) DeleteIR(irl,ir4); // Delete second ABS unless register is somehow reused
DeleteIR(irl,ir5); // Delete second QDIV
return 1;
}
// pattern:
// abs a, x
// qdiv y,a
// getq* b
// neg* z,b
// abs c, x wc
// qdiv y,c
// getq* d
// neg w,d (maybe)
static int FixupQdivSigned2(int arg, IRList *irl, IR *ir0)
{
IR* ir1 = ir0->next; // qdiv 1
IR* ir2 = ir1->next; // getq* 1
IR* ir3 = ir2->next; // neg* 1
IR* ir4 = ir3->next; // abs 2
IR* ir5 = ir4->next; // qdiv 2
if (ir3->opc != OPC_NEGC && ir3->opc != OPC_NEGNC && ir3->opc != OPC_NEG) return 0;
if (InstrModifies(ir2,ir4->src)||InstrModifies(ir3,ir4->src)||
InstrModifies(ir2,ir5->dst)||InstrModifies(ir3,ir5->dst) ) {
return 0;
}
if (IsDeadAfter(ir5,ir5->src)) DeleteIR(irl,ir4); // Delete second ABS unless register is somehow reused
DeleteIR(irl,ir5); // Delete second QDIV
ir0->flags |= FLAG_WC;
return 1;
}
// pattern:
// abs a, x
// qdiv y,a
// getq* z
// abs c, x wc
// qdiv y,c
// getq* d
// neg* w,d
static int FixupQdivSigned3(int arg, IRList *irl, IR *ir0)
{
IR* ir1 = ir0->next; // qdiv 1
IR* ir2 = ir1->next; // getq* 1
//IR* ir3 = ir2->next; // neg* 1
IR* ir4 = ir2->next; // abs 2
IR* ir5 = ir4->next; // qdiv 2
if (InstrModifies(ir2,ir4->src)||
InstrModifies(ir2,ir5->dst) ) {
return 0;
}
if (IsDeadAfter(ir5,ir5->src)) DeleteIR(irl,ir4); // Delete second ABS unless register is somehow reused
DeleteIR(irl,ir5); // Delete second QDIV
ir0->flags |= FLAG_WC;
return 1;
}
struct Peepholes {
PeepholePattern *check;
int arg;
int (*replace)(int arg, IRList *irl, IR *ir);
} peep2[] = {
{ pat_maxs, OPC_MAXS, ReplaceMaxMin },
{ pat_maxu, OPC_MAXU, ReplaceMaxMin },
{ pat_mins, OPC_MINS, ReplaceMaxMin },
{ pat_minu, OPC_MINU, ReplaceMaxMin },
{ pat_maxs_off, OPC_MAXS, ReplaceMaxMin },
{ pat_maxu_off, OPC_MAXU, ReplaceMaxMin },
{ pat_zeroex, OPC_ZEROX, ReplaceExtend },
{ pat_signex, OPC_SIGNX, ReplaceExtend },
{ pat_drvc1, OPC_DRVC, ReplaceDrvc },
{ pat_drvc2, OPC_DRVC, ReplaceDrvc },
{ pat_drvnc1, OPC_DRVNC, ReplaceDrvc },
{ pat_drvnc2, OPC_DRVNC, ReplaceDrvc },
{ pat_bitc1, OPC_BITC, ReplaceDrvc },
{ pat_bitc2, OPC_BITC, ReplaceDrvc },
{ pat_bitnc1, OPC_BITNC, ReplaceDrvc },
{ pat_bitnc2, OPC_BITNC, ReplaceDrvc },
{ pat_drvz, OPC_DRVZ, ReplaceDrvc },
{ pat_drvnz1, OPC_DRVNZ, ReplaceDrvc },
{ pat_drvnz2, OPC_DRVNZ, ReplaceDrvc },
{ pat_negc1, OPC_NEGC, ReplaceDrvc },
{ pat_negc2, OPC_NEGC, ReplaceDrvc },
{ pat_negnc1, OPC_NEGNC, ReplaceDrvc },
{ pat_negnc2, OPC_NEGNC, ReplaceDrvc },
{ pat_negz1, OPC_NEGZ, ReplaceDrvc },
{ pat_negz2, OPC_NEGZ, ReplaceDrvc },
{ pat_negnz1, OPC_NEGNZ, ReplaceDrvc },
{ pat_negnz2, OPC_NEGNZ, ReplaceDrvc },
{ pat_not, 0, ReplaceNot},
{ pat_wrc_cmp, 0, ReplaceWrcCmp },
{ pat_wrc_and, 1, RemoveNFlagged },
{ pat_wrc_test, 0, ReplaceWrcTest },
{ pat_muxc_cmp, 0, ReplaceWrcCmp },
{ pat_rdbyte1, 2, RemoveNFlagged },
{ pat_rdword1, 2, RemoveNFlagged },
{ pat_rdbyte2, 1, RemoveNFlagged },
{ pat_rdword2, 1, RemoveNFlagged },
{ pat_movadd, 0, FixupMovAdd },
{ pat_bmask1, 0, FixupBmask },
{ pat_bmask2, 0, FixupBmask },
{ pat_waitx, 0, FixupWaitx },
{ pat_seteq, OPC_WRZ, FixupEq },
{ pat_setne, OPC_WRNZ, FixupEq },
#if 0
{ pat_sar24getbyte, OPC_GETBYTE, FixupGetByteWord },
{ pat_shr24getbyte, OPC_GETBYTE, FixupGetByteWord },
{ pat_sar16getbyte, OPC_GETBYTE, FixupGetByteWord },
{ pat_shr16getbyte, OPC_GETBYTE, FixupGetByteWord },
{ pat_sar8getbyte, OPC_GETBYTE, FixupGetByteWord },
{ pat_shr8getbyte, OPC_GETBYTE, FixupGetByteWord },
{ pat_sar16getword, OPC_GETWORD, FixupGetByteWord },
{ pat_shr16getword, OPC_GETWORD, FixupGetByteWord },
#endif
{ pat_shl8setbyte, OPC_SETBYTE, FixupSetByteWord },
{ pat_shl16setbyte, OPC_SETBYTE, FixupSetByteWord },
{ pat_shl24setbyte, OPC_SETBYTE, FixupSetByteWord },
{ pat_shl16setword, OPC_SETWORD, FixupSetByteWord },
{ pat_clrc, 0, FixupClrC },
{ pat_setc1, 0, FixupSetC },
{ pat_setc2, 0, FixupSetC },
{ pat_mov_and_add, 0, FixupAndAdd },
{ pat_qmul_qmul1, 0, FixupQmuls },
{ pat_qmul_qmul2, 0, FixupQmuls },
{ pat_qdiv_qdiv1, 0, FixupQmuls },
{ pat_qdiv_qdiv2, 0, FixupQmuls },
{ pat_qdiv_qdiv_signed1, 0, FixupQdivSigned},
{ pat_qdiv_qdiv_signed2, 0, FixupQdivSigned},
{ pat_qdiv_qdiv_signed3, 0, FixupQdivSigned2},
{ pat_qdiv_qdiv_signed4, 0, FixupQdivSigned2},
{ pat_qdiv_qdiv_signed5, 0, FixupQdivSigned3},
};
static int OptimizePeephole2(IRList *irl)
{
IR *ir;
int change = 0;
int i, r;
ir = irl->head;
for(;;) {
while (ir && IsDummy(ir)) {
ir = ir->next;
}
if (!ir) break;
if (!InstrIsVolatile(ir)) {
for (i = 0; i < sizeof(peep2) / sizeof(peep2[0]); i++) {
r = MatchPattern(peep2[i].check, ir);
if (r) {
r = (*peep2[i].replace)(peep2[i].arg, irl, ir);
if (r) {
change++;
}
break;
}
}
}
ir = ir->next;
}
return change;
}
| 30.548398 | 191 | 0.539448 | [
"vector",
"transform"
] |
639fe37836668f36de8c392913d799c58e67fe84 | 4,623 | h | C | arangod/MMFiles/MMFilesCollectorCache.h | pavelsevcik/arangodb | 647a29d1aeab0909147961f5868dfd0618717e96 | [
"Apache-2.0"
] | 1 | 2018-12-08T01:58:16.000Z | 2018-12-08T01:58:16.000Z | arangod/MMFiles/MMFilesCollectorCache.h | lipper/arangodb | 66ea1fd4946668192e3f0d1060f0844f324ad7b8 | [
"Apache-2.0"
] | null | null | null | arangod/MMFiles/MMFilesCollectorCache.h | lipper/arangodb | 66ea1fd4946668192e3f0d1060f0844f324ad7b8 | [
"Apache-2.0"
] | 1 | 2018-12-05T04:56:16.000Z | 2018-12-05T04:56:16.000Z | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Jan Steemann
////////////////////////////////////////////////////////////////////////////////
#ifndef ARANGOD_MMFILES_MMFILES_COLLECTOR_CACHE_H
#define ARANGOD_MMFILES_MMFILES_COLLECTOR_CACHE_H 1
#include "Basics/Common.h"
#include "MMFiles/MMFilesDitch.h"
#include "MMFiles/MMFilesDatafileStatisticsContainer.h"
#include "VocBase/voc-types.h"
struct MMFilesDatafile;
struct MMFilesMarker;
namespace arangodb {
class MMFilesWalLogfile;
struct MMFilesCollectorOperation {
MMFilesCollectorOperation(char const* datafilePosition,
uint32_t datafileMarkerSize, char const* walPosition,
TRI_voc_fid_t datafileId)
: datafilePosition(datafilePosition),
datafileMarkerSize(datafileMarkerSize),
walPosition(walPosition),
datafileId(datafileId) {
TRI_ASSERT(datafilePosition != nullptr);
TRI_ASSERT(datafileMarkerSize > 0);
TRI_ASSERT(walPosition != nullptr);
TRI_ASSERT(datafileId > 0);
}
char const* datafilePosition;
uint32_t datafileMarkerSize;
char const* walPosition;
TRI_voc_fid_t datafileId;
};
struct MMFilesCollectorCache {
MMFilesCollectorCache(MMFilesCollectorCache const&) = delete;
MMFilesCollectorCache& operator=(MMFilesCollectorCache const&) = delete;
MMFilesCollectorCache(TRI_voc_cid_t collectionId, TRI_voc_tick_t databaseId,
MMFilesWalLogfile* logfile, int64_t totalOperationsCount,
size_t operationsSize)
: collectionId(collectionId),
databaseId(databaseId),
logfile(logfile),
totalOperationsCount(totalOperationsCount),
operations(new std::vector<MMFilesCollectorOperation>()),
ditches(),
dfi(),
lastFid(0),
lastDatafile(nullptr) {
operations->reserve(operationsSize);
}
~MMFilesCollectorCache() {
delete operations;
freeMMFilesDitches();
}
/// @brief return a reference to an existing datafile statistics struct
MMFilesDatafileStatisticsContainer& getDfi(TRI_voc_fid_t fid) {
return dfi[fid];
}
/// @brief return a reference to an existing datafile statistics struct,
/// create it if it does not exist
MMFilesDatafileStatisticsContainer& createDfi(TRI_voc_fid_t fid) {
// implicitly creates the entry if it does not exist yet
return dfi[fid];
}
/// @brief add a ditch
void addDitch(arangodb::MMFilesDocumentDitch* ditch) {
TRI_ASSERT(ditch != nullptr);
ditches.emplace_back(ditch);
}
/// @brief free all ditches
void freeMMFilesDitches() {
for (auto& it : ditches) {
it->ditches()->freeMMFilesDocumentDitch(it, false);
}
ditches.clear();
}
/// @brief id of collection
TRI_voc_cid_t const collectionId;
/// @brief id of database
TRI_voc_tick_t const databaseId;
/// @brief id of the WAL logfile
MMFilesWalLogfile* logfile;
/// @brief total number of operations in this block
int64_t const totalOperationsCount;
/// @brief all collector operations of a collection
std::vector<MMFilesCollectorOperation>* operations;
/// @brief ditches held by the operations
std::vector<arangodb::MMFilesDocumentDitch*> ditches;
/// @brief datafile info cache, updated when the collector transfers markers
std::unordered_map<TRI_voc_fid_t, MMFilesDatafileStatisticsContainer> dfi;
/// @brief id of last datafile handled
TRI_voc_fid_t lastFid;
/// @brief last datafile written to
MMFilesDatafile* lastDatafile;
};
/// @brief typedef key => document marker
typedef std::unordered_map<std::string, struct MMFilesMarker const*>
MMFilesDocumentOperationsType;
/// @brief typedef for structural operation (attributes, shapes) markers
typedef std::vector<struct MMFilesMarker const*> MMFilesOperationsType;
}
#endif
| 31.44898 | 80 | 0.703223 | [
"vector"
] |
63a0c12bc6063e7ed01454c4fa25a982e8e73d59 | 3,415 | c | C | libs/zexy/blockmirror~.c | d3cod3/ofxPdExternals | 57a4a36b0bf361d943ce5ef4621b26816ab2e08f | [
"MIT"
] | 4 | 2019-04-07T14:08:13.000Z | 2022-02-09T08:05:51.000Z | libs/zexy/blockmirror~.c | d3cod3/ofxPdExternals | 57a4a36b0bf361d943ce5ef4621b26816ab2e08f | [
"MIT"
] | 2 | 2020-11-08T22:13:07.000Z | 2022-02-10T15:38:55.000Z | libs/zexy/blockmirror~.c | d3cod3/ofxPdExternals | 57a4a36b0bf361d943ce5ef4621b26816ab2e08f | [
"MIT"
] | null | null | null | /*
* blockmirror~: mirrors a signalblock around it's center
*
* (c) 1999-2011 IOhannes m zmölnig, forum::für::umläute, institute of electronic music and acoustics (iem)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "zexy.h"
/* ------------------------ blockmirror~ ----------------------------- */
/* mirrors a signalblock around it's center:
{x[0], x[1], ... x[n-1]} --> {x[n-1], x[n-2], ... x[0]}
*/
static t_class *blockmirror_class;
typedef struct _blockmirror {
t_object x_obj;
int doit;
int blocksize;
t_sample *blockbuffer;
} t_blockmirror;
static void blockmirror_float(t_blockmirror *x, t_floatarg f)
{
x->doit = (f != 0);
}
static t_int *blockmirror_perform(t_int *w)
{
t_blockmirror *x = (t_blockmirror *)(w[1]);
t_sample *in = (t_sample *)(w[2]);
t_sample *out = (t_sample *)(w[3]);
int n = (int)(w[4]);
if (x->doit) {
if (in==out) {
int N=n;
t_sample *dummy=x->blockbuffer;
while(n--) {
*dummy++=*in++;
}
dummy--;
while(N--) {
*out++=*dummy--;
}
} else {
in+=n-1;
while(n--) {
*out++=*in--;
}
}
} else while (n--) {
*out++ = *in++;
}
return (w+5);
}
static void blockmirror_dsp(t_blockmirror *x, t_signal **sp)
{
if (x->blocksize<sp[0]->s_n) {
if(x->blockbuffer) {
freebytes(x->blockbuffer, sizeof(*x->blockbuffer)*x->blocksize);
}
x->blocksize = sp[0]->s_n;
x->blockbuffer = getbytes(sizeof(*x->blockbuffer)*x->blocksize);
}
dsp_add(blockmirror_perform, 4, x, sp[0]->s_vec, sp[1]->s_vec, sp[0]->s_n);
}
static void blockmirror_helper(t_blockmirror*x)
{
post("\n"HEARTSYMBOL" blockmirror~-object for reverting a signal");
post("'help' : view this\n"
"signal~");
post("outlet : signal~");
}
static void blockmirror_free(t_blockmirror*x)
{
if(x->blockbuffer) {
freebytes(x->blockbuffer, sizeof(*x->blockbuffer)*x->blocksize);
}
x->blockbuffer=0;
}
static void *blockmirror_new(void)
{
t_blockmirror *x = (t_blockmirror *)pd_new(blockmirror_class);
outlet_new(&x->x_obj, gensym("signal"));
x->doit = 1;
x->blocksize=0;
return (x);
}
void blockmirror_tilde_setup(void)
{
blockmirror_class = class_new(gensym("blockmirror~"),
(t_newmethod)blockmirror_new,
(t_method)blockmirror_free,
sizeof(t_blockmirror), 0, A_NULL);
class_addmethod(blockmirror_class, nullfn, gensym("signal"), 0);
class_addmethod(blockmirror_class, (t_method)blockmirror_dsp,
gensym("dsp"), 0);
class_addfloat(blockmirror_class, blockmirror_float);
class_addmethod(blockmirror_class, (t_method)blockmirror_helper,
gensym("help"), 0);
zexy_register("blockmirror~");
}
| 27.764228 | 107 | 0.622548 | [
"object"
] |
63a6f8b006572dad9124f121d0da2ad5041a6641 | 5,096 | h | C | PROX/FOUNDATION/TINY/TINY/include/tiny_coordsys_functions.h | diku-dk/PROX | c6be72cc253ff75589a1cac28e4e91e788376900 | [
"MIT"
] | 2 | 2019-11-27T09:44:45.000Z | 2020-01-13T00:24:21.000Z | PROX/FOUNDATION/TINY/TINY/include/tiny_coordsys_functions.h | erleben/matchstick | 1cfdc32b95437bbb0063ded391c34c9ee9b9583b | [
"MIT"
] | null | null | null | PROX/FOUNDATION/TINY/TINY/include/tiny_coordsys_functions.h | erleben/matchstick | 1cfdc32b95437bbb0063ded391c34c9ee9b9583b | [
"MIT"
] | null | null | null | #ifndef TINY_COORDSYS_FUNCTIONS_H
#define TINY_COORDSYS_FUNCTIONS_H
#include <tiny_coordsys.h>
#include <tiny_precision.h>
#include <tiny_quaternion.h>
#include <tiny_quaternion_functions.h>
#include <iosfwd> // for std::istream and std::ostream
namespace tiny
{
/**
* This method assumes that the point is in this coordinate system.
* In other words this method maps local points into non local
* points:
*
* BF -> WCS
*
* Let p be the point and let f designate the function of this
* method then we have
*
* [p]_WCS = f(p)
*
*/
template<typename T>
inline Vector<3,T> xform_point(CoordSys<T> const & X, Vector<3,T> const & p) { return rotate(X.Q(), p) + X.T(); }
/**
* This method assumes that the vector is in this
* coordinate system. That is it maps the vector
* from BF into WCS.
*/
template<typename T>
inline Vector<3,T> xform_vector(CoordSys<T> const & X, Vector<3,T> const & v) { return rotate(X.Q(), v); }
/**
* Transform Matrix.
*
* @param O A reference to a rotation matrix, which should be transformed by X.
*/
template<typename T>
inline Matrix<3,3,T> xform_matrix(CoordSys<T> const & X, Matrix<3,3,T> const & O) { return make(X.Q()) * O; }
/**
* Coordinate Transformation Product.
* This function should be used to concatenate coordinate transformations.
* In terms of homogeneous coordinates L and R corresponds to the matrices.
*
* L = | R_l T_l |
* | 0 1 |
*
* R = | R_r T_r |
* | 0 1 |
*
* This function computes the equivalent of the product
*
* X = L R
*
* = | R_l T_l | | R_r T_r |
* | 0 1 | | 0 1 |
*
* = | R_l R_r R_l T_r + T_l |
* | 0 1 |
*
* @param L The left coordinate transformation
* @param R The right coordinate transformation
*
* @return The coordinate transformation corresponding to the product L*R.
*/
template<typename T>
inline CoordSys<T> prod(CoordSys<T> const & L, CoordSys<T> const & R)
{
return CoordSys<T>( rotate(L.Q(), R.T() ) + L.T() , unit( prod( L.Q() , R.Q()) ) );
}
/**
* Inverse Transform.
*
* If we have
*
* BF -> WCS
*
* Then we want to find
*
* WCS -> BF
*
*/
template<typename T>
inline CoordSys<T> inverse(CoordSys<T> const & X)
{
//---
//--- p' = R p + T
//---
//--- =>
//---
//--- p = R^{-1} p' + R^{-1}(-T)
//---
return CoordSys<T>( rotate(conj(X.Q()), -X.T()) , conj(X.Q()) );
}
/**
* Model Update Transform.
* This function computes the necessary transform needed in
* order to transform coordinates from one local frame
* into another local frame. This utility is useful when
* one wants to do model updates instead of world updates.
*
* In mathematical terms we have two transforms:
*
* C1 : H -> G
* C2 : F -> G
*
* And we want to find
*
* C3 : H -> F
*
* This transform is computed and assigned to this coordinate
* system.
*
* Very important: Note that this method finds the transform A -> B.
*/
template<typename T>
inline CoordSys<T> model_update(Vector<3,T> const & TA, Quaternion<T> const & QA, Vector<3,T> const & TB, Quaternion<T> const & QB)
{
typedef typename T::real_type R;
typedef ValueTraits<R> VT;
//---
//--- p' = RA p + TA (*1) from A->WCS
//---
//--- p = RB^T (p' - TB) (*2) from WCS-B
//---
//--- Insert (*1) into (*2) A -> B
//---
//--- p = RB^T ( RA p + TA - TB)
//--- = RB^T RA p + RB^T (TA - TB)
//--- So
//--- R = RB^T RA
//--- T = RB^T (TA - TB)
//---
Quaternion<T> q;
if(fabs(VT::one()- tiny::inner_prod(QA, QB)) < working_precision<R>())
{
q = Quaternion<T>::identity();
}
else
{
q = unit( prod( conj(QB), QA) );
}
return CoordSys<T>( rotate( conj(QB), (TA - TB)) , q);
}
template<typename T>
inline CoordSys<T> model_update(CoordSys<T> const & A, CoordSys<T> const & B)
{
return model_update(A.T(),A.Q(),B.T(),B.Q());
}
template<typename T>
inline std::ostream & operator<< (std::ostream & o, CoordSys<T> const & C)
{
o << "[" << C.T() << "," << C.Q() << "]";
return o;
}
template<typename T>
inline std::istream & operator>>(std::istream & i, CoordSys<T> & C)
{
char dummy;
i >> dummy;
i >> C.T();
i >> dummy;
i >> C.Q();
i >> dummy;
return i;
}
} // namespace tiny
//TINY_COORDSYS_FUNCTIONS_H
#endif
| 27.695652 | 135 | 0.497253 | [
"vector",
"model",
"transform"
] |
63a8d81989cf8ae2a5d6157d7a130a99c82dceb0 | 1,246 | h | C | Engine/Source/Runtime/Engine/Public/SceneViewExtension.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Engine/Public/SceneViewExtension.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Engine/Public/SceneViewExtension.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
/*=============================================================================
SceneViewExtension.h: Allow changing the view parameters on the render thread
=============================================================================*/
#pragma once
class ISceneViewExtension
{
public:
/**
* Called on game thread when creating the view family.
*/
virtual void SetupViewFamily(FSceneViewFamily& InViewFamily) = 0;
/**
* Called on game thread when creating the view.
*/
virtual void SetupView(FSceneViewFamily& InViewFamily, FSceneView& InView) = 0;
/**
* Called on game thread when view family is about to be rendered.
*/
virtual void BeginRenderViewFamily(FSceneViewFamily& InViewFamily) = 0;
/**
* Called on render thread at the start of rendering.
*/
virtual void PreRenderViewFamily_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneViewFamily& InViewFamily) = 0;
/**
* Called on render thread at the start of rendering, for each view, after PreRenderViewFamily_RenderThread call.
*/
virtual void PreRenderView_RenderThread(FRHICommandListImmediate& RHICmdList, FSceneView& InView) = 0;
};
| 33.675676 | 124 | 0.635634 | [
"render"
] |
63ad179004ed556c07cc1be54c69756155fcaade | 3,746 | h | C | src/models/common/namedlist.h | undisbeliever/untech-editor | 8598097baf6b2ac0b5580bc000e9adc3bf682043 | [
"MIT"
] | 13 | 2016-05-02T09:00:42.000Z | 2020-11-07T11:21:07.000Z | src/models/common/namedlist.h | undisbeliever/untech-editor | 8598097baf6b2ac0b5580bc000e9adc3bf682043 | [
"MIT"
] | 3 | 2016-09-28T13:36:29.000Z | 2020-12-22T12:22:43.000Z | src/models/common/namedlist.h | undisbeliever/untech-editor | 8598097baf6b2ac0b5580bc000e9adc3bf682043 | [
"MIT"
] | 1 | 2016-05-08T09:26:01.000Z | 2016-05-08T09:26:01.000Z | /*
* This file is part of the UnTech Editor Suite.
* Copyright (c) 2016 - 2021, Marcus Rowe <undisbeliever@gmail.com>.
* Distributed under The MIT License: https://opensource.org/licenses/MIT
*/
#pragma once
#include "idstring.h"
#include "iterators.h"
#include "optional.h"
#include "vector-helpers.h"
#include <cassert>
#include <climits>
#include <memory>
#include <string>
#include <vector>
namespace UnTech {
template <typename T>
class NamedList {
public:
using container = typename std::vector<T>;
using value_type = T;
using iterator = typename container::iterator;
using const_iterator = typename container::const_iterator;
using size_type = typename container::size_type;
private:
container _list;
public:
NamedList() = default;
~NamedList() = default;
NamedList(const NamedList&) = default;
NamedList(NamedList&&) = default;
NamedList& operator=(const NamedList& other) = default;
NamedList& operator=(NamedList&& other) = default;
bool empty() const { return _list.empty(); }
size_type size() const { return _list.size(); }
// returns INT_MAX if name is not found
size_type indexOf(const std::string& name) const
{
for (const auto [i, item] : const_enumerate(_list)) {
if (item.name == name) {
return i;
}
}
return INT_MAX;
}
// NOTE: pointer may be null
// pointer is valid until item is removed or replaced
optional<T&> find(const std::string& name)
{
for (T& i : _list) {
if (i.name == name) {
return i;
}
}
return {};
}
// NOTE: pointer may be null
// pointer is valid until item is removed or replaced
optional<const T&> find(const std::string& name) const
{
for (const T& i : _list) {
if (i.name == name) {
return i;
}
}
return {};
}
// pointer is valid until item is removed or replaced
T& at(size_type index) { return _list.at(index); }
const T& at(size_type index) const { return _list.at(index); }
iterator begin() { return _list.begin(); }
iterator end() { return _list.end(); }
const_iterator begin() const { return _list.begin(); }
const_iterator end() const { return _list.end(); }
const_iterator cbegin() const { return _list.cbegin(); }
const_iterator cend() const { return _list.cend(); }
T& front() { return _list.front(); }
T& back() { return _list.back(); }
const T& front() const { return _list.front(); }
const T& back() const { return _list.back(); }
void resize(size_type n) { _list.resize(n); }
void reserve(size_type capacity) { _list.reserve(capacity); }
void emplace_back()
{
_list.emplace_back();
}
void insert_back()
{
_list.emplace_back();
}
void insert_back(const T& v)
{
_list.push_back(v);
}
void insert_back(T&& v)
{
_list.push_back(std::move(v));
}
void insert(size_type index, const T& v)
{
assert(index <= _list.size());
_list.emplace(_list.begin() + index, v);
}
void remove(size_type index)
{
assert(index < _list.size());
_list.erase(_list.begin() + index);
}
void moveItem(size_type from, size_type to)
{
moveVectorItem(from, to, _list);
}
void insert(const_iterator it, const T& value) { _list.insert(it, value); }
void erase(const_iterator it) { _list.erase(it); }
bool operator==(const NamedList& o) const
{
return _list == o._list;
}
bool operator!=(const NamedList& o) const { return !(*this == o); }
};
}
| 25.482993 | 79 | 0.596636 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.